Index: clang/.clang-format =================================================================== --- clang/.clang-format +++ clang/.clang-format @@ -1 +1,3 @@ BasedOnStyle: LLVM +QualifierAlignment: Custom +QualifierOrder: [ inline, static, type, const, volatile, restrict ] Index: clang/docs/ClangFormatStyleOptions.rst =================================================================== --- clang/docs/ClangFormatStyleOptions.rst +++ clang/docs/ClangFormatStyleOptions.rst @@ -3225,6 +3225,73 @@ +**QualifierAlignment** (``QualifierAlignmentStyle``) + Different ways to arrange const/volatile qualifiers. + + Possible values: + + * ``QAS_Leave`` (in configuration: ``Leave``) + Don't change specifiers/qualifier to either Left or Right alignment + + .. code-block:: c++ + + int const a; + const int *a; + + * ``QAS_Left`` (in configuration: ``Left``) + Change specifiers/qualifiers to be Left aligned. + + .. code-block:: c++ + + const int a; + const int *a; + + * ``QAS_Right`` (in configuration: ``Right``) + Change specifiers/qualifiers to be Right aligned. + + .. code-block:: c++ + + int const a; + int const *a; + + * ``QAS_Custom`` (in configuration: ``Custom``) + Change specifiers/qualifiers to be aligned based on QualfierOrder. + With: + + .. code-block:: yaml + + QualifierOrder: ['inline', 'static' , '', 'const'] + + + .. code-block:: c++ + + + int const a; + int const *a; + + + +**QualifierOrder** (``std::vector``) + The Order in which the qualifiers appear. + Order is a an array can contain any of the following + + * const + * inline + * static + * constexpr + * volatile + * restrict + * type + + Note: it MUST contain 'type'. + Items to the left of type will be aligned in the order supplied. + Items to the right of type will be aligned in the order supplied. + + + .. code-block:: yaml + + QualifierOrder: ['inline', 'static', 'type', 'const', 'volatile' ] + **RawStringFormats** (``std::vector``) Defines hints for detecting supported languages code blocks in raw strings. Index: clang/docs/ReleaseNotes.rst =================================================================== --- clang/docs/ReleaseNotes.rst +++ clang/docs/ReleaseNotes.rst @@ -188,6 +188,16 @@ - Option ``AllowShortEnumsOnASingleLine: false`` has been improved, it now correctly places the opening brace according to ``BraceWrapping.AfterEnum``. +- Option ``QualifierAligment`` has been added in order to auto-arrange the + positioning of specifiers/qualifiers + `const` `volatile` `static` `inline` `constexpr` `restrict` + in variable and parameter declarations to be either ``Right`` aligned + or ``Left`` aligned or ``Custom`` using ``QualifierOrder``. + +- Option ``QualifierOrder`` has been added to allow the order + `const` `volatile` `static` `inline` `constexpr` `restrict` + to be controlled relative to the ``. + libclang -------- Index: clang/include/clang/Format/Format.h =================================================================== --- clang/include/clang/Format/Format.h +++ clang/include/clang/Format/Format.h @@ -40,7 +40,11 @@ Success = 0, Error, Unsuitable, - BinPackTrailingCommaConflict + BinPackTrailingCommaConflict, + InvalidQualifierSpecified, + DuplicateQualifierSpecified, + MissingQualifierType, + MissingQualifierOrder }; class ParseErrorCategory final : public std::error_category { public: @@ -1819,6 +1823,63 @@ /// \endcode std::string CommentPragmas; + /// Different const/volatile qualifier alignment styles. + enum QualifierAlignmentStyle { + /// Don't change specifiers/qualifier to either Left or Right alignment + /// \code + /// int const a; + /// const int *a; + /// \endcode + QAS_Leave, + /// Change specifiers/qualifiers to be Left aligned. + /// \code + /// const int a; + /// const int *a; + /// \endcode + QAS_Left, + /// Change specifiers/qualifiers to be Right aligned. + /// \code + /// int const a; + /// int const *a; + /// \endcode + QAS_Right, + /// Change specifiers/qualifiers to be aligned based on QualfierOrder. + /// With: + /// \code{.yaml} + /// QualifierOrder: ['inline', 'static' , '', 'const'] + /// \endcode + /// + /// \code + /// + /// int const a; + /// int const *a; + /// \endcode + QAS_Custom + }; + + /// Different ways to arrange const/volatile qualifiers. + QualifierAlignmentStyle QualifierAlignment; + + /// The Order in which the qualifiers appear. + /// Order is a an array can contain any of the following + /// + /// * const + /// * inline + /// * static + /// * constexpr + /// * volatile + /// * restrict + /// * type + /// + /// Note: it MUST contain 'type'. + /// Items to the left of type will be aligned in the order supplied. + /// Items to the right of type will be aligned in the order supplied. + /// + /// \code{.yaml} + /// QualifierOrder: ['inline', 'static', 'type', 'const', 'volatile' ] + /// \endcode + std::vector QualifierOrder; + /// Different ways to break inheritance list. enum BreakInheritanceListStyle : unsigned char { /// Break inheritance list before the colon and after the commas. @@ -3496,6 +3557,8 @@ PenaltyBreakTemplateDeclaration == R.PenaltyBreakTemplateDeclaration && PointerAlignment == R.PointerAlignment && + QualifierAlignment == R.QualifierAlignment && + QualifierOrder == R.QualifierOrder && RawStringFormats == R.RawStringFormats && ReferenceAlignment == R.ReferenceAlignment && ShortNamespaceLines == R.ShortNamespaceLines && Index: clang/lib/AST/APValue.cpp =================================================================== --- clang/lib/AST/APValue.cpp +++ clang/lib/AST/APValue.cpp @@ -24,11 +24,11 @@ /// The identity of a type_info object depends on the canonical unqualified /// type only. -TypeInfoLValue::TypeInfoLValue(const Type *T) +TypeInfoLValue::TypeInfoLValue(Type const *T) : T(T->getCanonicalTypeUnqualified().getTypePtr()) {} void TypeInfoLValue::print(llvm::raw_ostream &Out, - const PrintingPolicy &Policy) const { + PrintingPolicy const &Policy) const { Out << "typeid("; QualType(getType(), 0).print(Out, Policy); Out << ")"; @@ -39,9 +39,9 @@ alignof(Type), "Type is insufficiently aligned"); -APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned V) +APValue::LValueBase::LValueBase(ValueDecl const *P, unsigned I, unsigned V) : Ptr(P ? cast(P->getCanonicalDecl()) : nullptr), Local{I, V} {} -APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V) +APValue::LValueBase::LValueBase(Expr const *P, unsigned I, unsigned V) : Ptr(P), Local{I, V} {} APValue::LValueBase APValue::LValueBase::getDynamicAlloc(DynamicAllocLValue LV, @@ -61,8 +61,9 @@ } QualType APValue::LValueBase::getType() const { - if (!*this) return QualType(); - if (const ValueDecl *D = dyn_cast()) { + if (!*this) + return QualType(); + if (ValueDecl const *D = dyn_cast()) { // FIXME: It's unclear where we're supposed to take the type from, and // this actually matters for arrays of unknown bound. Eg: // @@ -85,17 +86,17 @@ if (is()) return getDynamicAllocType(); - const Expr *Base = get(); + Expr const *Base = get(); // For a materialized temporary, the type of the temporary we materialized // may not be the type of the expression. - if (const MaterializeTemporaryExpr *MTE = + if (MaterializeTemporaryExpr const *MTE = clang::dyn_cast(Base)) { - SmallVector CommaLHSs; + SmallVector CommaLHSs; SmallVector Adjustments; - const Expr *Temp = MTE->getSubExpr(); - const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs, - Adjustments); + Expr const *Temp = MTE->getSubExpr(); + Expr const *Inner = + Temp->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); // Keep any cv-qualifiers from the reference if we generated a temporary // for it directly. Otherwise use the type after adjustment. if (!Adjustments.empty()) @@ -133,8 +134,8 @@ } namespace clang { -bool operator==(const APValue::LValueBase &LHS, - const APValue::LValueBase &RHS) { +bool operator==(APValue::LValueBase const &LHS, + APValue::LValueBase const &RHS) { if (LHS.Ptr != RHS.Ptr) return false; if (LHS.is() || LHS.is()) @@ -142,10 +143,10 @@ return LHS.Local.CallIndex == RHS.Local.CallIndex && LHS.Local.Version == RHS.Local.Version; } -} +} // namespace clang APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType BaseOrMember) { - if (const Decl *D = BaseOrMember.getPointer()) + if (Decl const *D = BaseOrMember.getPointer()) BaseOrMember.setPointer(D->getCanonicalDecl()); Value = reinterpret_cast(BaseOrMember.getOpaqueValue()); } @@ -156,70 +157,66 @@ APValue::LValuePathSerializationHelper::LValuePathSerializationHelper( ArrayRef Path, QualType ElemTy) - : ElemTy((const void *)ElemTy.getTypePtrOrNull()), Path(Path) {} + : ElemTy((void const *)ElemTy.getTypePtrOrNull()), Path(Path) {} QualType APValue::LValuePathSerializationHelper::getType() { return QualType::getFromOpaquePtr(ElemTy); } namespace { - struct LVBase { - APValue::LValueBase Base; - CharUnits Offset; - unsigned PathLength; - bool IsNullPtr : 1; - bool IsOnePastTheEnd : 1; - }; -} +struct LVBase { + APValue::LValueBase Base; + CharUnits Offset; + unsigned PathLength; + bool IsNullPtr : 1; + bool IsOnePastTheEnd : 1; +}; +} // namespace void *APValue::LValueBase::getOpaqueValue() const { return Ptr.getOpaqueValue(); } -bool APValue::LValueBase::isNull() const { - return Ptr.isNull(); -} +bool APValue::LValueBase::isNull() const { return Ptr.isNull(); } -APValue::LValueBase::operator bool () const { - return static_cast(Ptr); -} +APValue::LValueBase::operator bool() const { return static_cast(Ptr); } clang::APValue::LValueBase llvm::DenseMapInfo::getEmptyKey() { clang::APValue::LValueBase B; - B.Ptr = DenseMapInfo::getEmptyKey(); + B.Ptr = DenseMapInfo::getEmptyKey(); return B; } clang::APValue::LValueBase llvm::DenseMapInfo::getTombstoneKey() { clang::APValue::LValueBase B; - B.Ptr = DenseMapInfo::getTombstoneKey(); + B.Ptr = DenseMapInfo::getTombstoneKey(); return B; } namespace clang { -llvm::hash_code hash_value(const APValue::LValueBase &Base) { +llvm::hash_code hash_value(APValue::LValueBase const &Base) { if (Base.is() || Base.is()) return llvm::hash_value(Base.getOpaqueValue()); return llvm::hash_combine(Base.getOpaqueValue(), Base.getCallIndex(), Base.getVersion()); } -} +} // namespace clang unsigned llvm::DenseMapInfo::getHashValue( - const clang::APValue::LValueBase &Base) { + clang::APValue::LValueBase const &Base) { return hash_value(Base); } bool llvm::DenseMapInfo::isEqual( - const clang::APValue::LValueBase &LHS, - const clang::APValue::LValueBase &RHS) { + clang::APValue::LValueBase const &LHS, + clang::APValue::LValueBase const &RHS) { return LHS == RHS; } struct APValue::LV : LVBase { - static const unsigned InlinePathSpace = + static unsigned const InlinePathSpace = (DataSize - sizeof(LVBase)) / sizeof(LValuePathEntry); /// Path - The sequence of base classes, fields and array indices to follow to @@ -237,7 +234,7 @@ if (Length == PathLength) return; if (hasPathPtr()) - delete [] PathPtr; + delete[] PathPtr; PathLength = Length; if (hasPathPtr()) PathPtr = new LValuePathEntry[Length]; @@ -247,22 +244,22 @@ bool hasPathPtr() const { return hasPath() && PathLength > InlinePathSpace; } LValuePathEntry *getPath() { return hasPathPtr() ? PathPtr : Path; } - const LValuePathEntry *getPath() const { + LValuePathEntry const *getPath() const { return hasPathPtr() ? PathPtr : Path; } }; namespace { - struct MemberPointerBase { - llvm::PointerIntPair MemberAndIsDerivedMember; - unsigned PathLength; - }; -} +struct MemberPointerBase { + llvm::PointerIntPair MemberAndIsDerivedMember; + unsigned PathLength; +}; +} // namespace struct APValue::MemberPointerData : MemberPointerBase { - static const unsigned InlinePathSpace = - (DataSize - sizeof(MemberPointerBase)) / sizeof(const CXXRecordDecl*); - typedef const CXXRecordDecl *PathElem; + static unsigned const InlinePathSpace = + (DataSize - sizeof(MemberPointerBase)) / sizeof(CXXRecordDecl const *); + typedef CXXRecordDecl const *PathElem; union { PathElem Path[InlinePathSpace]; PathElem *PathPtr; @@ -275,7 +272,7 @@ if (Length == PathLength) return; if (hasPathPtr()) - delete [] PathPtr; + delete[] PathPtr; PathLength = Length; if (hasPathPtr()) PathPtr = new PathElem[Length]; @@ -284,31 +281,25 @@ bool hasPathPtr() const { return PathLength > InlinePathSpace; } PathElem *getPath() { return hasPathPtr() ? PathPtr : Path; } - const PathElem *getPath() const { - return hasPathPtr() ? PathPtr : Path; - } + PathElem const *getPath() const { return hasPathPtr() ? PathPtr : Path; } }; // FIXME: Reduce the malloc traffic here. -APValue::Arr::Arr(unsigned NumElts, unsigned Size) : - Elts(new APValue[NumElts + (NumElts != Size ? 1 : 0)]), - NumElts(NumElts), ArrSize(Size) {} -APValue::Arr::~Arr() { delete [] Elts; } +APValue::Arr::Arr(unsigned NumElts, unsigned Size) + : Elts(new APValue[NumElts + (NumElts != Size ? 1 : 0)]), NumElts(NumElts), + ArrSize(Size) {} +APValue::Arr::~Arr() { delete[] Elts; } -APValue::StructData::StructData(unsigned NumBases, unsigned NumFields) : - Elts(new APValue[NumBases+NumFields]), - NumBases(NumBases), NumFields(NumFields) {} -APValue::StructData::~StructData() { - delete [] Elts; -} +APValue::StructData::StructData(unsigned NumBases, unsigned NumFields) + : Elts(new APValue[NumBases + NumFields]), NumBases(NumBases), + NumFields(NumFields) {} +APValue::StructData::~StructData() { delete[] Elts; } APValue::UnionData::UnionData() : Field(nullptr), Value(new APValue) {} -APValue::UnionData::~UnionData () { - delete Value; -} +APValue::UnionData::~UnionData() { delete Value; } -APValue::APValue(const APValue &RHS) : Kind(None) { +APValue::APValue(APValue const &RHS) : Kind(None) { switch (RHS.getKind()) { case None: case Indeterminate: @@ -329,7 +320,7 @@ } case Vector: MakeVector(); - setVector(((const Vec *)(const char *)&RHS.Data)->Elts, + setVector(((Vec const *)(char const *)&RHS.Data)->Elts, RHS.getVectorLength()); break; case ComplexInt: @@ -383,7 +374,7 @@ RHS.Kind = None; } -APValue &APValue::operator=(const APValue &RHS) { +APValue &APValue::operator=(APValue const &RHS) { if (this != &RHS) *this = APValue(RHS); return *this; @@ -458,7 +449,7 @@ case LValue: return reinterpret_cast(&Data)->hasPathPtr(); case MemberPointer: - return reinterpret_cast(&Data)->hasPathPtr(); + return reinterpret_cast(&Data)->hasPathPtr(); } llvm_unreachable("Unknown APValue kind!"); } @@ -469,7 +460,7 @@ } /// Profile the value of an APInt, excluding its bit-width. -static void profileIntValue(llvm::FoldingSetNodeID &ID, const llvm::APInt &V) { +static void profileIntValue(llvm::FoldingSetNodeID &ID, llvm::APInt const &V) { for (unsigned I = 0, N = V.getBitWidth(); I < N; I += 32) ID.AddInteger((uint32_t)V.extractBitsAsZExtValue(std::min(32u, N - I), I)); } @@ -609,7 +600,7 @@ case MemberPointer: ID.AddPointer(getMemberPointerDecl()); ID.AddInteger(isMemberPointerToDerivedMember()); - for (const CXXRecordDecl *D : getMemberPointerPath()) + for (CXXRecordDecl const *D : getMemberPointerPath()) ID.AddPointer(D); return; } @@ -617,7 +608,7 @@ llvm_unreachable("Unknown APValue kind!"); } -static double GetApproxValue(const llvm::APFloat &F) { +static double GetApproxValue(llvm::APFloat const &F) { llvm::APFloat V = F; bool ignored; V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven, @@ -625,13 +616,13 @@ return V.convertToDouble(); } -void APValue::printPretty(raw_ostream &Out, const ASTContext &Ctx, +void APValue::printPretty(raw_ostream &Out, ASTContext const &Ctx, QualType Ty) const { printPretty(Out, Ctx.getPrintingPolicy(), Ty, &Ctx); } -void APValue::printPretty(raw_ostream &Out, const PrintingPolicy &Policy, - QualType Ty, const ASTContext *Ctx) const { +void APValue::printPretty(raw_ostream &Out, PrintingPolicy const &Policy, + QualType Ty, ASTContext const *Ctx) const { // There are no objects of type 'void', but values of this type can be // returned from functions. if (Ty->isVoidType()) { @@ -678,8 +669,8 @@ return; case APValue::LValue: { bool IsReference = Ty->isReferenceType(); - QualType InnerTy - = IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType(); + QualType InnerTy = + IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType(); if (InnerTy.isNull()) InnerTy = Ty; @@ -713,18 +704,17 @@ Out << '&'; } - if (const ValueDecl *VD = Base.dyn_cast()) + if (ValueDecl const *VD = Base.dyn_cast()) Out << *VD; else if (TypeInfoLValue TI = Base.dyn_cast()) { TI.print(Out, Policy); } else if (DynamicAllocLValue DA = Base.dyn_cast()) { - Out << "{*new " - << Base.getDynamicAllocType().stream(Policy) << "#" + Out << "{*new " << Base.getDynamicAllocType().stream(Policy) << "#" << DA.getIndex() << "}"; } else { - assert(Base.get() != nullptr && + assert(Base.get() != nullptr && "Expecting non-null Expr"); - Base.get()->printPretty(Out, nullptr, Policy); + Base.get()->printPretty(Out, nullptr, Policy); } if (!O.isZero()) { @@ -742,7 +732,7 @@ Out << "*(&"; QualType ElemTy = Base.getType(); - if (const ValueDecl *VD = Base.dyn_cast()) { + if (ValueDecl const *VD = Base.dyn_cast()) { Out << *VD; } else if (TypeInfoLValue TI = Base.dyn_cast()) { TI.print(Out, Policy); @@ -750,24 +740,24 @@ Out << "{*new " << Base.getDynamicAllocType().stream(Policy) << "#" << DA.getIndex() << "}"; } else { - const Expr *E = Base.get(); + Expr const *E = Base.get(); assert(E != nullptr && "Expecting non-null Expr"); E->printPretty(Out, nullptr, Policy); } ArrayRef Path = getLValuePath(); - const CXXRecordDecl *CastToBase = nullptr; + CXXRecordDecl const *CastToBase = nullptr; for (unsigned I = 0, N = Path.size(); I != N; ++I) { if (ElemTy->isRecordType()) { // The lvalue refers to a class type, so the next path entry is a base // or member. - const Decl *BaseOrMember = Path[I].getAsBaseOrMember().getPointer(); - if (const CXXRecordDecl *RD = dyn_cast(BaseOrMember)) { + Decl const *BaseOrMember = Path[I].getAsBaseOrMember().getPointer(); + if (CXXRecordDecl const *RD = dyn_cast(BaseOrMember)) { CastToBase = RD; // Leave ElemTy referring to the most-derived class. The actual type // doesn't matter except for array types. } else { - const ValueDecl *VD = cast(BaseOrMember); + ValueDecl const *VD = cast(BaseOrMember); Out << "."; if (CastToBase) Out << *CastToBase << "::"; @@ -792,7 +782,7 @@ return; } case APValue::Array: { - const ArrayType *AT = Ty->castAsArrayTypeUnsafe(); + ArrayType const *AT = Ty->castAsArrayTypeUnsafe(); QualType ElemTy = AT->getElementType(); Out << '{'; if (unsigned N = getArrayInitializedElts()) { @@ -812,10 +802,10 @@ } case APValue::Struct: { Out << '{'; - const RecordDecl *RD = Ty->castAs()->getDecl(); + RecordDecl const *RD = Ty->castAs()->getDecl(); bool First = true; if (unsigned N = getStructNumBases()) { - const CXXRecordDecl *CD = cast(RD); + CXXRecordDecl const *CD = cast(RD); CXXRecordDecl::base_class_const_iterator BI = CD->bases_begin(); for (unsigned I = 0; I != N; ++I, ++BI) { assert(BI != CD->bases_end()); @@ -825,12 +815,13 @@ First = false; } } - for (const auto *FI : RD->fields()) { + for (auto const *FI : RD->fields()) { if (!First) Out << ", "; - if (FI->isUnnamedBitfield()) continue; - getStructField(FI->getFieldIndex()). - printPretty(Out, Policy, FI->getType(), Ctx); + if (FI->isUnnamedBitfield()) + continue; + getStructField(FI->getFieldIndex()) + .printPretty(Out, Policy, FI->getType(), Ctx); First = false; } Out << '}'; @@ -838,7 +829,7 @@ } case APValue::Union: Out << '{'; - if (const FieldDecl *FD = getUnionField()) { + if (FieldDecl const *FD = getUnionField()) { Out << "." << *FD << " = "; getUnionValue().printPretty(Out, Policy, FD->getType(), Ctx); } @@ -847,7 +838,7 @@ case APValue::MemberPointer: // FIXME: This is not enough to unambiguously identify the member in a // multiple-inheritance scenario. - if (const ValueDecl *VD = getMemberPointerDecl()) { + if (ValueDecl const *VD = getMemberPointerDecl()) { Out << '&' << *cast(VD->getDeclContext()) << "::" << *VD; return; } @@ -862,7 +853,7 @@ llvm_unreachable("Unknown APValue kind!"); } -std::string APValue::getAsString(const ASTContext &Ctx, QualType Ty) const { +std::string APValue::getAsString(ASTContext const &Ctx, QualType Ty) const { std::string Result; llvm::raw_string_ostream Out(Result); printPretty(Out, Ctx, Ty); @@ -871,7 +862,7 @@ } bool APValue::toIntegralConstant(APSInt &Result, QualType SrcTy, - const ASTContext &Ctx) const { + ASTContext const &Ctx) const { if (isInt()) { Result = getInt(); return true; @@ -892,12 +883,12 @@ const APValue::LValueBase APValue::getLValueBase() const { assert(isLValue() && "Invalid accessor"); - return ((const LV *)(const void *)&Data)->Base; + return ((const LV *)(void const *)&Data)->Base; } bool APValue::isLValueOnePastTheEnd() const { assert(isLValue() && "Invalid accessor"); - return ((const LV *)(const void *)&Data)->IsOnePastTheEnd; + return ((const LV *)(void const *)&Data)->IsOnePastTheEnd; } CharUnits &APValue::getLValueOffset() { @@ -907,31 +898,31 @@ bool APValue::hasLValuePath() const { assert(isLValue() && "Invalid accessor"); - return ((const LV *)(const char *)&Data)->hasPath(); + return ((const LV *)(char const *)&Data)->hasPath(); } ArrayRef APValue::getLValuePath() const { assert(isLValue() && hasLValuePath() && "Invalid accessor"); - const LV &LVal = *((const LV *)(const char *)&Data); + const LV &LVal = *((const LV *)(char const *)&Data); return llvm::makeArrayRef(LVal.getPath(), LVal.PathLength); } unsigned APValue::getLValueCallIndex() const { assert(isLValue() && "Invalid accessor"); - return ((const LV *)(const char *)&Data)->Base.getCallIndex(); + return ((const LV *)(char const *)&Data)->Base.getCallIndex(); } unsigned APValue::getLValueVersion() const { assert(isLValue() && "Invalid accessor"); - return ((const LV *)(const char *)&Data)->Base.getVersion(); + return ((const LV *)(char const *)&Data)->Base.getVersion(); } bool APValue::isNullPointer() const { assert(isLValue() && "Invalid usage"); - return ((const LV *)(const char *)&Data)->IsNullPtr; + return ((const LV *)(char const *)&Data)->IsNullPtr; } -void APValue::setLValue(LValueBase B, const CharUnits &O, NoLValuePath, +void APValue::setLValue(LValueBase B, CharUnits const &O, NoLValuePath, bool IsNullPtr) { assert(isLValue() && "Invalid accessor"); LV &LVal = *((LV *)(char *)&Data); @@ -943,7 +934,7 @@ } MutableArrayRef -APValue::setLValueUninit(LValueBase B, const CharUnits &O, unsigned Size, +APValue::setLValueUninit(LValueBase B, CharUnits const &O, unsigned Size, bool IsOnePastTheEnd, bool IsNullPtr) { assert(isLValue() && "Invalid accessor"); LV &LVal = *((LV *)(char *)&Data); @@ -955,7 +946,7 @@ return {LVal.getPath(), Size}; } -void APValue::setLValue(LValueBase B, const CharUnits &O, +void APValue::setLValue(LValueBase B, CharUnits const &O, ArrayRef Path, bool IsOnePastTheEnd, bool IsNullPtr) { MutableArrayRef InternalPath = @@ -966,31 +957,31 @@ } } -void APValue::setUnion(const FieldDecl *Field, const APValue &Value) { +void APValue::setUnion(FieldDecl const *Field, APValue const &Value) { assert(isUnion() && "Invalid accessor"); ((UnionData *)(char *)&Data)->Field = Field ? Field->getCanonicalDecl() : nullptr; *((UnionData *)(char *)&Data)->Value = Value; } -const ValueDecl *APValue::getMemberPointerDecl() const { +ValueDecl const *APValue::getMemberPointerDecl() const { assert(isMemberPointer() && "Invalid accessor"); - const MemberPointerData &MPD = - *((const MemberPointerData *)(const char *)&Data); + MemberPointerData const &MPD = + *((MemberPointerData const *)(char const *)&Data); return MPD.MemberAndIsDerivedMember.getPointer(); } bool APValue::isMemberPointerToDerivedMember() const { assert(isMemberPointer() && "Invalid accessor"); - const MemberPointerData &MPD = - *((const MemberPointerData *)(const char *)&Data); + MemberPointerData const &MPD = + *((MemberPointerData const *)(char const *)&Data); return MPD.MemberAndIsDerivedMember.getInt(); } -ArrayRef APValue::getMemberPointerPath() const { +ArrayRef APValue::getMemberPointerPath() const { assert(isMemberPointer() && "Invalid accessor"); - const MemberPointerData &MPD = - *((const MemberPointerData *)(const char *)&Data); + MemberPointerData const &MPD = + *((MemberPointerData const *)(char const *)&Data); return llvm::makeArrayRef(MPD.getPath(), MPD.PathLength); } @@ -1008,11 +999,11 @@ } MutableArrayRef -setLValueUninit(APValue::LValueBase B, const CharUnits &O, unsigned Size, +setLValueUninit(APValue::LValueBase B, CharUnits const &O, unsigned Size, bool OnePastTheEnd, bool IsNullPtr); -MutableArrayRef -APValue::setMemberPointerUninit(const ValueDecl *Member, bool IsDerivedMember, +MutableArrayRef +APValue::setMemberPointerUninit(ValueDecl const *Member, bool IsDerivedMember, unsigned Size) { assert(isAbsent() && "Bad state change"); MemberPointerData *MPD = new ((void *)(char *)&Data) MemberPointerData; @@ -1024,15 +1015,15 @@ return {MPD->getPath(), MPD->PathLength}; } -void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember, - ArrayRef Path) { - MutableArrayRef InternalPath = +void APValue::MakeMemberPointer(ValueDecl const *Member, bool IsDerivedMember, + ArrayRef Path) { + MutableArrayRef InternalPath = setMemberPointerUninit(Member, IsDerivedMember, Path.size()); for (unsigned I = 0; I != Path.size(); ++I) InternalPath[I] = Path[I]->getCanonicalDecl(); } -LinkageInfo LinkageComputer::getLVForValue(const APValue &V, +LinkageInfo LinkageComputer::getLVForValue(APValue const &V, LVComputationKind computation) { LinkageInfo LV = LinkageInfo::external(); @@ -1040,7 +1031,7 @@ LV.merge(MergeLV); return LV.getLinkage() == InternalLinkage; }; - auto Merge = [&](const APValue &V) { + auto Merge = [&](APValue const &V) { return MergeLV(getLVForValue(V, computation)); }; @@ -1087,14 +1078,14 @@ case APValue::LValue: { if (!V.getLValueBase()) { // Null or absolute address: this is external. - } else if (const auto *VD = - V.getLValueBase().dyn_cast()) { + } else if (auto const *VD = + V.getLValueBase().dyn_cast()) { if (VD && MergeLV(getLVForDecl(VD, computation))) break; - } else if (const auto TI = V.getLValueBase().dyn_cast()) { + } else if (auto const TI = V.getLValueBase().dyn_cast()) { if (MergeLV(getLVForType(*TI.getType(), computation))) break; - } else if (const Expr *E = V.getLValueBase().dyn_cast()) { + } else if (Expr const *E = V.getLValueBase().dyn_cast()) { // Almost all expression bases are internal. The exception is // lifetime-extended temporaries. // FIXME: These should be modeled as having the @@ -1117,7 +1108,7 @@ } case APValue::MemberPointer: - if (const NamedDecl *D = V.getMemberPointerDecl()) + if (NamedDecl const *D = V.getMemberPointerDecl()) MergeLV(getLVForDecl(D, computation)); // Note that we could have a base-to-derived conversion here to a member of // a derived class with less linkage/visibility. That's covered by the Index: clang/lib/AST/ASTConcept.cpp =================================================================== --- clang/lib/AST/ASTConcept.cpp +++ clang/lib/AST/ASTConcept.cpp @@ -19,17 +19,17 @@ #include "llvm/ADT/FoldingSet.h" using namespace clang; -ASTConstraintSatisfaction::ASTConstraintSatisfaction(const ASTContext &C, - const ConstraintSatisfaction &Satisfaction): - NumRecords{Satisfaction.Details.size()}, - IsSatisfied{Satisfaction.IsSatisfied} { +ASTConstraintSatisfaction::ASTConstraintSatisfaction( + ASTContext const &C, ConstraintSatisfaction const &Satisfaction) + : NumRecords{Satisfaction.Details.size()}, IsSatisfied{ + Satisfaction.IsSatisfied} { for (unsigned I = 0; I < NumRecords; ++I) { auto &Detail = Satisfaction.Details[I]; if (Detail.second.is()) new (getTrailingObjects() + I) - UnsatisfiedConstraintRecord{Detail.first, - UnsatisfiedConstraintRecord::second_type( - Detail.second.get())}; + UnsatisfiedConstraintRecord{Detail.first, + UnsatisfiedConstraintRecord::second_type( + Detail.second.get())}; else { auto &SubstitutionDiagnostic = *Detail.second.get *>(); @@ -38,28 +38,26 @@ memcpy(Mem, SubstitutionDiagnostic.second.data(), MessageSize); auto *NewSubstDiag = new (C) std::pair( SubstitutionDiagnostic.first, StringRef(Mem, MessageSize)); - new (getTrailingObjects() + I) - UnsatisfiedConstraintRecord{Detail.first, - UnsatisfiedConstraintRecord::second_type( - NewSubstDiag)}; + new (getTrailingObjects() + + I) UnsatisfiedConstraintRecord{ + Detail.first, UnsatisfiedConstraintRecord::second_type(NewSubstDiag)}; } } } - ASTConstraintSatisfaction * -ASTConstraintSatisfaction::Create(const ASTContext &C, - const ConstraintSatisfaction &Satisfaction) { - std::size_t size = - totalSizeToAlloc( - Satisfaction.Details.size()); +ASTConstraintSatisfaction::Create(ASTContext const &C, + ConstraintSatisfaction const &Satisfaction) { + std::size_t size = totalSizeToAlloc( + Satisfaction.Details.size()); void *Mem = C.Allocate(size, alignof(ASTConstraintSatisfaction)); return new (Mem) ASTConstraintSatisfaction(C, Satisfaction); } -void ConstraintSatisfaction::Profile( - llvm::FoldingSetNodeID &ID, const ASTContext &C, - const NamedDecl *ConstraintOwner, ArrayRef TemplateArgs) { +void ConstraintSatisfaction::Profile(llvm::FoldingSetNodeID &ID, + ASTContext const &C, + NamedDecl const *ConstraintOwner, + ArrayRef TemplateArgs) { ID.AddPointer(ConstraintOwner); ID.AddInteger(TemplateArgs.size()); for (auto &Arg : TemplateArgs) Index: clang/lib/AST/ASTConsumer.cpp =================================================================== --- clang/lib/AST/ASTConsumer.cpp +++ clang/lib/AST/ASTConsumer.cpp @@ -15,9 +15,7 @@ #include "clang/AST/DeclGroup.h" using namespace clang; -bool ASTConsumer::HandleTopLevelDecl(DeclGroupRef D) { - return true; -} +bool ASTConsumer::HandleTopLevelDecl(DeclGroupRef D) { return true; } void ASTConsumer::HandleInterestingDecl(DeclGroupRef D) { HandleTopLevelDecl(D); Index: clang/lib/AST/ASTContext.cpp =================================================================== --- clang/lib/AST/ASTContext.cpp +++ clang/lib/AST/ASTContext.cpp @@ -113,7 +113,7 @@ /// \returns location that is relevant when searching for Doc comments related /// to \p D. -static SourceLocation getDeclLocForCommentSearch(const Decl *D, +static SourceLocation getDeclLocForCommentSearch(Decl const *D, SourceManager &SourceMgr) { assert(D); @@ -122,34 +122,33 @@ return {}; // User can not attach documentation to implicit instantiations. - if (const auto *FD = dyn_cast(D)) { + if (auto const *FD = dyn_cast(D)) { if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return {}; } - if (const auto *VD = dyn_cast(D)) { + if (auto const *VD = dyn_cast(D)) { if (VD->isStaticDataMember() && VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return {}; } - if (const auto *CRD = dyn_cast(D)) { + if (auto const *CRD = dyn_cast(D)) { if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return {}; } - if (const auto *CTSD = dyn_cast(D)) { + if (auto const *CTSD = dyn_cast(D)) { TemplateSpecializationKind TSK = CTSD->getSpecializationKind(); - if (TSK == TSK_ImplicitInstantiation || - TSK == TSK_Undeclared) + if (TSK == TSK_ImplicitInstantiation || TSK == TSK_Undeclared) return {}; } - if (const auto *ED = dyn_cast(D)) { + if (auto const *ED = dyn_cast(D)) { if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) return {}; } - if (const auto *TD = dyn_cast(D)) { + if (auto const *TD = dyn_cast(D)) { // When tag declaration (but not definition!) is part of the // decl-specifier-seq of some other declaration, it doesn't get comment if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition()) @@ -161,8 +160,7 @@ // TODO: we could look up template parameter documentation in the template // documentation. - if (isa(D) || - isa(D) || + if (isa(D) || isa(D) || isa(D)) return {}; @@ -173,8 +171,7 @@ // For all other declarations multiple declarators are used quite frequently, // so we use the location of the identifier as the "declaration location". if (isa(D) || isa(D) || - isa(D) || - isa(D) || + isa(D) || isa(D) || isa(D) || // Allow association with Y across {} in `typedef struct X {} Y`. isa(D)) @@ -189,7 +186,7 @@ return D->getBeginLoc(); } - if (const auto *TD = dyn_cast(D)) { + if (auto const *TD = dyn_cast(D)) { // If location of the tag decl is inside a macro, but the spelling of // the tag name comes from a macro argument, it looks like a special // macro like NS_ENUM is being used to define the tag decl. In that @@ -204,8 +201,8 @@ } RawComment *ASTContext::getRawCommentForDeclNoCacheImpl( - const Decl *D, const SourceLocation RepresentativeLocForDecl, - const std::map &CommentsInTheFile) const { + Decl const *D, const SourceLocation RepresentativeLocForDecl, + std::map const &CommentsInTheFile) const { // If the declaration doesn't map directly to a location in a file, we // can't find the comment. if (RepresentativeLocForDecl.isInvalid() || @@ -259,13 +256,13 @@ return nullptr; // Decompose the end of the comment. - const unsigned CommentEndOffset = + unsigned const CommentEndOffset = Comments.getCommentEndOffset(CommentBeforeDecl); // Get the corresponding buffer. bool Invalid = false; - const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, - &Invalid).data(); + char const *Buffer = + SourceMgr.getBufferData(DeclLocDecomp.first, &Invalid).data(); if (Invalid) return nullptr; @@ -281,7 +278,7 @@ return CommentBeforeDecl; } -RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { +RawComment *ASTContext::getRawCommentForDeclNoCache(Decl const *D) const { const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr); // If the declaration doesn't map directly to a location in a file, we @@ -298,14 +295,14 @@ return nullptr; const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first; - const auto CommentsInThisFile = Comments.getCommentsInFile(File); + auto const CommentsInThisFile = Comments.getCommentsInFile(File); if (!CommentsInThisFile || CommentsInThisFile->empty()) return nullptr; return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile); } -void ASTContext::addComment(const RawComment &RC) { +void ASTContext::addComment(RawComment const &RC) { assert(LangOpts.RetainCommentsFromSystemHeaders || !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin())); Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc); @@ -314,10 +311,10 @@ /// If we have a 'templated' declaration for a template, adjust 'D' to /// refer to the actual template. /// If we have an implicit instantiation, adjust 'D' to refer to template. -static const Decl &adjustDeclToTemplate(const Decl &D) { - if (const auto *FD = dyn_cast(&D)) { +static Decl const &adjustDeclToTemplate(Decl const &D) { + if (auto const *FD = dyn_cast(&D)) { // Is this function declaration part of a function template? - if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) + if (FunctionTemplateDecl const *FTD = FD->getDescribedFunctionTemplate()) return *FTD; // Nothing to do if function is not an implicit instantiation. @@ -325,54 +322,54 @@ return D; // Function is an implicit instantiation of a function template? - if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate()) + if (FunctionTemplateDecl const *FTD = FD->getPrimaryTemplate()) return *FTD; // Function is instantiated from a member definition of a class template? - if (const FunctionDecl *MemberDecl = + if (FunctionDecl const *MemberDecl = FD->getInstantiatedFromMemberFunction()) return *MemberDecl; return D; } - if (const auto *VD = dyn_cast(&D)) { + if (auto const *VD = dyn_cast(&D)) { // Static data member is instantiated from a member definition of a class // template? if (VD->isStaticDataMember()) - if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember()) + if (VarDecl const *MemberDecl = VD->getInstantiatedFromStaticDataMember()) return *MemberDecl; return D; } - if (const auto *CRD = dyn_cast(&D)) { + if (auto const *CRD = dyn_cast(&D)) { // Is this class declaration part of a class template? - if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate()) + if (ClassTemplateDecl const *CTD = CRD->getDescribedClassTemplate()) return *CTD; // Class is an implicit instantiation of a class template or partial // specialization? - if (const auto *CTSD = dyn_cast(CRD)) { + if (auto const *CTSD = dyn_cast(CRD)) { if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation) return D; llvm::PointerUnion PU = CTSD->getSpecializedTemplateOrPartial(); return PU.is() - ? *static_cast(PU.get()) - : *static_cast( + ? *static_cast(PU.get()) + : *static_cast( PU.get()); } // Class is instantiated from a member definition of a class template? - if (const MemberSpecializationInfo *Info = + if (MemberSpecializationInfo const *Info = CRD->getMemberSpecializationInfo()) return *Info->getInstantiatedFrom(); return D; } - if (const auto *ED = dyn_cast(&D)) { + if (auto const *ED = dyn_cast(&D)) { // Enum is instantiated from a member definition of a class template? - if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum()) + if (EnumDecl const *MemberDecl = ED->getInstantiatedFromMemberEnum()) return *MemberDecl; return D; @@ -381,9 +378,9 @@ return D; } -const RawComment *ASTContext::getRawCommentForAnyRedecl( - const Decl *D, - const Decl **OriginalDecl) const { +RawComment const * +ASTContext::getRawCommentForAnyRedecl(Decl const *D, + Decl const **OriginalDecl) const { if (!D) { if (OriginalDecl) OriginalDecl = nullptr; @@ -403,7 +400,7 @@ } // Any comment attached to any redeclaration of D? - const Decl *CanonicalD = D->getCanonicalDecl(); + Decl const *CanonicalD = D->getCanonicalDecl(); if (!CanonicalD) return nullptr; @@ -421,14 +418,14 @@ // Any redeclarations of D that we haven't checked for comments yet? // We can't use DenseMap::iterator directly since it'd get invalid. - auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * { + auto LastCheckedRedecl = [this, CanonicalD]() -> Decl const * { auto LookupRes = CommentlessRedeclChains.find(CanonicalD); if (LookupRes != CommentlessRedeclChains.end()) return LookupRes->second; return nullptr; }(); - for (const auto Redecl : D->redecls()) { + for (auto const Redecl : D->redecls()) { assert(Redecl); // Skip all redeclarations that have been checked previously. if (LastCheckedRedecl) { @@ -437,7 +434,7 @@ } continue; } - const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl); + RawComment const *RedeclComment = getRawCommentForDeclNoCache(Redecl); if (RedeclComment) { cacheRawCommentForDecl(*Redecl, *RedeclComment); if (OriginalDecl) @@ -452,34 +449,34 @@ return nullptr; } -void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD, - const RawComment &Comment) const { +void ASTContext::cacheRawCommentForDecl(Decl const &OriginalD, + RawComment const &Comment) const { assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments); DeclRawComments.try_emplace(&OriginalD, &Comment); - const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl(); + Decl const *const CanonicalDecl = OriginalD.getCanonicalDecl(); RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD); CommentlessRedeclChains.erase(CanonicalDecl); } -static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod, - SmallVectorImpl &Redeclared) { - const DeclContext *DC = ObjCMethod->getDeclContext(); - if (const auto *IMD = dyn_cast(DC)) { - const ObjCInterfaceDecl *ID = IMD->getClassInterface(); +static void +addRedeclaredMethods(ObjCMethodDecl const *ObjCMethod, + SmallVectorImpl &Redeclared) { + DeclContext const *DC = ObjCMethod->getDeclContext(); + if (auto const *IMD = dyn_cast(DC)) { + ObjCInterfaceDecl const *ID = IMD->getClassInterface(); if (!ID) return; // Add redeclared method here. - for (const auto *Ext : ID->known_extensions()) { - if (ObjCMethodDecl *RedeclaredMethod = - Ext->getMethod(ObjCMethod->getSelector(), - ObjCMethod->isInstanceMethod())) + for (auto const *Ext : ID->known_extensions()) { + if (ObjCMethodDecl *RedeclaredMethod = Ext->getMethod( + ObjCMethod->getSelector(), ObjCMethod->isInstanceMethod())) Redeclared.push_back(RedeclaredMethod); } } } void ASTContext::attachCommentsToJustParsedDecls(ArrayRef Decls, - const Preprocessor *PP) { + Preprocessor const *PP) { if (Comments.empty() || Decls.empty()) return; @@ -510,7 +507,7 @@ // the lookahead in the lexer: we've consumed the semicolon and looked // ahead through comments. - for (const Decl *D : Decls) { + for (Decl const *D : Decls) { assert(D); if (D->isInvalidDecl()) continue; @@ -535,7 +532,7 @@ } comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC, - const Decl *D) const { + Decl const *D) const { auto *ThisDeclInfo = new (*this) comments::DeclInfo; ThisDeclInfo->CommentDecl = D; ThisDeclInfo->IsFilled = false; @@ -544,25 +541,24 @@ if (!ThisDeclInfo->TemplateParameters) ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters; comments::FullComment *CFC = - new (*this) comments::FullComment(FC->getBlocks(), - ThisDeclInfo); + new (*this) comments::FullComment(FC->getBlocks(), ThisDeclInfo); return CFC; } -comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const { - const RawComment *RC = getRawCommentForDeclNoCache(D); +comments::FullComment * +ASTContext::getLocalCommentForDeclUncached(Decl const *D) const { + RawComment const *RC = getRawCommentForDeclNoCache(D); return RC ? RC->parse(*this, nullptr, D) : nullptr; } -comments::FullComment *ASTContext::getCommentForDecl( - const Decl *D, - const Preprocessor *PP) const { +comments::FullComment * +ASTContext::getCommentForDecl(Decl const *D, Preprocessor const *PP) const { if (!D || D->isInvalidDecl()) return nullptr; D = &adjustDeclToTemplate(*D); - const Decl *Canonical = D->getCanonicalDecl(); - llvm::DenseMap::iterator Pos = + Decl const *Canonical = D->getCanonicalDecl(); + llvm::DenseMap::iterator Pos = ParsedComments.find(Canonical); if (Pos != ParsedComments.end()) { @@ -574,15 +570,15 @@ return Pos->second; } - const Decl *OriginalDecl = nullptr; + Decl const *OriginalDecl = nullptr; - const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); + RawComment const *RC = getRawCommentForAnyRedecl(D, &OriginalDecl); if (!RC) { if (isa(D) || isa(D)) { - SmallVector Overridden; - const auto *OMD = dyn_cast(D); + SmallVector Overridden; + auto const *OMD = dyn_cast(D); if (OMD && OMD->isPropertyAccessor()) - if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl()) + if (ObjCPropertyDecl const *PDecl = OMD->findPropertyDecl()) if (comments::FullComment *FC = getCommentForDecl(PDecl, PP)) return cloneFullComment(FC, D); if (OMD) @@ -591,55 +587,52 @@ for (unsigned i = 0, e = Overridden.size(); i < e; i++) if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP)) return cloneFullComment(FC, D); - } - else if (const auto *TD = dyn_cast(D)) { + } else if (auto const *TD = dyn_cast(D)) { // Attach any tag type's documentation to its typedef if latter // does not have one of its own. QualType QT = TD->getUnderlyingType(); - if (const auto *TT = QT->getAs()) - if (const Decl *TD = TT->getDecl()) + if (auto const *TT = QT->getAs()) + if (Decl const *TD = TT->getDecl()) if (comments::FullComment *FC = getCommentForDecl(TD, PP)) return cloneFullComment(FC, D); - } - else if (const auto *IC = dyn_cast(D)) { + } else if (auto const *IC = dyn_cast(D)) { while (IC->getSuperClass()) { IC = IC->getSuperClass(); if (comments::FullComment *FC = getCommentForDecl(IC, PP)) return cloneFullComment(FC, D); } - } - else if (const auto *CD = dyn_cast(D)) { - if (const ObjCInterfaceDecl *IC = CD->getClassInterface()) + } else if (auto const *CD = dyn_cast(D)) { + if (ObjCInterfaceDecl const *IC = CD->getClassInterface()) if (comments::FullComment *FC = getCommentForDecl(IC, PP)) return cloneFullComment(FC, D); - } - else if (const auto *RD = dyn_cast(D)) { + } else if (auto const *RD = dyn_cast(D)) { if (!(RD = RD->getDefinition())) return nullptr; // Check non-virtual bases. - for (const auto &I : RD->bases()) { + for (auto const &I : RD->bases()) { if (I.isVirtual() || (I.getAccessSpecifier() != AS_public)) continue; QualType Ty = I.getType(); if (Ty.isNull()) continue; - if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) { - if (!(NonVirtualBase= NonVirtualBase->getDefinition())) + if (CXXRecordDecl const *NonVirtualBase = Ty->getAsCXXRecordDecl()) { + if (!(NonVirtualBase = NonVirtualBase->getDefinition())) continue; - if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP)) + if (comments::FullComment *FC = + getCommentForDecl((NonVirtualBase), PP)) return cloneFullComment(FC, D); } } // Check virtual bases. - for (const auto &I : RD->vbases()) { + for (auto const &I : RD->vbases()) { if (I.getAccessSpecifier() != AS_public) continue; QualType Ty = I.getType(); if (Ty.isNull()) continue; - if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) { - if (!(VirtualBase= VirtualBase->getDefinition())) + if (CXXRecordDecl const *VirtualBase = Ty->getAsCXXRecordDecl()) { + if (!(VirtualBase = VirtualBase->getDefinition())) continue; if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP)) return cloneFullComment(FC, D); @@ -661,10 +654,9 @@ return FC; } -void -ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, - const ASTContext &C, - TemplateTemplateParmDecl *Parm) { +void ASTContext::CanonicalTemplateTemplateParm::Profile( + llvm::FoldingSetNodeID &ID, ASTContext const &C, + TemplateTemplateParmDecl *Parm) { ID.AddInteger(Parm->getDepth()); ID.AddInteger(Parm->getPosition()); ID.AddBoolean(Parm->isParameterPack()); @@ -672,12 +664,12 @@ TemplateParameterList *Params = Parm->getTemplateParameters(); ID.AddInteger(Params->size()); for (TemplateParameterList::const_iterator P = Params->begin(), - PEnd = Params->end(); + PEnd = Params->end(); P != PEnd; ++P) { - if (const auto *TTP = dyn_cast(*P)) { + if (auto const *TTP = dyn_cast(*P)) { ID.AddInteger(0); ID.AddBoolean(TTP->isParameterPack()); - const TypeConstraint *TC = TTP->getTypeConstraint(); + TypeConstraint const *TC = TTP->getTypeConstraint(); ID.AddBoolean(TC != nullptr); if (TC) TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, @@ -690,7 +682,7 @@ continue; } - if (const auto *NTTP = dyn_cast(*P)) { + if (auto const *NTTP = dyn_cast(*P)) { ID.AddInteger(1); ID.AddBoolean(NTTP->isParameterPack()); ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); @@ -717,7 +709,7 @@ } static Expr * -canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC, +canonicalizeImmediatelyDeclaredConstraint(ASTContext const &C, Expr *IDC, QualType ConstrainedType) { // This is a bit ugly - we need to form a new immediately-declared // constraint that references the new parameter; this would ideally @@ -727,7 +719,7 @@ // We don't have semantic analysis here so we dig deep into the // ready-made constraint expr and change the thing manually. ConceptSpecializationExpr *CSE; - if (const auto *Fold = dyn_cast(IDC)) + if (auto const *Fold = dyn_cast(IDC)) CSE = cast(Fold->getLHS()); else CSE = cast(IDC); @@ -760,22 +752,21 @@ CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack()); if (auto *OrigFold = dyn_cast(IDC)) - NewIDC = new (C) CXXFoldExpr( - OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC, - BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr, - SourceLocation(), /*NumExpansions=*/None); + NewIDC = new (C) + CXXFoldExpr(OrigFold->getType(), /*Callee*/ nullptr, SourceLocation(), + NewIDC, BinaryOperatorKind::BO_LAnd, SourceLocation(), + /*RHS=*/nullptr, SourceLocation(), /*NumExpansions=*/None); return NewIDC; } -TemplateTemplateParmDecl * -ASTContext::getCanonicalTemplateTemplateParmDecl( - TemplateTemplateParmDecl *TTP) const { +TemplateTemplateParmDecl *ASTContext::getCanonicalTemplateTemplateParmDecl( + TemplateTemplateParmDecl *TTP) const { // Check if we already have a canonical template template parameter. llvm::FoldingSetNodeID ID; CanonicalTemplateTemplateParm::Profile(ID, *this, TTP); void *InsertPos = nullptr; - CanonicalTemplateTemplateParm *Canonical - = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); + CanonicalTemplateTemplateParm *Canonical = + CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); if (Canonical) return Canonical->getParam(); @@ -784,36 +775,36 @@ SmallVector CanonParams; CanonParams.reserve(Params->size()); for (TemplateParameterList::const_iterator P = Params->begin(), - PEnd = Params->end(); + PEnd = Params->end(); P != PEnd; ++P) { - if (const auto *TTP = dyn_cast(*P)) { - TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this, - getTranslationUnitDecl(), SourceLocation(), SourceLocation(), + if (auto const *TTP = dyn_cast(*P)) { + TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create( + *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), TTP->getDepth(), TTP->getIndex(), nullptr, false, TTP->isParameterPack(), TTP->hasTypeConstraint(), - TTP->isExpandedParameterPack() ? - llvm::Optional(TTP->getNumExpansionParameters()) : None); - if (const auto *TC = TTP->getTypeConstraint()) { + TTP->isExpandedParameterPack() + ? llvm::Optional(TTP->getNumExpansionParameters()) + : None); + if (auto const *TC = TTP->getTypeConstraint()) { QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0); Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint( - *this, TC->getImmediatelyDeclaredConstraint(), - ParamAsArgument); + *this, TC->getImmediatelyDeclaredConstraint(), ParamAsArgument); TemplateArgumentListInfo CanonArgsAsWritten; if (auto *Args = TC->getTemplateArgsAsWritten()) - for (const auto &ArgLoc : Args->arguments()) - CanonArgsAsWritten.addArgument( - TemplateArgumentLoc(ArgLoc.getArgument(), - TemplateArgumentLocInfo())); + for (auto const &ArgLoc : Args->arguments()) + CanonArgsAsWritten.addArgument(TemplateArgumentLoc( + ArgLoc.getArgument(), TemplateArgumentLocInfo())); NewTTP->setTypeConstraint( NestedNameSpecifierLoc(), DeclarationNameInfo(TC->getNamedConcept()->getDeclName(), - SourceLocation()), /*FoundDecl=*/nullptr, + SourceLocation()), + /*FoundDecl=*/nullptr, // Actually canonicalizing a TemplateArgumentLoc is difficult so we // simply omit the ArgsAsWritten TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC); } CanonParams.push_back(NewTTP); - } else if (const auto *NTTP = dyn_cast(*P)) { + } else if (auto const *NTTP = dyn_cast(*P)) { QualType T = getCanonicalType(NTTP->getType()); TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); NonTypeTemplateParmDecl *Param; @@ -823,27 +814,18 @@ for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); ExpandedTInfos.push_back( - getTrivialTypeSourceInfo(ExpandedTypes.back())); + getTrivialTypeSourceInfo(ExpandedTypes.back())); } - Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), - SourceLocation(), - SourceLocation(), - NTTP->getDepth(), - NTTP->getPosition(), nullptr, - T, - TInfo, - ExpandedTypes, - ExpandedTInfos); + Param = NonTypeTemplateParmDecl::Create( + *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), + NTTP->getDepth(), NTTP->getPosition(), nullptr, T, TInfo, + ExpandedTypes, ExpandedTInfos); } else { - Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), - SourceLocation(), - SourceLocation(), - NTTP->getDepth(), - NTTP->getPosition(), nullptr, - T, - NTTP->isParameterPack(), - TInfo); + Param = NonTypeTemplateParmDecl::Create( + *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(), + NTTP->getDepth(), NTTP->getPosition(), nullptr, T, + NTTP->isParameterPack(), TInfo); } if (AutoType *AT = T->getContainedAutoType()) { if (AT->isConstrained()) { @@ -856,24 +838,19 @@ } else CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( - cast(*P))); + cast(*P))); } Expr *CanonRequiresClause = nullptr; if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause()) CanonRequiresClause = RequiresClause; - TemplateTemplateParmDecl *CanonTTP - = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), - SourceLocation(), TTP->getDepth(), - TTP->getPosition(), - TTP->isParameterPack(), - nullptr, - TemplateParameterList::Create(*this, SourceLocation(), - SourceLocation(), - CanonParams, - SourceLocation(), - CanonRequiresClause)); + TemplateTemplateParmDecl *CanonTTP = TemplateTemplateParmDecl::Create( + *this, getTranslationUnitDecl(), SourceLocation(), TTP->getDepth(), + TTP->getPosition(), TTP->isParameterPack(), nullptr, + TemplateParameterList::Create(*this, SourceLocation(), SourceLocation(), + CanonParams, SourceLocation(), + CanonRequiresClause)); // Get the new insert position for the node we care about. Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); @@ -891,8 +868,9 @@ return getLangOpts().CXXABI.getValueOr(Kind); } -CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { - if (!LangOpts.CPlusPlus) return nullptr; +CXXABI *ASTContext::createCXXABI(TargetInfo const &T) { + if (!LangOpts.CPlusPlus) + return nullptr; switch (getCXXABIKind()) { case TargetCXXABI::AppleARM64: @@ -925,12 +903,12 @@ return *ParentMapCtx.get(); } -static const LangASMap *getAddressSpaceMap(const TargetInfo &T, - const LangOptions &LOpts) { +static LangASMap const *getAddressSpaceMap(TargetInfo const &T, + LangOptions const &LOpts) { if (LOpts.FakeAddressSpaceMap) { // The fake address space map must have a distinct entry for each // language-specific address space. - static const unsigned FakeAddrSpaceMap[] = { + static unsigned const FakeAddrSpaceMap[] = { 0, // Default 1, // opencl_global 3, // opencl_local @@ -957,8 +935,8 @@ } } -static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, - const LangOptions &LangOpts) { +static bool isAddrSpaceMapManglingEnabled(TargetInfo const &TI, + LangOptions const &LangOpts) { switch (LangOpts.getAddressSpaceMapMangling()) { case LangOptions::ASMM_Target: return TI.useAddressSpaceMapMangling(); @@ -1001,30 +979,34 @@ // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed // because they can contain DenseMaps. - for (llvm::DenseMap::iterator - I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) + for (llvm::DenseMap::iterator + I = ObjCLayouts.begin(), + E = ObjCLayouts.end(); + I != E;) // Increment in loop to prevent using deallocated memory. if (auto *R = const_cast((I++)->second)) R->Destroy(*this); - for (llvm::DenseMap::iterator - I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { + for (llvm::DenseMap::iterator + I = ASTRecordLayouts.begin(), + E = ASTRecordLayouts.end(); + I != E;) { // Increment in loop to prevent using deallocated memory. if (auto *R = const_cast((I++)->second)) R->Destroy(*this); } - for (llvm::DenseMap::iterator A = DeclAttrs.begin(), - AEnd = DeclAttrs.end(); + for (llvm::DenseMap::iterator A = DeclAttrs.begin(), + AEnd = DeclAttrs.end(); A != AEnd; ++A) A->second->~AttrVec(); - for (const auto &Value : ModuleInitializers) + for (auto const &Value : ModuleInitializers) Value.second->~PerModuleInitializers(); } -void ASTContext::setTraversalScope(const std::vector &TopLevelDecls) { +void ASTContext::setTraversalScope(std::vector const &TopLevelDecls) { TraversalScope = TopLevelDecls; getParentMapContext().clear(); } @@ -1033,8 +1015,8 @@ Deallocations.push_back({Callback, Data}); } -void -ASTContext::setExternalSource(IntrusiveRefCntPtr Source) { +void ASTContext::setExternalSource( + IntrusiveRefCntPtr Source) { ExternalSource = std::move(Source); } @@ -1046,7 +1028,7 @@ #define TYPE(Name, Parent) 0, #define ABSTRACT_TYPE(Name, Parent) #include "clang/AST/TypeNodes.inc" - 0 // Extra + 0 // Extra }; for (unsigned i = 0, e = Types.size(); i != e; ++i) { @@ -1056,13 +1038,12 @@ unsigned Idx = 0; unsigned TotalBytes = 0; -#define TYPE(Name, Parent) \ - if (counts[Idx]) \ - llvm::errs() << " " << counts[Idx] << " " << #Name \ - << " types, " << sizeof(Name##Type) << " each " \ - << "(" << counts[Idx] * sizeof(Name##Type) \ - << " bytes)\n"; \ - TotalBytes += counts[Idx] * sizeof(Name##Type); \ +#define TYPE(Name, Parent) \ + if (counts[Idx]) \ + llvm::errs() << " " << counts[Idx] << " " << #Name << " types, " \ + << sizeof(Name##Type) << " each " \ + << "(" << counts[Idx] * sizeof(Name##Type) << " bytes)\n"; \ + TotalBytes += counts[Idx] * sizeof(Name##Type); \ ++Idx; #define ABSTRACT_TYPE(Name, Parent) #include "clang/AST/TypeNodes.inc" @@ -1088,8 +1069,7 @@ << NumImplicitMoveAssignmentOperators << " implicit move assignment operators created\n"; llvm::errs() << NumImplicitDestructorsDeclared << "/" - << NumImplicitDestructors - << " implicit destructors created\n"; + << NumImplicitDestructors << " implicit destructors created\n"; if (ExternalSource) { llvm::errs() << "\n"; @@ -1114,15 +1094,16 @@ return; auto &Merged = It->second; - llvm::DenseSet Found; + llvm::DenseSet Found; for (Module *&M : Merged) if (!Found.insert(M).second) M = nullptr; - Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end()); + Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), + Merged.end()); } ArrayRef -ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) { +ASTContext::getModulesWithMergedDefinition(NamedDecl const *Def) { auto MergedIt = MergedDefModules.find(cast(Def->getCanonicalDecl())); if (MergedIt == MergedDefModules.end()) @@ -1150,7 +1131,7 @@ void ASTContext::addModuleInitializer(Module *M, Decl *D) { // One special case: if we add a module initializer that imports another // module, and that module's only initializer is an ImportDecl, simplify. - if (const auto *ID = dyn_cast(D)) { + if (auto const *ID = dyn_cast(D)) { auto It = ModuleInitializers.find(ID->getImportedModule()); // Maybe the ImportDecl does nothing at all. (Common case.) @@ -1177,8 +1158,8 @@ auto *&Inits = ModuleInitializers[M]; if (!Inits) Inits = new (*this) PerModuleInitializers; - Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), - IDs.begin(), IDs.end()); + Inits->LazyInitializers.insert(Inits->LazyInitializers.end(), IDs.begin(), + IDs.end()); } ArrayRef ASTContext::getModuleInitializers(Module *M) { @@ -1193,14 +1174,15 @@ ExternCContextDecl *ASTContext::getExternCContextDecl() const { if (!ExternCContext) - ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl()); + ExternCContext = + ExternCContextDecl::Create(*this, getTranslationUnitDecl()); return ExternCContext; } BuiltinTemplateDecl * ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK, - const IdentifierInfo *II) const { + IdentifierInfo const *II) const { auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK); BuiltinTemplate->setImplicit(); @@ -1209,16 +1191,14 @@ return BuiltinTemplate; } -BuiltinTemplateDecl * -ASTContext::getMakeIntegerSeqDecl() const { +BuiltinTemplateDecl *ASTContext::getMakeIntegerSeqDecl() const { if (!MakeIntegerSeqDecl) MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq, getMakeIntegerSeqName()); return MakeIntegerSeqDecl; } -BuiltinTemplateDecl * -ASTContext::getTypePackElementDecl() const { +BuiltinTemplateDecl *ASTContext::getTypePackElementDecl() const { if (!TypePackElementDecl) TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element, getTypePackElementName()); @@ -1269,8 +1249,8 @@ Types.push_back(Ty); } -void ASTContext::InitBuiltinTypes(const TargetInfo &Target, - const TargetInfo *AuxTarget) { +void ASTContext::InitBuiltinTypes(TargetInfo const &Target, + TargetInfo const *AuxTarget) { assert((!this->Target || this->Target == &Target) && "Incorrect target reinitialization"); assert(VoidTy.isNull() && "Context reinitialized?"); @@ -1283,78 +1263,78 @@ AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); // C99 6.2.5p19. - InitBuiltinType(VoidTy, BuiltinType::Void); + InitBuiltinType(VoidTy, BuiltinType::Void); // C99 6.2.5p2. - InitBuiltinType(BoolTy, BuiltinType::Bool); + InitBuiltinType(BoolTy, BuiltinType::Bool); // C99 6.2.5p3. if (LangOpts.CharIsSigned) - InitBuiltinType(CharTy, BuiltinType::Char_S); + InitBuiltinType(CharTy, BuiltinType::Char_S); else - InitBuiltinType(CharTy, BuiltinType::Char_U); + InitBuiltinType(CharTy, BuiltinType::Char_U); // C99 6.2.5p4. - InitBuiltinType(SignedCharTy, BuiltinType::SChar); - InitBuiltinType(ShortTy, BuiltinType::Short); - InitBuiltinType(IntTy, BuiltinType::Int); - InitBuiltinType(LongTy, BuiltinType::Long); - InitBuiltinType(LongLongTy, BuiltinType::LongLong); + InitBuiltinType(SignedCharTy, BuiltinType::SChar); + InitBuiltinType(ShortTy, BuiltinType::Short); + InitBuiltinType(IntTy, BuiltinType::Int); + InitBuiltinType(LongTy, BuiltinType::Long); + InitBuiltinType(LongLongTy, BuiltinType::LongLong); // C99 6.2.5p6. - InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); - InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); - InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); - InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); - InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); + InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); + InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); + InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); + InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); + InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); // C99 6.2.5p10. - InitBuiltinType(FloatTy, BuiltinType::Float); - InitBuiltinType(DoubleTy, BuiltinType::Double); - InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); + InitBuiltinType(FloatTy, BuiltinType::Float); + InitBuiltinType(DoubleTy, BuiltinType::Double); + InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); // GNU extension, __float128 for IEEE quadruple precision - InitBuiltinType(Float128Ty, BuiltinType::Float128); + InitBuiltinType(Float128Ty, BuiltinType::Float128); // __ibm128 for IBM extended precision InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128); // C11 extension ISO/IEC TS 18661-3 - InitBuiltinType(Float16Ty, BuiltinType::Float16); + InitBuiltinType(Float16Ty, BuiltinType::Float16); // ISO/IEC JTC1 SC22 WG14 N1169 Extension - InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); - InitBuiltinType(AccumTy, BuiltinType::Accum); - InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); - InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); - InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); - InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); - InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); - InitBuiltinType(FractTy, BuiltinType::Fract); - InitBuiltinType(LongFractTy, BuiltinType::LongFract); - InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); - InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); - InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); - InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); - InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); - InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); + InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum); + InitBuiltinType(AccumTy, BuiltinType::Accum); + InitBuiltinType(LongAccumTy, BuiltinType::LongAccum); + InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum); + InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum); + InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum); + InitBuiltinType(ShortFractTy, BuiltinType::ShortFract); + InitBuiltinType(FractTy, BuiltinType::Fract); + InitBuiltinType(LongFractTy, BuiltinType::LongFract); + InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract); + InitBuiltinType(UnsignedFractTy, BuiltinType::UFract); + InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract); + InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum); + InitBuiltinType(SatAccumTy, BuiltinType::SatAccum); + InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum); InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum); - InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); - InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); - InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); - InitBuiltinType(SatFractTy, BuiltinType::SatFract); - InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); + InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum); + InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum); + InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract); + InitBuiltinType(SatFractTy, BuiltinType::SatFract); + InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract); InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract); - InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); - InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); + InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract); + InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract); // GNU extension, 128-bit integers. - InitBuiltinType(Int128Ty, BuiltinType::Int128); - InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); + InitBuiltinType(Int128Ty, BuiltinType::Int128); + InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); // C++ 3.9.1p5 if (TargetInfo::isTypeSigned(Target.getWCharType())) - InitBuiltinType(WCharTy, BuiltinType::WChar_S); - else // -fshort-wchar makes wchar_t be unsigned. - InitBuiltinType(WCharTy, BuiltinType::WChar_U); + InitBuiltinType(WCharTy, BuiltinType::WChar_S); + else // -fshort-wchar makes wchar_t be unsigned. + InitBuiltinType(WCharTy, BuiltinType::WChar_U); if (LangOpts.CPlusPlus && LangOpts.WChar) WideCharTy = WCharTy; else { @@ -1365,15 +1345,15 @@ WIntTy = getFromTargetType(Target.getWIntType()); // C++20 (proposed) - InitBuiltinType(Char8Ty, BuiltinType::Char8); + InitBuiltinType(Char8Ty, BuiltinType::Char8); if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ - InitBuiltinType(Char16Ty, BuiltinType::Char16); + InitBuiltinType(Char16Ty, BuiltinType::Char16); else // C99 Char16Ty = getFromTargetType(Target.getChar16Type()); if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ - InitBuiltinType(Char32Ty, BuiltinType::Char32); + InitBuiltinType(Char32Ty, BuiltinType::Char32); else // C99 Char32Ty = getFromTargetType(Target.getChar32Type()); @@ -1382,25 +1362,25 @@ // DependentTy and users should never see it; however, it is here to // help diagnose failures to properly check for type-dependent // expressions. - InitBuiltinType(DependentTy, BuiltinType::Dependent); + InitBuiltinType(DependentTy, BuiltinType::Dependent); // Placeholder type for functions. - InitBuiltinType(OverloadTy, BuiltinType::Overload); + InitBuiltinType(OverloadTy, BuiltinType::Overload); // Placeholder type for bound members. - InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); + InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); // Placeholder type for pseudo-objects. - InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); + InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); // "any" type; useful for debugger-like clients. - InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); + InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); // Placeholder type for unbridged ARC casts. - InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); + InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); // Placeholder type for builtin functions. - InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); + InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); // Placeholder type for OMP array sections. if (LangOpts.OpenMP) { @@ -1412,10 +1392,10 @@ InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx); // C99 6.2.5p11. - FloatComplexTy = getComplexType(FloatTy); - DoubleComplexTy = getComplexType(DoubleTy); + FloatComplexTy = getComplexType(FloatTy); + DoubleComplexTy = getComplexType(DoubleTy); LongDoubleComplexTy = getComplexType(LongDoubleTy); - Float128ComplexTy = getComplexType(Float128Ty); + Float128ComplexTy = getComplexType(Float128Ty); // Builtin types for 'id', 'Class', and 'SEL'. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); @@ -1423,8 +1403,8 @@ InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); if (LangOpts.OpenCL) { -#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ - InitBuiltinType(SingletonId, BuiltinType::Id); +#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ + InitBuiltinType(SingletonId, BuiltinType::Id); #include "clang/Basic/OpenCLImageTypes.def" InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); @@ -1433,26 +1413,26 @@ InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue); InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID); -#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ - InitBuiltinType(Id##Ty, BuiltinType::Id); +#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ + InitBuiltinType(Id##Ty, BuiltinType::Id); #include "clang/Basic/OpenCLExtensionTypes.def" } if (Target.hasAArch64SVETypes()) { -#define SVE_TYPE(Name, Id, SingletonId) \ - InitBuiltinType(SingletonId, BuiltinType::Id); +#define SVE_TYPE(Name, Id, SingletonId) \ + InitBuiltinType(SingletonId, BuiltinType::Id); #include "clang/Basic/AArch64SVEACLETypes.def" } if (Target.getTriple().isPPC64() && Target.hasFeature("paired-vector-memops")) { if (Target.hasFeature("mma")) { -#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ - InitBuiltinType(Id##Ty, BuiltinType::Id); +#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ + InitBuiltinType(Id##Ty, BuiltinType::Id); #include "clang/Basic/PPCTypes.def" } -#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ - InitBuiltinType(Id##Ty, BuiltinType::Id); +#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ + InitBuiltinType(Id##Ty, BuiltinType::Id); #include "clang/Basic/PPCTypes.def" } @@ -1463,8 +1443,8 @@ } // Builtin type for __objc_yes and __objc_no - ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? - SignedCharTy : BoolTy); + ObjCBuiltinBoolTy = + (Target.useSignedCharForObjCBool() ? SignedCharTy : BoolTy); ObjCConstantStringType = QualType(); @@ -1474,14 +1454,14 @@ if (LangOpts.OpenCLGenericAddressSpace) { auto Q = VoidTy.getQualifiers(); Q.setAddressSpace(LangAS::opencl_generic); - VoidPtrTy = getPointerType(getCanonicalType( - getQualifiedType(VoidTy.getUnqualifiedType(), Q))); + VoidPtrTy = getPointerType( + getCanonicalType(getQualifiedType(VoidTy.getUnqualifiedType(), Q))); } else { VoidPtrTy = getPointerType(VoidTy); } // nullptr type (C++0x 2.14.7) - InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); + InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 InitBuiltinType(HalfTy, BuiltinType::Half); @@ -1502,7 +1482,7 @@ return SourceMgr.getDiagnostics(); } -AttrVec& ASTContext::getDeclAttrs(const Decl *D) { +AttrVec &ASTContext::getDeclAttrs(Decl const *D) { AttrVec *&Result = DeclAttrs[D]; if (!Result) { void *Mem = Allocate(sizeof(AttrVec)); @@ -1513,8 +1493,8 @@ } /// Erase the attributes corresponding to the given declaration. -void ASTContext::eraseDeclAttrs(const Decl *D) { - llvm::DenseMap::iterator Pos = DeclAttrs.find(D); +void ASTContext::eraseDeclAttrs(Decl const *D) { + llvm::DenseMap::iterator Pos = DeclAttrs.find(D); if (Pos != DeclAttrs.end()) { Pos->second->~AttrVec(); DeclAttrs.erase(Pos); @@ -1523,15 +1503,15 @@ // FIXME: Remove ? MemberSpecializationInfo * -ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { +ASTContext::getInstantiatedFromStaticDataMember(VarDecl const *Var) { assert(Var->isStaticDataMember() && "Not a static data member"); return getTemplateOrSpecializationInfo(Var) .dyn_cast(); } ASTContext::TemplateOrSpecializationInfo -ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { - llvm::DenseMap::iterator Pos = +ASTContext::getTemplateOrSpecializationInfo(VarDecl const *Var) { + llvm::DenseMap::iterator Pos = TemplateOrInstantiation.find(Var); if (Pos == TemplateOrInstantiation.end()) return {}; @@ -1539,26 +1519,23 @@ return Pos->second; } -void -ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, - TemplateSpecializationKind TSK, - SourceLocation PointOfInstantiation) { +void ASTContext::setInstantiatedFromStaticDataMember( + VarDecl *Inst, VarDecl *Tmpl, TemplateSpecializationKind TSK, + SourceLocation PointOfInstantiation) { assert(Inst->isStaticDataMember() && "Not a static data member"); assert(Tmpl->isStaticDataMember() && "Not a static data member"); setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( Tmpl, TSK, PointOfInstantiation)); } -void -ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, - TemplateOrSpecializationInfo TSI) { +void ASTContext::setTemplateOrSpecializationInfo( + VarDecl *Inst, TemplateOrSpecializationInfo TSI) { assert(!TemplateOrInstantiation[Inst] && "Already noted what the variable was instantiated from"); TemplateOrInstantiation[Inst] = TSI; } -NamedDecl * -ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { +NamedDecl *ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) { auto Pos = InstantiatedFromUsingDecl.find(UUD); if (Pos == InstantiatedFromUsingDecl.end()) return nullptr; @@ -1566,14 +1543,12 @@ return Pos->second; } -void -ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) { - assert((isa(Pattern) || - isa(Pattern) || +void ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, + NamedDecl *Pattern) { + assert((isa(Pattern) || isa(Pattern) || isa(Pattern)) && "pattern decl is not a using decl"); - assert((isa(Inst) || - isa(Inst) || + assert((isa(Inst) || isa(Inst) || isa(Inst)) && "instantiation did not produce a using decl"); assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); @@ -1597,24 +1572,23 @@ UsingShadowDecl * ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { - llvm::DenseMap::const_iterator Pos - = InstantiatedFromUsingShadowDecl.find(Inst); + llvm::DenseMap::const_iterator Pos = + InstantiatedFromUsingShadowDecl.find(Inst); if (Pos == InstantiatedFromUsingShadowDecl.end()) return nullptr; return Pos->second; } -void -ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, - UsingShadowDecl *Pattern) { +void ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, + UsingShadowDecl *Pattern) { assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); InstantiatedFromUsingShadowDecl[Inst] = Pattern; } FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { - llvm::DenseMap::iterator Pos - = InstantiatedFromUnnamedFieldDecl.find(Field); + llvm::DenseMap::iterator Pos = + InstantiatedFromUnnamedFieldDecl.find(Field); if (Pos == InstantiatedFromUnnamedFieldDecl.end()) return nullptr; @@ -1632,52 +1606,51 @@ } ASTContext::overridden_cxx_method_iterator -ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { +ASTContext::overridden_methods_begin(CXXMethodDecl const *Method) const { return overridden_methods(Method).begin(); } ASTContext::overridden_cxx_method_iterator -ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { +ASTContext::overridden_methods_end(CXXMethodDecl const *Method) const { return overridden_methods(Method).end(); } unsigned -ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { +ASTContext::overridden_methods_size(CXXMethodDecl const *Method) const { auto Range = overridden_methods(Method); return Range.end() - Range.begin(); } ASTContext::overridden_method_range -ASTContext::overridden_methods(const CXXMethodDecl *Method) const { - llvm::DenseMap::const_iterator Pos = +ASTContext::overridden_methods(CXXMethodDecl const *Method) const { + llvm::DenseMap::const_iterator Pos = OverriddenMethods.find(Method->getCanonicalDecl()); if (Pos == OverriddenMethods.end()) return overridden_method_range(nullptr, nullptr); return overridden_method_range(Pos->second.begin(), Pos->second.end()); } -void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, - const CXXMethodDecl *Overridden) { +void ASTContext::addOverriddenMethod(CXXMethodDecl const *Method, + CXXMethodDecl const *Overridden) { assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); OverriddenMethods[Method].push_back(Overridden); } void ASTContext::getOverriddenMethods( - const NamedDecl *D, - SmallVectorImpl &Overridden) const { + NamedDecl const *D, SmallVectorImpl &Overridden) const { assert(D); - if (const auto *CXXMethod = dyn_cast(D)) { + if (auto const *CXXMethod = dyn_cast(D)) { Overridden.append(overridden_methods_begin(CXXMethod), overridden_methods_end(CXXMethod)); return; } - const auto *Method = dyn_cast(D); + auto const *Method = dyn_cast(D); if (!Method) return; - SmallVector OverDecls; + SmallVector OverDecls; Method->getOverriddenMethods(OverDecls); Overridden.append(OverDecls.begin(), OverDecls.end()); } @@ -1702,7 +1675,7 @@ /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified /// scalar floating point type. -const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { +llvm::fltSemantics const &ASTContext::getFloatTypeSemantics(QualType T) const { switch (T->castAs()->getKind()) { default: llvm_unreachable("Not a floating point type!"); @@ -1711,8 +1684,10 @@ case BuiltinType::Float16: case BuiltinType::Half: return Target->getHalfFormat(); - case BuiltinType::Float: return Target->getFloatFormat(); - case BuiltinType::Double: return Target->getDoubleFormat(); + case BuiltinType::Float: + return Target->getFloatFormat(); + case BuiltinType::Double: + return Target->getDoubleFormat(); case BuiltinType::Ibm128: return Target->getIbm128Format(); case BuiltinType::LongDouble: @@ -1726,7 +1701,7 @@ } } -CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { +CharUnits ASTContext::getDeclAlign(Decl const *D, bool ForAlignof) const { unsigned Align = Target->getCharWidth(); bool UseAlignAttrOnly = false; @@ -1741,23 +1716,21 @@ // ignore that possibility; Sema should diagnose it. if (isa(D)) { UseAlignAttrOnly = D->hasAttr() || - cast(D)->getParent()->hasAttr(); + cast(D)->getParent()->hasAttr(); } else { UseAlignAttrOnly = true; } - } - else if (isa(D)) - UseAlignAttrOnly = - D->hasAttr() || - cast(D)->getParent()->hasAttr(); + } else if (isa(D)) + UseAlignAttrOnly = D->hasAttr() || + cast(D)->getParent()->hasAttr(); // If we're using the align attribute only, just ignore everything // else about the declaration and its type. if (UseAlignAttrOnly) { // do nothing - } else if (const auto *VD = dyn_cast(D)) { + } else if (auto const *VD = dyn_cast(D)) { QualType T = VD->getType(); - if (const auto *RT = T->getAs()) { + if (auto const *RT = T->getAs()) { if (ForAlignof) T = RT->getPointeeType(); else @@ -1769,7 +1742,7 @@ else if (!BaseT->isIncompleteType()) { // Adjust alignments of declarations with array type by the // large-array alignment on the target. - if (const ArrayType *arrayType = getAsArrayType(T)) { + if (ArrayType const *arrayType = getAsArrayType(T)) { unsigned MinWidth = Target->getLargeArrayMinWidth(); if (!ForAlignof && MinWidth) { if (isa(arrayType)) @@ -1782,7 +1755,7 @@ Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); if (BaseT.getQualifiers().hasUnaligned()) Align = Target->getCharWidth(); - if (const auto *VD = dyn_cast(D)) { + if (auto const *VD = dyn_cast(D)) { if (VD->hasGlobalStorage() && !ForAlignof) { uint64_t TypeSize = getTypeSize(T.getTypePtr()); Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize)); @@ -1795,11 +1768,11 @@ // a max-field-alignment constraint (#pragma pack). So calculate // the actual alignment of the field within the struct, and then // (as we're expected to) constrain that by the alignment of the type. - if (const auto *Field = dyn_cast(VD)) { - const RecordDecl *Parent = Field->getParent(); + if (auto const *Field = dyn_cast(VD)) { + RecordDecl const *Parent = Field->getParent(); // We can only produce a sensible answer if the record is valid. if (!Parent->isInvalidDecl()) { - const ASTRecordLayout &Layout = getASTRecordLayout(Parent); + ASTRecordLayout const &Layout = getASTRecordLayout(Parent); // Start with the record's overall alignment. unsigned FieldAlign = toBits(Layout.getAlignment()); @@ -1821,8 +1794,8 @@ // Some targets have hard limitation on the maximum requestable alignment in // aligned attribute for static variables. - const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); - const auto *VD = dyn_cast(D); + unsigned const MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute(); + auto const *VD = dyn_cast(D); if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static) Align = std::min(Align, MaxAlignedAttr); @@ -1844,8 +1817,8 @@ // of a base-class subobject. We decide whether that's possible // during class layout, so here we can just trust the layout results. if (getLangOpts().CPlusPlus) { - if (const auto *RT = T->getAs()) { - const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); + if (auto const *RT = T->getAs()) { + ASTRecordLayout const &layout = getASTRecordLayout(RT->getDecl()); Info.Width = layout.getDataSize(); } } @@ -1855,13 +1828,12 @@ /// getConstantArrayInfoInChars - Performing the computation in CharUnits /// instead of in bits prevents overflowing the uint64_t for some large arrays. -TypeInfoChars -static getConstantArrayInfoInChars(const ASTContext &Context, - const ConstantArrayType *CAT) { +static TypeInfoChars getConstantArrayInfoInChars(ASTContext const &Context, + ConstantArrayType const *CAT) { TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType()); uint64_t Size = CAT->getSize().getZExtValue(); assert((Size == 0 || static_cast(EltInfo.Width.getQuantity()) <= - (uint64_t)(-1)/Size) && + (uint64_t)(-1) / Size) && "Overflow in array type char size evaluation"); uint64_t Width = EltInfo.Width.getQuantity() * Size; unsigned Align = EltInfo.Align.getQuantity(); @@ -1873,8 +1845,8 @@ EltInfo.AlignRequirement); } -TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const { - if (const auto *CAT = dyn_cast(T)) +TypeInfoChars ASTContext::getTypeInfoInChars(Type const *T) const { + if (auto const *CAT = dyn_cast(T)) return getConstantArrayInfoInChars(*this, CAT); TypeInfo Info = getTypeInfo(T); return TypeInfoChars(toCharUnitsFromBits(Info.Width), @@ -1885,7 +1857,7 @@ return getTypeInfoInChars(T.getTypePtr()); } -bool ASTContext::isAlignmentRequired(const Type *T) const { +bool ASTContext::isAlignmentRequired(Type const *T) const { return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None; } @@ -1896,7 +1868,7 @@ unsigned ASTContext::getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment) const { // An alignment on a typedef overrides anything else. - if (const auto *TT = T->getAs()) + if (auto const *TT = T->getAs()) if (unsigned Align = TT->getDecl()->getMaxAlignment()) return Align; @@ -1907,18 +1879,18 @@ // If we had an array type, its element type might be a typedef // type with an alignment attribute. - if (const auto *TT = T->getAs()) + if (auto const *TT = T->getAs()) if (unsigned Align = TT->getDecl()->getMaxAlignment()) return Align; // Otherwise, see if the declaration of the type had an attribute. - if (const auto *TT = T->getAs()) + if (auto const *TT = T->getAs()) return TT->getDecl()->getMaxAlignment(); return 0; } -TypeInfo ASTContext::getTypeInfo(const Type *T) const { +TypeInfo ASTContext::getTypeInfo(Type const *T) const { TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); if (I != MemoizedTypeInfo.end()) return I->second; @@ -1935,7 +1907,7 @@ /// FIXME: Pointers into different addr spaces could have different sizes and /// alignment requirements: getPointerInfo should take an AddrSpace, this /// should take a QualType, &c. -TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { +TypeInfo ASTContext::getTypeInfoImpl(Type const *T) const { uint64_t Width = 0; unsigned Align = 8; AlignRequirementKind AlignRequirement = AlignRequirementKind::None; @@ -1947,8 +1919,8 @@ #define DEPENDENT_TYPE(Class, Base) case Type::Class: #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ case Type::Class: \ - assert(!T->isDependentType() && "should not see dependent types here"); \ - return getTypeInfo(cast(T)->desugar().getTypePtr()); + assert(!T->isDependentType() && "should not see dependent types here"); \ + return getTypeInfo(cast(T)->desugar().getTypePtr()); #include "clang/AST/TypeNodes.inc" llvm_unreachable("Should not see dependent types"); @@ -1964,7 +1936,7 @@ case Type::ConstantArray: { // Model non-constant sized arrays as size zero, but track the alignment. uint64_t Size = 0; - if (const auto *CAT = dyn_cast(T)) + if (auto const *CAT = dyn_cast(T)) Size = CAT->getSize().getZExtValue(); TypeInfo EltInfo = getTypeInfo(cast(T)->getElementType()); @@ -1981,13 +1953,13 @@ case Type::ExtVector: case Type::Vector: { - const auto *VT = cast(T); + auto const *VT = cast(T); TypeInfo EltInfo = getTypeInfo(VT->getElementType()); Width = EltInfo.Width * VT->getNumElements(); Align = Width; // If the alignment is not a power of 2, round up to the next power of 2. // This happens for non-power-of-2 length vectors. - if (Align & (Align-1)) { + if (Align & (Align - 1)) { Align = llvm::NextPowerOf2(Align); Width = llvm::alignTo(Width, Align); } @@ -2006,7 +1978,7 @@ } case Type::ConstantMatrix: { - const auto *MT = cast(T); + auto const *MT = cast(T); TypeInfo ElementInfo = getTypeInfo(MT->getElementType()); // The internal layout of a matrix value is implementation defined. // Initially be ABI compatible with arrays with respect to alignment and @@ -2018,7 +1990,8 @@ case Type::Builtin: switch (cast(T)->getKind()) { - default: llvm_unreachable("Unknown builtin type!"); + default: + llvm_unreachable("Unknown builtin type!"); case BuiltinType::Void: // GCC extension: alignof(void) = 8 bits. Width = 0; @@ -2183,25 +2156,24 @@ case BuiltinType::OCLClkEvent: case BuiltinType::OCLQueue: case BuiltinType::OCLReserveID: -#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ - case BuiltinType::Id: -#include "clang/Basic/OpenCLImageTypes.def" -#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ +#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ case BuiltinType::Id: +#include "clang/Basic/OpenCLImageTypes.def" +#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id: #include "clang/Basic/OpenCLExtensionTypes.def" AS = getTargetAddressSpace( Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T))); Width = Target->getPointerWidth(AS); Align = Target->getPointerAlign(AS); break; - // The SVE types are effectively target-specific. The length of an - // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple - // of 128 bits. There is one predicate bit for each vector byte, so the - // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. - // - // Because the length is only known at runtime, we use a dummy value - // of 0 for the static length. The alignment values are those defined - // by the Procedure Call Standard for the Arm Architecture. + // The SVE types are effectively target-specific. The length of an + // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple + // of 128 bits. There is one predicate bit for each vector byte, so the + // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits. + // + // Because the length is only known at runtime, we use a dummy value + // of 0 for the static length. The alignment values are those defined + // by the Procedure Call Standard for the Arm Architecture. #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \ IsSigned, IsFP, IsBF) \ case BuiltinType::Id: \ @@ -2257,7 +2229,7 @@ Align = Target->getPointerAlign(AS); break; case Type::MemberPointer: { - const auto *MPT = cast(T); + auto const *MPT = cast(T); CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT); Width = MPI.Width; Align = MPI.Align; @@ -2277,19 +2249,19 @@ case Type::Decayed: return getTypeInfo(cast(T)->getAdjustedType().getTypePtr()); case Type::ObjCInterface: { - const auto *ObjCI = cast(T); + auto const *ObjCI = cast(T); if (ObjCI->getDecl()->isInvalidDecl()) { Width = 8; Align = 8; break; } - const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); + ASTRecordLayout const &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); Width = toBits(Layout.getSize()); Align = toBits(Layout.getAlignment()); break; } case Type::ExtInt: { - const auto *EIT = cast(T); + auto const *EIT = cast(T); Align = std::min(static_cast(std::max( getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))), @@ -2299,7 +2271,7 @@ } case Type::Record: case Type::Enum: { - const auto *TT = cast(T); + auto const *TT = cast(T); if (TT->getDecl()->isInvalidDecl()) { Width = 8; @@ -2307,8 +2279,8 @@ break; } - if (const auto *ET = dyn_cast(TT)) { - const EnumDecl *ED = ET->getDecl(); + if (auto const *ET = dyn_cast(TT)) { + EnumDecl const *ED = ET->getDecl(); TypeInfo Info = getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType()); if (unsigned AttrAlign = ED->getMaxAlignment()) { @@ -2318,9 +2290,9 @@ return Info; } - const auto *RT = cast(TT); - const RecordDecl *RD = RT->getDecl(); - const ASTRecordLayout &Layout = getASTRecordLayout(RD); + auto const *RT = cast(TT); + RecordDecl const *RD = RT->getDecl(); + ASTRecordLayout const &Layout = getASTRecordLayout(RD); Width = toBits(Layout.getSize()); Align = toBits(Layout.getAlignment()); AlignRequirement = RD->hasAttr() @@ -2330,12 +2302,12 @@ } case Type::SubstTemplateTypeParm: - return getTypeInfo(cast(T)-> - getReplacementType().getTypePtr()); + return getTypeInfo( + cast(T)->getReplacementType().getTypePtr()); case Type::Auto: case Type::DeducedTemplateSpecialization: { - const auto *A = cast(T); + auto const *A = cast(T); assert(!A->getDeducedType().isNull() && "cannot request the size of an undeduced or dependent auto type"); return getTypeInfo(A->getDeducedType().getTypePtr()); @@ -2352,7 +2324,7 @@ return getTypeInfo(cast(T)->desugar().getTypePtr()); case Type::Typedef: { - const TypedefNameDecl *Typedef = cast(T)->getDecl(); + TypedefNameDecl const *Typedef = cast(T)->getDecl(); TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); // If the typedef has an aligned attribute on it, it overrides any computed // alignment we have. This violates the GCC documentation (which says that @@ -2373,7 +2345,7 @@ case Type::Attributed: return getTypeInfo( - cast(T)->getEquivalentType().getTypePtr()); + cast(T)->getEquivalentType().getTypePtr()); case Type::Atomic: { // Start with the base type information. @@ -2398,12 +2370,13 @@ // Set the alignment equal to the size. Align = static_cast(Width); } - } - break; + } break; case Type::Pipe: - Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); - Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); + Width = + Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global)); + Align = + Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global)); break; } @@ -2411,18 +2384,18 @@ return TypeInfo(Width, Align, AlignRequirement); } -unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const { +unsigned ASTContext::getTypeUnadjustedAlign(Type const *T) const { UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T); if (I != MemoizedUnadjustedAlign.end()) return I->second; unsigned UnadjustedAlign; - if (const auto *RT = T->getAs()) { - const RecordDecl *RD = RT->getDecl(); - const ASTRecordLayout &Layout = getASTRecordLayout(RD); + if (auto const *RT = T->getAs()) { + RecordDecl const *RD = RT->getDecl(); + ASTRecordLayout const &Layout = getASTRecordLayout(RD); UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); - } else if (const auto *ObjCI = T->getAs()) { - const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); + } else if (auto const *ObjCI = T->getAs()) { + ASTRecordLayout const &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); UnadjustedAlign = toBits(Layout.getUnadjustedAlignment()); } else { UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType()); @@ -2452,7 +2425,7 @@ CharUnits ASTContext::getTypeSizeInChars(QualType T) const { return getTypeInfoInChars(T).Width; } -CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { +CharUnits ASTContext::getTypeSizeInChars(Type const *T) const { return getTypeInfoInChars(T).Width; } @@ -2461,7 +2434,7 @@ CharUnits ASTContext::getTypeAlignInChars(QualType T) const { return toCharUnitsFromBits(getTypeAlign(T)); } -CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { +CharUnits ASTContext::getTypeAlignInChars(Type const *T) const { return toCharUnitsFromBits(getTypeAlign(T)); } @@ -2471,7 +2444,7 @@ CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const { return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); } -CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const { +CharUnits ASTContext::getTypeUnadjustedAlignInChars(Type const *T) const { return toCharUnitsFromBits(getTypeUnadjustedAlign(T)); } @@ -2480,7 +2453,7 @@ /// alignment in cases where it is beneficial for performance or backwards /// compatibility preserving to overalign a data type. (Note: despite the name, /// the preferred alignment is ABI-impacting, and not an optimization.) -unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { +unsigned ASTContext::getPreferredTypeAlign(Type const *T) const { TypeInfo TI = getTypeInfo(T); unsigned ABIAlign = TI.Align; @@ -2493,8 +2466,8 @@ if (!Target->allowsLargerPreferedTypeAlignment()) return ABIAlign; - if (const auto *RT = T->getAs()) { - const RecordDecl *RD = RT->getDecl(); + if (auto const *RT = T->getAs()) { + RecordDecl const *RD = RT->getDecl(); // When used as part of a typedef, or together with a 'packed' attribute, // the 'aligned' attribute can be used to decrease alignment. Note that the @@ -2514,9 +2487,9 @@ // Double (and, for targets supporting AIX `power` alignment, long double) and // long long should be naturally aligned (despite requiring less alignment) if // possible. - if (const auto *CT = T->getAs()) + if (auto const *CT = T->getAs()) T = CT->getElementType().getTypePtr(); - if (const auto *ET = T->getAs()) + if (auto const *ET = T->getAs()) T = ET->getDecl()->getIntegerType().getTypePtr(); if (T->isSpecificBuiltinType(BuiltinType::Double) || T->isSpecificBuiltinType(BuiltinType::LongLong) || @@ -2552,25 +2525,25 @@ return toCharUnitsFromBits(getAlignOfGlobalVar(T)); } -CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const { +CharUnits ASTContext::getOffsetOfBaseWithVBPtr(CXXRecordDecl const *RD) const { CharUnits Offset = CharUnits::Zero(); - const ASTRecordLayout *Layout = &getASTRecordLayout(RD); - while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) { + ASTRecordLayout const *Layout = &getASTRecordLayout(RD); + while (CXXRecordDecl const *Base = Layout->getBaseSharingVBPtr()) { Offset += Layout->getBaseClassOffset(Base); Layout = &getASTRecordLayout(Base); } return Offset; } -CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const { - const ValueDecl *MPD = MP.getMemberPointerDecl(); +CharUnits ASTContext::getMemberPointerPathAdjustment(APValue const &MP) const { + ValueDecl const *MPD = MP.getMemberPointerDecl(); CharUnits ThisAdjustment = CharUnits::Zero(); - ArrayRef Path = MP.getMemberPointerPath(); + ArrayRef Path = MP.getMemberPointerPath(); bool DerivedMember = MP.isMemberPointerToDerivedMember(); - const CXXRecordDecl *RD = cast(MPD->getDeclContext()); + CXXRecordDecl const *RD = cast(MPD->getDeclContext()); for (unsigned I = 0, N = Path.size(); I != N; ++I) { - const CXXRecordDecl *Base = RD; - const CXXRecordDecl *Derived = Path[I]; + CXXRecordDecl const *Base = RD; + CXXRecordDecl const *Derived = Path[I]; if (DerivedMember) std::swap(Base, Derived); ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base); @@ -2586,27 +2559,27 @@ /// super class and then collects all ivars, including those synthesized for /// current class. This routine is used for implementation of current class /// when all ivars, declared and synthesized are known. -void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, - bool leafClass, - SmallVectorImpl &Ivars) const { - if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) +void ASTContext::DeepCollectObjCIvars( + ObjCInterfaceDecl const *OI, bool leafClass, + SmallVectorImpl &Ivars) const { + if (ObjCInterfaceDecl const *SuperClass = OI->getSuperClass()) DeepCollectObjCIvars(SuperClass, false, Ivars); if (!leafClass) { - for (const auto *I : OI->ivars()) + for (auto const *I : OI->ivars()) Ivars.push_back(I); } else { auto *IDecl = const_cast(OI); - for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; - Iv= Iv->getNextIvar()) + for (ObjCIvarDecl const *Iv = IDecl->all_declared_ivar_begin(); Iv; + Iv = Iv->getNextIvar()) Ivars.push_back(Iv); } } /// CollectInheritedProtocols - Collect all protocols in current class and /// those inherited by it. -void ASTContext::CollectInheritedProtocols(const Decl *CDecl, - llvm::SmallPtrSet &Protocols) { - if (const auto *OI = dyn_cast(CDecl)) { +void ASTContext::CollectInheritedProtocols( + Decl const *CDecl, llvm::SmallPtrSet &Protocols) { + if (auto const *OI = dyn_cast(CDecl)) { // We can use protocol_iterator here instead of // all_referenced_protocol_iterator since we are walking all categories. for (auto *Proto : OI->all_referenced_protocols()) { @@ -2614,7 +2587,7 @@ } // Categories of this Interface. - for (const auto *Cat : OI->visible_categories()) + for (auto const *Cat : OI->visible_categories()) CollectInheritedProtocols(Cat, Protocols); if (ObjCInterfaceDecl *SD = OI->getSuperClass()) @@ -2622,14 +2595,15 @@ CollectInheritedProtocols(SD, Protocols); SD = SD->getSuperClass(); } - } else if (const auto *OC = dyn_cast(CDecl)) { + } else if (auto const *OC = dyn_cast(CDecl)) { for (auto *Proto : OC->protocols()) { CollectInheritedProtocols(Proto, Protocols); } - } else if (const auto *OP = dyn_cast(CDecl)) { + } else if (auto const *OP = dyn_cast(CDecl)) { // Insert the protocol. - if (!Protocols.insert( - const_cast(OP->getCanonicalDecl())).second) + if (!Protocols + .insert(const_cast(OP->getCanonicalDecl())) + .second) return; for (auto *Proto : OP->protocols()) @@ -2637,12 +2611,12 @@ } } -static bool unionHasUniqueObjectRepresentations(const ASTContext &Context, - const RecordDecl *RD) { +static bool unionHasUniqueObjectRepresentations(ASTContext const &Context, + RecordDecl const *RD) { assert(RD->isUnion() && "Must be union type"); CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl()); - for (const auto *Field : RD->fields()) { + for (auto const *Field : RD->fields()) { if (!Context.hasUniqueObjectRepresentations(Field->getType())) return false; CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType()); @@ -2652,26 +2626,26 @@ return !RD->field_empty(); } -static int64_t getSubobjectOffset(const FieldDecl *Field, - const ASTContext &Context, - const clang::ASTRecordLayout & /*Layout*/) { +static int64_t getSubobjectOffset(FieldDecl const *Field, + ASTContext const &Context, + clang::ASTRecordLayout const & /*Layout*/) { return Context.getFieldOffset(Field); } -static int64_t getSubobjectOffset(const CXXRecordDecl *RD, - const ASTContext &Context, - const clang::ASTRecordLayout &Layout) { +static int64_t getSubobjectOffset(CXXRecordDecl const *RD, + ASTContext const &Context, + clang::ASTRecordLayout const &Layout) { return Context.toBits(Layout.getBaseClassOffset(RD)); } static llvm::Optional -structHasUniqueObjectRepresentations(const ASTContext &Context, - const RecordDecl *RD); +structHasUniqueObjectRepresentations(ASTContext const &Context, + RecordDecl const *RD); static llvm::Optional -getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) { +getSubobjectSizeInBits(FieldDecl const *Field, ASTContext const &Context) { if (Field->getType()->isRecordType()) { - const RecordDecl *RD = Field->getType()->getAsRecordDecl(); + RecordDecl const *RD = Field->getType()->getAsRecordDecl(); if (!RD->isUnion()) return structHasUniqueObjectRepresentations(Context, RD); } @@ -2691,15 +2665,15 @@ } static llvm::Optional -getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) { +getSubobjectSizeInBits(CXXRecordDecl const *RD, ASTContext const &Context) { return structHasUniqueObjectRepresentations(Context, RD); } template static llvm::Optional structSubobjectsHaveUniqueObjectRepresentations( - const RangeT &Subobjects, int64_t CurOffsetInBits, - const ASTContext &Context, const clang::ASTRecordLayout &Layout) { - for (const auto *Subobject : Subobjects) { + RangeT const &Subobjects, int64_t CurOffsetInBits, + ASTContext const &Context, clang::ASTRecordLayout const &Layout) { + for (auto const *Subobject : Subobjects) { llvm::Optional SizeInBits = getSubobjectSizeInBits(Subobject, Context); if (!SizeInBits) @@ -2715,24 +2689,24 @@ } static llvm::Optional -structHasUniqueObjectRepresentations(const ASTContext &Context, - const RecordDecl *RD) { +structHasUniqueObjectRepresentations(ASTContext const &Context, + RecordDecl const *RD) { assert(!RD->isUnion() && "Must be struct/class type"); - const auto &Layout = Context.getASTRecordLayout(RD); + auto const &Layout = Context.getASTRecordLayout(RD); int64_t CurOffsetInBits = 0; - if (const auto *ClassDecl = dyn_cast(RD)) { + if (auto const *ClassDecl = dyn_cast(RD)) { if (ClassDecl->isDynamicClass()) return llvm::None; SmallVector Bases; - for (const auto &Base : ClassDecl->bases()) { + for (auto const &Base : ClassDecl->bases()) { // Empty types can be inherited from, and non-empty types can potentially // have tail padding, so just make sure there isn't an error. Bases.emplace_back(Base.getType()->getAsCXXRecordDecl()); } - llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) { + llvm::sort(Bases, [&](CXXRecordDecl const *L, CXXRecordDecl const *R) { return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R); }); @@ -2791,12 +2765,12 @@ return true; if (Ty->isMemberPointerType()) { - const auto *MPT = Ty->getAs(); + auto const *MPT = Ty->getAs(); return !ABI->getMemberPointerInfo(MPT).HasPadding; } if (Ty->isRecordType()) { - const RecordDecl *Record = Ty->castAs()->getDecl(); + RecordDecl const *Record = Ty->castAs()->getDecl(); if (Record->isInvalidDecl()) return false; @@ -2825,10 +2799,10 @@ return false; } -unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { +unsigned ASTContext::CountNonClassIvars(ObjCInterfaceDecl const *OI) const { unsigned count = 0; // Count ivars declared in class extension. - for (const auto *Ext : OI->known_extensions()) + for (auto const *Ext : OI->known_extensions()) count += Ext->ivar_size(); // Count ivar defined in this class's implementation. This @@ -2839,29 +2813,32 @@ return count; } -bool ASTContext::isSentinelNullExpr(const Expr *E) { +bool ASTContext::isSentinelNullExpr(Expr const *E) { if (!E) return false; // nullptr_t is always treated as null. - if (E->getType()->isNullPtrType()) return true; + if (E->getType()->isNullPtrType()) + return true; if (E->getType()->isAnyPointerType() && - E->IgnoreParenCasts()->isNullPointerConstant(*this, - Expr::NPC_ValueDependentIsNull)) + E->IgnoreParenCasts()->isNullPointerConstant( + *this, Expr::NPC_ValueDependentIsNull)) return true; // Unfortunately, __null has type 'int'. - if (isa(E)) return true; + if (isa(E)) + return true; return false; } /// Get the implementation of ObjCInterfaceDecl, or nullptr if none /// exists. -ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { - llvm::DenseMap::iterator - I = ObjCImpls.find(D); +ObjCImplementationDecl * +ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { + llvm::DenseMap::iterator I = + ObjCImpls.find(D); if (I != ObjCImpls.end()) return cast(I->second); return nullptr; @@ -2870,8 +2847,8 @@ /// Get the implementation of ObjCCategoryDecl, or nullptr if none /// exists. ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { - llvm::DenseMap::iterator - I = ObjCImpls.find(D); + llvm::DenseMap::iterator I = + ObjCImpls.find(D); if (I != ObjCImpls.end()) return cast(I->second); return nullptr; @@ -2879,36 +2856,36 @@ /// Set the implementation of ObjCInterfaceDecl. void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, - ObjCImplementationDecl *ImplD) { + ObjCImplementationDecl *ImplD) { assert(IFaceD && ImplD && "Passed null params"); ObjCImpls[IFaceD] = ImplD; } /// Set the implementation of ObjCCategoryDecl. void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, - ObjCCategoryImplDecl *ImplD) { + ObjCCategoryImplDecl *ImplD) { assert(CatD && ImplD && "Passed null params"); ObjCImpls[CatD] = ImplD; } -const ObjCMethodDecl * -ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const { +ObjCMethodDecl const * +ASTContext::getObjCMethodRedeclaration(ObjCMethodDecl const *MD) const { return ObjCMethodRedecls.lookup(MD); } -void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD, - const ObjCMethodDecl *Redecl) { +void ASTContext::setObjCMethodRedeclaration(ObjCMethodDecl const *MD, + ObjCMethodDecl const *Redecl) { assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration"); ObjCMethodRedecls[MD] = Redecl; } -const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( - const NamedDecl *ND) const { - if (const auto *ID = dyn_cast(ND->getDeclContext())) +ObjCInterfaceDecl const * +ASTContext::getObjContainingInterface(NamedDecl const *ND) const { + if (auto const *ID = dyn_cast(ND->getDeclContext())) return ID; - if (const auto *CD = dyn_cast(ND->getDeclContext())) + if (auto const *CD = dyn_cast(ND->getDeclContext())) return CD->getClassInterface(); - if (const auto *IMD = dyn_cast(ND->getDeclContext())) + if (auto const *IMD = dyn_cast(ND->getDeclContext())) return IMD->getClassInterface(); return nullptr; @@ -2916,10 +2893,9 @@ /// Get the copy initialization expression of VarDecl, or nullptr if /// none exists. -BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const { +BlockVarCopyInit ASTContext::getBlockVarCopyInit(VarDecl const *VD) const { assert(VD && "Passed null params"); - assert(VD->hasAttr() && - "getBlockVarCopyInits - not __block var"); + assert(VD->hasAttr() && "getBlockVarCopyInits - not __block var"); auto I = BlockVarCopyInits.find(VD); if (I != BlockVarCopyInits.end()) return I->second; @@ -2927,11 +2903,10 @@ } /// Set the copy initialization expression of a block var decl. -void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr, +void ASTContext::setBlockVarCopyInit(VarDecl const *VD, Expr *CopyExpr, bool CanThrow) { assert(VD && CopyExpr && "Passed null params"); - assert(VD->hasAttr() && - "setBlockVarCopyInits - not __block var"); + assert(VD->hasAttr() && "setBlockVarCopyInits - not __block var"); BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow); } @@ -2943,8 +2918,8 @@ assert(DataSize == TypeLoc::getFullDataSizeForType(T) && "incorrect data size provided to CreateTypeSourceInfo!"); - auto *TInfo = - (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); + auto *TInfo = (TypeSourceInfo *)BumpAlloc.Allocate( + sizeof(TypeSourceInfo) + DataSize, 8); new (TInfo) TypeSourceInfo(T); return TInfo; } @@ -2956,14 +2931,13 @@ return DI; } -const ASTRecordLayout & -ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { +ASTRecordLayout const & +ASTContext::getASTObjCInterfaceLayout(ObjCInterfaceDecl const *D) const { return getObjCLayout(D, nullptr); } -const ASTRecordLayout & -ASTContext::getASTObjCImplementationLayout( - const ObjCImplementationDecl *D) const { +ASTRecordLayout const &ASTContext::getASTObjCImplementationLayout( + ObjCImplementationDecl const *D) const { return getObjCLayout(D->getClassInterface(), D); } @@ -2971,8 +2945,8 @@ // Type creation/memoization methods //===----------------------------------------------------------------------===// -QualType -ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { +QualType ASTContext::getExtQualType(Type const *baseType, + Qualifiers quals) const { unsigned fastQuals = quals.getFastQualifiers(); quals.removeFastQualifiers(); @@ -2993,7 +2967,7 @@ canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); // Re-find the insert position. - (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); + (void)ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); } auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); @@ -3010,12 +2984,11 @@ // If we are composing extended qualifiers together, merge together // into one ExtQuals node. QualifierCollector Quals; - const Type *TypeNode = Quals.strip(T); + Type const *TypeNode = Quals.strip(T); // If this type already has an address space specified, it cannot get // another one. - assert(!Quals.hasAddressSpace() && - "Type cannot be in multiple addr spaces!"); + assert(!Quals.hasAddressSpace() && "Type cannot be in multiple addr spaces!"); Quals.addAddressSpace(AddressSpace); return getExtQualType(TypeNode, Quals); @@ -3030,7 +3003,7 @@ // If we are composing extended qualifiers together, merge together // into one ExtQuals node. QualifierCollector Quals; - const Type *TypeNode; + Type const *TypeNode; while (T.hasAddressSpace()) { TypeNode = Quals.strip(T); @@ -3061,7 +3034,7 @@ if (CanT.getObjCGCAttr() == GCAttr) return T; - if (const auto *ptr = T->getAs()) { + if (auto const *ptr = T->getAs()) { QualType Pointee = ptr->getPointeeType(); if (Pointee->isAnyPointerType()) { QualType ResultType = getObjCGCQualType(Pointee, GCAttr); @@ -3072,19 +3045,18 @@ // If we are composing extended qualifiers together, merge together // into one ExtQuals node. QualifierCollector Quals; - const Type *TypeNode = Quals.strip(T); + Type const *TypeNode = Quals.strip(T); // If this type already has an ObjCGC specified, it cannot get // another one. - assert(!Quals.hasObjCGCAttr() && - "Type cannot have multiple ObjCGCs!"); + assert(!Quals.hasObjCGCAttr() && "Type cannot have multiple ObjCGCs!"); Quals.addObjCGCAttr(GCAttr); return getExtQualType(TypeNode, Quals); } QualType ASTContext::removePtrSizeAddrSpace(QualType T) const { - if (const PointerType *Ptr = T->getAs()) { + if (PointerType const *Ptr = T->getAs()) { QualType Pointee = Ptr->getPointeeType(); if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) { return getPointerType(removeAddrSpaceQualType(Pointee)); @@ -3093,16 +3065,16 @@ return T; } -const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, +FunctionType const *ASTContext::adjustFunctionType(FunctionType const *T, FunctionType::ExtInfo Info) { if (T->getExtInfo() == Info) return T; QualType Result; - if (const auto *FNPT = dyn_cast(T)) { + if (auto const *FNPT = dyn_cast(T)) { Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); } else { - const auto *FPT = cast(T); + auto const *FPT = cast(T); FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); EPI.ExtInfo = Info; Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); @@ -3115,7 +3087,7 @@ QualType ResultType) { FD = FD->getMostRecentDecl(); while (true) { - const auto *FPT = FD->getType()->castAs(); + auto const *FPT = FD->getType()->castAs(); FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); if (FunctionDecl *Next = FD->getPreviousDecl()) @@ -3132,20 +3104,20 @@ /// declaration of a function with an exception specification is permitted /// and preserved. Other type sugar (for instance, typedefs) is not. QualType ASTContext::getFunctionTypeWithExceptionSpec( - QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) { + QualType Orig, FunctionProtoType::ExceptionSpecInfo const &ESI) { // Might have some parens. - if (const auto *PT = dyn_cast(Orig)) + if (auto const *PT = dyn_cast(Orig)) return getParenType( getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI)); // Might be wrapped in a macro qualified type. - if (const auto *MQT = dyn_cast(Orig)) + if (auto const *MQT = dyn_cast(Orig)) return getMacroQualifiedType( getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI), MQT->getMacroIdentifier()); // Might have a calling-convention attribute. - if (const auto *AT = dyn_cast(Orig)) + if (auto const *AT = dyn_cast(Orig)) return getAttributedType( AT->getAttrKind(), getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI), @@ -3153,10 +3125,9 @@ // Anything else must be a function type. Rebuild it with the new exception // specification. - const auto *Proto = Orig->castAs(); - return getFunctionType( - Proto->getReturnType(), Proto->getParamTypes(), - Proto->getExtProtoInfo().withExceptionSpec(ESI)); + auto const *Proto = Orig->castAs(); + return getFunctionType(Proto->getReturnType(), Proto->getParamTypes(), + Proto->getExtProtoInfo().withExceptionSpec(ESI)); } bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T, @@ -3168,7 +3139,7 @@ } QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) { - if (const auto *Proto = T->getAs()) { + if (auto const *Proto = T->getAs()) { QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); SmallVector Args(Proto->param_types()); for (unsigned i = 0, n = Args.size(); i != n; ++i) @@ -3176,7 +3147,7 @@ return getFunctionType(RetTy, Args, Proto->getExtProtoInfo()); } - if (const FunctionNoProtoType *Proto = T->getAs()) { + if (FunctionNoProtoType const *Proto = T->getAs()) { QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType()); return getFunctionNoProtoType(RetTy, Proto->getExtInfo()); } @@ -3185,17 +3156,15 @@ } bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) { - return hasSameType(T, U) || - hasSameType(getFunctionTypeWithoutPtrSizes(T), - getFunctionTypeWithoutPtrSizes(U)); + return hasSameType(T, U) || hasSameType(getFunctionTypeWithoutPtrSizes(T), + getFunctionTypeWithoutPtrSizes(U)); } void ASTContext::adjustExceptionSpec( - FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, + FunctionDecl *FD, FunctionProtoType::ExceptionSpecInfo const &ESI, bool AsWritten) { // Update the type. - QualType Updated = - getFunctionTypeWithExceptionSpec(FD->getType(), ESI); + QualType Updated = getFunctionTypeWithExceptionSpec(FD->getType(), ESI); FD->setType(Updated); if (!AsWritten) @@ -3238,7 +3207,8 @@ // Get the new insert position for the node we care about. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical); Types.push_back(New); @@ -3266,7 +3236,8 @@ // Get the new insert position for the node we care about. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } auto *New = new (*this, TypeAlignment) PointerType(T, Canonical); Types.push_back(New); @@ -3345,7 +3316,7 @@ void *InsertPos = nullptr; if (BlockPointerType *PT = - BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) + BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(PT, 0); // If the block pointee type isn't canonical, this won't be a canonical @@ -3356,8 +3327,9 @@ // Get the new insert position for the node we care about. BlockPointerType *NewIP = - BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical); Types.push_back(New); @@ -3367,8 +3339,8 @@ /// getLValueReferenceType - Return the uniqued reference to the type for an /// lvalue reference to the specified type. -QualType -ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { +QualType ASTContext::getLValueReferenceType(QualType T, + bool SpelledAsLValue) const { assert(getCanonicalType(T) != OverloadTy && "Unresolved overloaded function type"); @@ -3379,10 +3351,10 @@ void *InsertPos = nullptr; if (LValueReferenceType *RT = - LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) + LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(RT, 0); - const auto *InnerRef = T->getAs(); + auto const *InnerRef = T->getAs(); // If the referencee type isn't canonical, this won't be a canonical type // either, so fill in the canonical type field. @@ -3393,12 +3365,13 @@ // Get the new insert position for the node we care about. LValueReferenceType *NewIP = - LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } - auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, - SpelledAsLValue); + auto *New = new (*this, TypeAlignment) + LValueReferenceType(T, Canonical, SpelledAsLValue); Types.push_back(New); LValueReferenceTypes.InsertNode(New, InsertPos); @@ -3415,10 +3388,10 @@ void *InsertPos = nullptr; if (RValueReferenceType *RT = - RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) + RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(RT, 0); - const auto *InnerRef = T->getAs(); + auto const *InnerRef = T->getAs(); // If the referencee type isn't canonical, this won't be a canonical type // either, so fill in the canonical type field. @@ -3429,8 +3402,9 @@ // Get the new insert position for the node we care about. RValueReferenceType *NewIP = - RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); @@ -3441,7 +3415,7 @@ /// getMemberPointerType - Return the uniqued reference to the type for a /// member pointer to the specified type, in the specified class. -QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { +QualType ASTContext::getMemberPointerType(QualType T, Type const *Cls) const { // Unique pointers, to guarantee there is only one pointer of a particular // structure. llvm::FoldingSetNodeID ID; @@ -3449,19 +3423,21 @@ void *InsertPos = nullptr; if (MemberPointerType *PT = - MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) + MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(PT, 0); // If the pointee or class type isn't canonical, this won't be a canonical // type either, so fill in the canonical type field. QualType Canonical; if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { - Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); + Canonical = + getMemberPointerType(getCanonicalType(T), getCanonicalType(Cls)); // Get the new insert position for the node we care about. MemberPointerType *NewIP = - MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); Types.push_back(New); @@ -3472,12 +3448,12 @@ /// getConstantArrayType - Return the unique reference to the type for an /// array of the specified element type. QualType ASTContext::getConstantArrayType(QualType EltTy, - const llvm::APInt &ArySizeIn, - const Expr *SizeExpr, + llvm::APInt const &ArySizeIn, + Expr const *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const { - assert((EltTy->isDependentType() || - EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && + assert((EltTy->isDependentType() || EltTy->isIncompleteType() || + EltTy->isConstantSizeType()) && "Constant array of VLAs is illegal!"); // We only need the size as part of the type if it's instantiation-dependent. @@ -3495,7 +3471,7 @@ void *InsertPos = nullptr; if (ConstantArrayType *ATP = - ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) + ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(ATP, 0); // If the element type isn't canonical or has qualifiers, or the array bound @@ -3510,15 +3486,16 @@ // Get the new insert position for the node we care about. ConstantArrayType *NewIP = - ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } void *Mem = Allocate( - ConstantArrayType::totalSizeToAlloc(SizeExpr ? 1 : 0), + ConstantArrayType::totalSizeToAlloc(SizeExpr ? 1 : 0), TypeAlignment); auto *New = new (Mem) - ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); + ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals); ConstantArrayTypes.InsertNode(New, InsertPos); Types.push_back(New); return QualType(New, 0); @@ -3529,12 +3506,13 @@ /// sizes replaced with [*]. QualType ASTContext::getVariableArrayDecayedType(QualType type) const { // Vastly most common case. - if (!type->isVariablyModifiedType()) return type; + if (!type->isVariablyModifiedType()) + return type; QualType result; SplitQualType split = type.getSplitDesugaredType(); - const Type *ty = split.Ty; + Type const *ty = split.Ty; switch (ty->getTypeClass()) { #define TYPE(Class, Base) #define ABSTRACT_TYPE(Class, Base) @@ -3589,74 +3567,66 @@ // TODO: if we ever care about optimizing VLAs, there are no-op // optimizations available here. case Type::Pointer: - result = getPointerType(getVariableArrayDecayedType( - cast(ty)->getPointeeType())); + result = getPointerType( + getVariableArrayDecayedType(cast(ty)->getPointeeType())); break; case Type::LValueReference: { - const auto *lv = cast(ty); + auto const *lv = cast(ty); result = getLValueReferenceType( - getVariableArrayDecayedType(lv->getPointeeType()), - lv->isSpelledAsLValue()); + getVariableArrayDecayedType(lv->getPointeeType()), + lv->isSpelledAsLValue()); break; } case Type::RValueReference: { - const auto *lv = cast(ty); + auto const *lv = cast(ty); result = getRValueReferenceType( - getVariableArrayDecayedType(lv->getPointeeType())); + getVariableArrayDecayedType(lv->getPointeeType())); break; } case Type::Atomic: { - const auto *at = cast(ty); + auto const *at = cast(ty); result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); break; } case Type::ConstantArray: { - const auto *cat = cast(ty); + auto const *cat = cast(ty); result = getConstantArrayType( - getVariableArrayDecayedType(cat->getElementType()), - cat->getSize(), - cat->getSizeExpr(), - cat->getSizeModifier(), - cat->getIndexTypeCVRQualifiers()); + getVariableArrayDecayedType(cat->getElementType()), cat->getSize(), + cat->getSizeExpr(), cat->getSizeModifier(), + cat->getIndexTypeCVRQualifiers()); break; } case Type::DependentSizedArray: { - const auto *dat = cast(ty); + auto const *dat = cast(ty); result = getDependentSizedArrayType( - getVariableArrayDecayedType(dat->getElementType()), - dat->getSizeExpr(), - dat->getSizeModifier(), - dat->getIndexTypeCVRQualifiers(), - dat->getBracketsRange()); + getVariableArrayDecayedType(dat->getElementType()), dat->getSizeExpr(), + dat->getSizeModifier(), dat->getIndexTypeCVRQualifiers(), + dat->getBracketsRange()); break; } // Turn incomplete types into [*] types. case Type::IncompleteArray: { - const auto *iat = cast(ty); - result = getVariableArrayType( - getVariableArrayDecayedType(iat->getElementType()), - /*size*/ nullptr, - ArrayType::Normal, - iat->getIndexTypeCVRQualifiers(), - SourceRange()); + auto const *iat = cast(ty); + result = + getVariableArrayType(getVariableArrayDecayedType(iat->getElementType()), + /*size*/ nullptr, ArrayType::Normal, + iat->getIndexTypeCVRQualifiers(), SourceRange()); break; } // Turn VLA types into [*] types. case Type::VariableArray: { - const auto *vat = cast(ty); + auto const *vat = cast(ty); result = getVariableArrayType( - getVariableArrayDecayedType(vat->getElementType()), - /*size*/ nullptr, - ArrayType::Star, - vat->getIndexTypeCVRQualifiers(), - vat->getBracketsRange()); + getVariableArrayDecayedType(vat->getElementType()), + /*size*/ nullptr, ArrayType::Star, vat->getIndexTypeCVRQualifiers(), + vat->getBracketsRange()); break; } } @@ -3667,8 +3637,7 @@ /// getVariableArrayType - Returns a non-unique reference to the type for a /// variable array of the specified element type. -QualType ASTContext::getVariableArrayType(QualType EltTy, - Expr *NumElts, +QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const { @@ -3685,7 +3654,7 @@ } auto *New = new (*this, TypeAlignment) - VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); + VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); VariableArrayTypes.push_back(New); Types.push_back(New); @@ -3695,11 +3664,9 @@ /// getDependentSizedArrayType - Returns a non-unique reference to /// the type for a dependently-sized array of the specified element /// type. -QualType ASTContext::getDependentSizedArrayType(QualType elementType, - Expr *numElements, - ArrayType::ArraySizeModifier ASM, - unsigned elementTypeQuals, - SourceRange brackets) const { +QualType ASTContext::getDependentSizedArrayType( + QualType elementType, Expr *numElements, ArrayType::ArraySizeModifier ASM, + unsigned elementTypeQuals, SourceRange brackets) const { assert((!numElements || numElements->isTypeDependent() || numElements->isValueDependent()) && "Size must be type- or value-dependent!"); @@ -3709,11 +3676,9 @@ // initializer. We do no canonicalization here at all, which is okay // because they can't be used in most locations. if (!numElements) { - auto *newType - = new (*this, TypeAlignment) - DependentSizedArrayType(*this, elementType, QualType(), - numElements, ASM, elementTypeQuals, - brackets); + auto *newType = new (*this, TypeAlignment) + DependentSizedArrayType(*this, elementType, QualType(), numElements, + ASM, elementTypeQuals, brackets); Types.push_back(newType); return QualType(newType, 0); } @@ -3725,27 +3690,25 @@ void *insertPos = nullptr; llvm::FoldingSetNodeID ID; - DependentSizedArrayType::Profile(ID, *this, - QualType(canonElementType.Ty, 0), + DependentSizedArrayType::Profile(ID, *this, QualType(canonElementType.Ty, 0), ASM, elementTypeQuals, numElements); // Look for an existing type with these properties. DependentSizedArrayType *canonTy = - DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); + DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); // If we don't have one, build one. if (!canonTy) { - canonTy = new (*this, TypeAlignment) - DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), - QualType(), numElements, ASM, elementTypeQuals, - brackets); + canonTy = new (*this, TypeAlignment) DependentSizedArrayType( + *this, QualType(canonElementType.Ty, 0), QualType(), numElements, ASM, + elementTypeQuals, brackets); DependentSizedArrayTypes.InsertNode(canonTy, insertPos); Types.push_back(canonTy); } // Apply qualifiers from the element type to the array. - QualType canon = getQualifiedType(QualType(canonTy,0), - canonElementType.Quals); + QualType canon = + getQualifiedType(QualType(canonTy, 0), canonElementType.Quals); // If we didn't need extra canonicalization for the element type or the size // expression, then just use that as our result. @@ -3755,10 +3718,8 @@ // Otherwise, we need to build a type which follows the spelling // of the element type. - auto *sugaredType - = new (*this, TypeAlignment) - DependentSizedArrayType(*this, elementType, canon, numElements, - ASM, elementTypeQuals, brackets); + auto *sugaredType = new (*this, TypeAlignment) DependentSizedArrayType( + *this, elementType, canon, numElements, ASM, elementTypeQuals, brackets); Types.push_back(sugaredType); return QualType(sugaredType, 0); } @@ -3771,7 +3732,7 @@ void *insertPos = nullptr; if (IncompleteArrayType *iat = - IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) + IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) return QualType(iat, 0); // If the element type isn't canonical, this won't be a canonical type @@ -3781,18 +3742,19 @@ if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { SplitQualType canonSplit = getCanonicalType(elementType).split(); - canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), - ASM, elementTypeQuals); + canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), ASM, + elementTypeQuals); canon = getQualifiedType(canon, canonSplit.Quals); // Get the new insert position for the node we care about. IncompleteArrayType *existing = - IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); - assert(!existing && "Shouldn't be in the map!"); (void) existing; + IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); + assert(!existing && "Shouldn't be in the map!"); + (void)existing; } auto *newType = new (*this, TypeAlignment) - IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); + IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); IncompleteArrayTypes.InsertNode(newType, insertPos); Types.push_back(newType); @@ -3800,7 +3762,7 @@ } ASTContext::BuiltinVectorTypeInfo -ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const { +ASTContext::getBuiltinVectorTypeInfo(BuiltinType const *Ty) const { #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \ {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \ NUMVECTORS}; @@ -3952,15 +3914,15 @@ uint64_t EltTySize = getTypeSize(EltTy); #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \ IsFP) \ - if (!EltTy->isBooleanType() && \ - ((EltTy->hasIntegerRepresentation() && \ - EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ - (EltTy->hasFloatingRepresentation() && IsFP)) && \ - EltTySize == ElBits && NumElts == NumEls) \ - return SingletonId; + if (!EltTy->isBooleanType() && \ + ((EltTy->hasIntegerRepresentation() && \ + EltTy->hasSignedIntegerRepresentation() == IsSigned) || \ + (EltTy->hasFloatingRepresentation() && IsFP)) && \ + EltTySize == ElBits && NumElts == NumEls) \ + return SingletonId; #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \ - if (EltTy->isBooleanType() && NumElts == NumEls) \ - return SingletonId; + if (EltTy->isBooleanType() && NumElts == NumEls) \ + return SingletonId; #include "clang/Basic/RISCVVTypes.def" } return QualType(); @@ -3988,10 +3950,11 @@ // Get the new insert position for the node we care about. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } auto *New = new (*this, TypeAlignment) - VectorType(vecType, NumElts, Canonical, VecKind); + VectorType(vecType, NumElts, Canonical, VecKind); VectorTypes.InsertNode(New, InsertPos); Types.push_back(New); return QualType(New, 0); @@ -4038,8 +4001,8 @@ /// getExtVectorType - Return the unique reference to an extended vector type of /// the specified element type and size. VectorType must be a built-in type. -QualType -ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { +QualType ASTContext::getExtVectorType(QualType vecType, + unsigned NumElts) const { assert(vecType->isBuiltinType() || vecType->isDependentType()); // Check if we've already instantiated a vector of this type. @@ -4058,42 +4021,40 @@ // Get the new insert position for the node we care about. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } - auto *New = new (*this, TypeAlignment) - ExtVectorType(vecType, NumElts, Canonical); + auto *New = + new (*this, TypeAlignment) ExtVectorType(vecType, NumElts, Canonical); VectorTypes.InsertNode(New, InsertPos); Types.push_back(New); return QualType(New, 0); } QualType -ASTContext::getDependentSizedExtVectorType(QualType vecType, - Expr *SizeExpr, +ASTContext::getDependentSizedExtVectorType(QualType vecType, Expr *SizeExpr, SourceLocation AttrLoc) const { llvm::FoldingSetNodeID ID; DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), SizeExpr); void *InsertPos = nullptr; - DependentSizedExtVectorType *Canon - = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); + DependentSizedExtVectorType *Canon = + DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); DependentSizedExtVectorType *New; if (Canon) { // We already have a canonical version of this array type; use it as // the canonical type for a newly-built type. - New = new (*this, TypeAlignment) - DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), - SizeExpr, AttrLoc); + New = new (*this, TypeAlignment) DependentSizedExtVectorType( + *this, vecType, QualType(Canon, 0), SizeExpr, AttrLoc); } else { QualType CanonVecTy = getCanonicalType(vecType); if (CanonVecTy == vecType) { - New = new (*this, TypeAlignment) - DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, - AttrLoc); + New = new (*this, TypeAlignment) DependentSizedExtVectorType( + *this, vecType, QualType(), SizeExpr, AttrLoc); - DependentSizedExtVectorType *CanonCheck - = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); + DependentSizedExtVectorType *CanonCheck = + DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); (void)CanonCheck; DependentSizedExtVectorTypes.InsertNode(New, InsertPos); @@ -4181,9 +4142,8 @@ return QualType(New, 0); } -QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType, - Expr *AddrSpaceExpr, - SourceLocation AttrLoc) const { +QualType ASTContext::getDependentAddressSpaceType( + QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttrLoc) const { assert(AddrSpaceExpr->isInstantiationDependent()); QualType canonPointeeType = getCanonicalType(PointeeType); @@ -4194,12 +4154,11 @@ AddrSpaceExpr); DependentAddressSpaceType *canonTy = - DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); + DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos); if (!canonTy) { - canonTy = new (*this, TypeAlignment) - DependentAddressSpaceType(*this, canonPointeeType, - QualType(), AddrSpaceExpr, AttrLoc); + canonTy = new (*this, TypeAlignment) DependentAddressSpaceType( + *this, canonPointeeType, QualType(), AddrSpaceExpr, AttrLoc); DependentAddressSpaceTypes.InsertNode(canonTy, insertPos); Types.push_back(canonTy); } @@ -4208,10 +4167,8 @@ canonTy->getAddrSpaceExpr() == AddrSpaceExpr) return QualType(canonTy, 0); - auto *sugaredType - = new (*this, TypeAlignment) - DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0), - AddrSpaceExpr, AttrLoc); + auto *sugaredType = new (*this, TypeAlignment) DependentAddressSpaceType( + *this, PointeeType, QualType(canonTy, 0), AddrSpaceExpr, AttrLoc); Types.push_back(sugaredType); return QualType(sugaredType, 0); } @@ -4226,7 +4183,7 @@ /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, - const FunctionType::ExtInfo &Info) const { + FunctionType::ExtInfo const &Info) const { // Unique functions, to guarantee there is only one function of a particular // structure. llvm::FoldingSetNodeID ID; @@ -4234,22 +4191,23 @@ void *InsertPos = nullptr; if (FunctionNoProtoType *FT = - FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) + FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(FT, 0); QualType Canonical; if (!isCanonicalResultType(ResultTy)) { Canonical = - getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); + getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info); // Get the new insert position for the node we care about. FunctionNoProtoType *NewIP = - FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } - auto *New = new (*this, TypeAlignment) - FunctionNoProtoType(ResultTy, Canonical, Info); + auto *New = + new (*this, TypeAlignment) FunctionNoProtoType(ResultTy, Canonical, Info); Types.push_back(New); FunctionNoProtoTypes.InsertNode(New, InsertPos); return QualType(New, 0); @@ -4264,14 +4222,14 @@ Qualifiers Qs = CanResultType.getQualifiers(); Qs.removeObjCLifetime(); return CanQualType::CreateUnsafe( - getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); + getQualifiedType(CanResultType.getUnqualifiedType(), Qs)); } return CanResultType; } static bool isCanonicalExceptionSpecification( - const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) { + FunctionProtoType::ExceptionSpecInfo const &ESI, bool NoexceptInType) { if (ESI.Type == EST_None) return true; if (!NoexceptInType) @@ -4306,7 +4264,7 @@ QualType ASTContext::getFunctionTypeInternal( QualType ResultTy, ArrayRef ArgArray, - const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const { + FunctionProtoType::ExtProtoInfo const &EPI, bool OnlyWantCanonical) const { size_t NumArgs = ArgArray.size(); // Unique functions, to guarantee there is only one function of a particular @@ -4320,7 +4278,7 @@ void *InsertPos = nullptr; if (FunctionProtoType *FPT = - FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { + FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) { QualType Existing = QualType(FPT, 0); // If we find a pre-existing equivalent FunctionProtoType, we can just reuse @@ -4371,11 +4329,15 @@ // Exception spec is already OK. } else if (NoexceptInType) { switch (EPI.ExceptionSpec.Type) { - case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated: + case EST_Unparsed: + case EST_Unevaluated: + case EST_Uninstantiated: // We don't know yet. It shouldn't matter what we pick here; no-one // should ever look at this. LLVM_FALLTHROUGH; - case EST_None: case EST_MSAny: case EST_NoexceptFalse: + case EST_None: + case EST_MSAny: + case EST_NoexceptFalse: CanonicalEPI.ExceptionSpec.Type = EST_None; break; @@ -4418,8 +4380,9 @@ // Get the new insert position for the node we care about. FunctionProtoType *NewIP = - FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } // Compute the needed size to hold this FunctionProtoType and the @@ -4518,9 +4481,10 @@ } #ifndef NDEBUG -static bool NeedsInjectedClassNameType(const RecordDecl *D) { - if (!isa(D)) return false; - const auto *RD = cast(D); +static bool NeedsInjectedClassNameType(RecordDecl const *D) { + if (!isa(D)) + return false; + auto const *RD = cast(D); if (isa(RD)) return true; if (RD->getDescribedClassTemplate() && @@ -4542,8 +4506,7 @@ Decl->TypeForDecl = PrevDecl->TypeForDecl; assert(isa(Decl->TypeForDecl)); } else { - Type *newType = - new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); + Type *newType = new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); Decl->TypeForDecl = newType; Types.push_back(newType); } @@ -4552,24 +4515,24 @@ /// getTypeDeclType - Return the unique reference to the type for the /// specified type declaration. -QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { +QualType ASTContext::getTypeDeclTypeSlow(TypeDecl const *Decl) const { assert(Decl && "Passed null for Decl param"); assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); - if (const auto *Typedef = dyn_cast(Decl)) + if (auto const *Typedef = dyn_cast(Decl)) return getTypedefType(Typedef); assert(!isa(Decl) && "Template type parameter types are always available."); - if (const auto *Record = dyn_cast(Decl)) { + if (auto const *Record = dyn_cast(Decl)) { assert(Record->isFirstDecl() && "struct/union has previous declaration"); assert(!NeedsInjectedClassNameType(Record)); return getRecordType(Record); - } else if (const auto *Enum = dyn_cast(Decl)) { + } else if (auto const *Enum = dyn_cast(Decl)) { assert(Enum->isFirstDecl() && "enum has previous declaration"); return getEnumType(Enum); - } else if (const auto *Using = dyn_cast(Decl)) { + } else if (auto const *Using = dyn_cast(Decl)) { Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); Decl->TypeForDecl = newType; Types.push_back(newType); @@ -4581,9 +4544,10 @@ /// getTypedefType - Return the unique reference to the type for the /// specified typedef name decl. -QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl, +QualType ASTContext::getTypedefType(TypedefNameDecl const *Decl, QualType Underlying) const { - if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); + if (Decl->TypeForDecl) + return QualType(Decl->TypeForDecl, 0); if (Underlying.isNull()) Underlying = Decl->getUnderlyingType(); @@ -4595,10 +4559,11 @@ return QualType(newType, 0); } -QualType ASTContext::getRecordType(const RecordDecl *Decl) const { - if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); +QualType ASTContext::getRecordType(RecordDecl const *Decl) const { + if (Decl->TypeForDecl) + return QualType(Decl->TypeForDecl, 0); - if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) + if (RecordDecl const *PrevDecl = Decl->getPreviousDecl()) if (PrevDecl->TypeForDecl) return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); @@ -4608,10 +4573,11 @@ return QualType(newType, 0); } -QualType ASTContext::getEnumType(const EnumDecl *Decl) const { - if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); +QualType ASTContext::getEnumType(EnumDecl const *Decl) const { + if (Decl->TypeForDecl) + return QualType(Decl->TypeForDecl, 0); - if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) + if (EnumDecl const *PrevDecl = Decl->getPreviousDecl()) if (PrevDecl->TypeForDecl) return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); @@ -4629,7 +4595,8 @@ void *insertPos = nullptr; AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); - if (type) return QualType(type, 0); + if (type) + return QualType(type, 0); QualType canon = getCanonicalType(equivalentType); type = new (*this, TypeAlignment) @@ -4643,20 +4610,20 @@ /// Retrieve a substitution-result type. QualType -ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, +ASTContext::getSubstTemplateTypeParmType(TemplateTypeParmType const *Parm, QualType Replacement) const { - assert(Replacement.isCanonical() - && "replacement types must always be canonical"); + assert(Replacement.isCanonical() && + "replacement types must always be canonical"); llvm::FoldingSetNodeID ID; SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); void *InsertPos = nullptr; - SubstTemplateTypeParmType *SubstParm - = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); + SubstTemplateTypeParmType *SubstParm = + SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); if (!SubstParm) { - SubstParm = new (*this, TypeAlignment) - SubstTemplateTypeParmType(Parm, Replacement); + SubstParm = + new (*this, TypeAlignment) SubstTemplateTypeParmType(Parm, Replacement); Types.push_back(SubstParm); SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); } @@ -4665,12 +4632,12 @@ } /// Retrieve a -QualType ASTContext::getSubstTemplateTypeParmPackType( - const TemplateTypeParmType *Parm, - const TemplateArgument &ArgPack) { +QualType +ASTContext::getSubstTemplateTypeParmPackType(TemplateTypeParmType const *Parm, + TemplateArgument const &ArgPack) { #ifndef NDEBUG - for (const auto &P : ArgPack.pack_elements()) { - assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); + for (auto const &P : ArgPack.pack_elements()) { + assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type"); assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); } #endif @@ -4678,8 +4645,8 @@ llvm::FoldingSetNodeID ID; SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); void *InsertPos = nullptr; - if (SubstTemplateTypeParmPackType *SubstParm - = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) + if (SubstTemplateTypeParmPackType *SubstParm = + SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(SubstParm, 0); QualType Canon; @@ -4690,9 +4657,8 @@ SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); } - auto *SubstParm - = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, - ArgPack); + auto *SubstParm = new (*this, TypeAlignment) + SubstTemplateTypeParmPackType(Parm, Canon, ArgPack); Types.push_back(SubstParm); SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos); return QualType(SubstParm, 0); @@ -4701,14 +4667,15 @@ /// Retrieve the template type parameter type for a template /// parameter or parameter pack with the given depth, index, and (optionally) /// name. -QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, - bool ParameterPack, - TemplateTypeParmDecl *TTPDecl) const { +QualType +ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, + bool ParameterPack, + TemplateTypeParmDecl *TTPDecl) const { llvm::FoldingSetNodeID ID; TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); void *InsertPos = nullptr; - TemplateTypeParmType *TypeParm - = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); + TemplateTypeParmType *TypeParm = + TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); if (TypeParm) return QualType(TypeParm, 0); @@ -4717,13 +4684,13 @@ QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); - TemplateTypeParmType *TypeCheck - = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); + TemplateTypeParmType *TypeCheck = + TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); assert(!TypeCheck && "Template type parameter canonical type broken"); (void)TypeCheck; } else TypeParm = new (*this, TypeAlignment) - TemplateTypeParmType(Depth, Index, ParameterPack); + TemplateTypeParmType(Depth, Index, ParameterPack); Types.push_back(TypeParm); TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); @@ -4731,11 +4698,9 @@ return QualType(TypeParm, 0); } -TypeSourceInfo * -ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, - SourceLocation NameLoc, - const TemplateArgumentListInfo &Args, - QualType Underlying) const { +TypeSourceInfo *ASTContext::getTemplateSpecializationTypeInfo( + TemplateName Name, SourceLocation NameLoc, + TemplateArgumentListInfo const &Args, QualType Underlying) const { assert(!Name.getAsDependentTemplateName() && "No dependent template names here!"); QualType TST = getTemplateSpecializationType(Name, Args, Underlying); @@ -4754,14 +4719,14 @@ QualType ASTContext::getTemplateSpecializationType(TemplateName Template, - const TemplateArgumentListInfo &Args, + TemplateArgumentListInfo const &Args, QualType Underlying) const { assert(!Template.getAsDependentTemplateName() && "No dependent template names here!"); SmallVector ArgVec; ArgVec.reserve(Args.size()); - for (const TemplateArgumentLoc &Arg : Args.arguments()) + for (TemplateArgumentLoc const &Arg : Args.arguments()) ArgVec.push_back(Arg.getArgument()); return getTemplateSpecializationType(Template, ArgVec, Underlying); @@ -4769,7 +4734,7 @@ #ifndef NDEBUG static bool hasAnyPackExpansions(ArrayRef Args) { - for (const TemplateArgument &Arg : Args) + for (TemplateArgument const &Arg : Args) if (Arg.isPackExpansion()) return true; @@ -4787,9 +4752,8 @@ if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) Template = TemplateName(QTN->getTemplateDecl()); - bool IsTypeAlias = - Template.getAsTemplateDecl() && - isa(Template.getAsTemplateDecl()); + bool IsTypeAlias = Template.getAsTemplateDecl() && + isa(Template.getAsTemplateDecl()); QualType CanonType; if (!Underlying.isNull()) CanonType = getCanonicalType(Underlying); @@ -4806,12 +4770,11 @@ // try to unique it: these types typically have location information that // we don't unique and don't want to lose. void *Mem = Allocate(sizeof(TemplateSpecializationType) + - sizeof(TemplateArgument) * Args.size() + - (IsTypeAlias? sizeof(QualType) : 0), + sizeof(TemplateArgument) * Args.size() + + (IsTypeAlias ? sizeof(QualType) : 0), TypeAlignment); - auto *Spec - = new (Mem) TemplateSpecializationType(Template, Args, CanonType, - IsTypeAlias ? Underlying : QualType()); + auto *Spec = new (Mem) TemplateSpecializationType( + Template, Args, CanonType, IsTypeAlias ? Underlying : QualType()); Types.push_back(Spec); return QualType(Spec, 0); @@ -4831,26 +4794,24 @@ SmallVector CanonArgs; unsigned NumArgs = Args.size(); CanonArgs.reserve(NumArgs); - for (const TemplateArgument &Arg : Args) + for (TemplateArgument const &Arg : Args) CanonArgs.push_back(getCanonicalTemplateArgument(Arg)); // Determine whether this canonical template specialization type already // exists. llvm::FoldingSetNodeID ID; - TemplateSpecializationType::Profile(ID, CanonTemplate, - CanonArgs, *this); + TemplateSpecializationType::Profile(ID, CanonTemplate, CanonArgs, *this); void *InsertPos = nullptr; - TemplateSpecializationType *Spec - = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); + TemplateSpecializationType *Spec = + TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); if (!Spec) { // Allocate a new canonical template specialization type. void *Mem = Allocate((sizeof(TemplateSpecializationType) + sizeof(TemplateArgument) * NumArgs), TypeAlignment); - Spec = new (Mem) TemplateSpecializationType(CanonTemplate, - CanonArgs, + Spec = new (Mem) TemplateSpecializationType(CanonTemplate, CanonArgs, QualType(), QualType()); Types.push_back(Spec); TemplateSpecializationTypes.InsertNode(Spec, InsertPos); @@ -4881,8 +4842,9 @@ (void)CheckT; } - void *Mem = Allocate(ElaboratedType::totalSizeToAlloc(!!OwnedTagDecl), - TypeAlignment); + void *Mem = + Allocate(ElaboratedType::totalSizeToAlloc(!!OwnedTagDecl), + TypeAlignment); T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl); Types.push_back(T); @@ -4890,8 +4852,7 @@ return QualType(T, 0); } -QualType -ASTContext::getParenType(QualType InnerType) const { +QualType ASTContext::getParenType(QualType InnerType) const { llvm::FoldingSetNodeID ID; ParenType::Profile(ID, InnerType); @@ -4916,7 +4877,7 @@ QualType ASTContext::getMacroQualifiedType(QualType UnderlyingTy, - const IdentifierInfo *MacroII) const { + IdentifierInfo const *MacroII) const { QualType Canon = UnderlyingTy; if (!Canon.isCanonical()) Canon = getCanonicalType(UnderlyingTy); @@ -4929,7 +4890,7 @@ QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, - const IdentifierInfo *Name, + IdentifierInfo const *Name, QualType Canon) const { if (Canon.isNull()) { NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); @@ -4941,8 +4902,7 @@ DependentNameType::Profile(ID, Keyword, NNS, Name); void *InsertPos = nullptr; - DependentNameType *T - = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); + DependentNameType *T = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); @@ -4952,12 +4912,9 @@ return QualType(T, 0); } -QualType -ASTContext::getDependentTemplateSpecializationType( - ElaboratedTypeKeyword Keyword, - NestedNameSpecifier *NNS, - const IdentifierInfo *Name, - const TemplateArgumentListInfo &Args) const { +QualType ASTContext::getDependentTemplateSpecializationType( + ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, + IdentifierInfo const *Name, TemplateArgumentListInfo const &Args) const { // TODO: avoid this copy SmallVector ArgCopy; for (unsigned I = 0, E = Args.size(); I != E; ++I) @@ -4965,29 +4922,27 @@ return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy); } -QualType -ASTContext::getDependentTemplateSpecializationType( - ElaboratedTypeKeyword Keyword, - NestedNameSpecifier *NNS, - const IdentifierInfo *Name, - ArrayRef Args) const { +QualType ASTContext::getDependentTemplateSpecializationType( + ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, + IdentifierInfo const *Name, ArrayRef Args) const { assert((!NNS || NNS->isDependent()) && "nested-name-specifier must be dependent"); llvm::FoldingSetNodeID ID; - DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, - Name, Args); + DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, Name, + Args); void *InsertPos = nullptr; - DependentTemplateSpecializationType *T - = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); + DependentTemplateSpecializationType *T = + DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); if (T) return QualType(T, 0); NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); ElaboratedTypeKeyword CanonKeyword = Keyword; - if (Keyword == ETK_None) CanonKeyword = ETK_Typename; + if (Keyword == ETK_None) + CanonKeyword = ETK_Typename; bool AnyNonCanonArgs = false; unsigned NumArgs = Args.size(); @@ -5000,8 +4955,7 @@ QualType Canon; if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { - Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, - Name, + Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, Name, CanonArgs); // Find the insert position again. @@ -5011,8 +4965,8 @@ void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + sizeof(TemplateArgument) * NumArgs), TypeAlignment); - T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, - Name, Args, Canon); + T = new (Mem) + DependentTemplateSpecializationType(Keyword, NNS, Name, Args, Canon); Types.push_back(T); DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); return QualType(T, 0); @@ -5020,7 +4974,7 @@ TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) { TemplateArgument Arg; - if (const auto *TTP = dyn_cast(Param)) { + if (auto const *TTP = dyn_cast(Param)) { QualType ArgType = getTypeDeclType(TTP); if (TTP->isParameterPack()) ArgType = getPackExpansionType(ArgType, None); @@ -5040,8 +4994,8 @@ Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation()); if (NTTP->isParameterPack()) - E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(), - None); + E = new (*this) + PackExpansionExpr(DependentTy, E, NTTP->getLocation(), None); Arg = TemplateArgument(E); } else { auto *TTP = cast(Param); @@ -5057,9 +5011,9 @@ return Arg; } -void -ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params, - SmallVectorImpl &Args) { +void ASTContext::getInjectedTemplateArgs( + TemplateParameterList const *Params, + SmallVectorImpl &Args) { Args.reserve(Args.size() + Params->size()); for (NamedDecl *Param : *Params) @@ -5105,7 +5059,8 @@ } static bool areSortedAndUniqued(ArrayRef Protocols) { - if (Protocols.empty()) return true; + if (Protocols.empty()) + return true; if (Protocols[0]->getCanonicalDecl() != Protocols[0]) return false; @@ -5132,18 +5087,17 @@ } QualType ASTContext::getObjCObjectType(QualType BaseType, - ObjCProtocolDecl * const *Protocols, + ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const { return getObjCObjectType(BaseType, {}, llvm::makeArrayRef(Protocols, NumProtocols), /*isKindOf=*/false); } -QualType ASTContext::getObjCObjectType( - QualType baseType, - ArrayRef typeArgs, - ArrayRef protocols, - bool isKindOf) const { +QualType ASTContext::getObjCObjectType(QualType baseType, + ArrayRef typeArgs, + ArrayRef protocols, + bool isKindOf) const { // If the base type is an interface and there aren't any protocols or // type arguments to add, then the interface type will do just fine. if (typeArgs.empty() && protocols.empty() && !isKindOf && @@ -5162,7 +5116,7 @@ // type. ArrayRef effectiveTypeArgs = typeArgs; if (effectiveTypeArgs.empty()) { - if (const auto *baseObject = baseType->getAs()) + if (auto const *baseObject = baseType->getAs()) effectiveTypeArgs = baseObject->getTypeArgs(); } @@ -5170,11 +5124,9 @@ // sorted-and-uniqued list of protocols and the type arguments // canonicalized. QualType canonical; - bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(), - effectiveTypeArgs.end(), - [&](QualType type) { - return type.isCanonical(); - }); + bool typeArgsAreCanonical = + std::all_of(effectiveTypeArgs.begin(), effectiveTypeArgs.end(), + [&](QualType type) { return type.isCanonical(); }); bool protocolsSorted = areSortedAndUniqued(protocols); if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) { // Determine the canonical type arguments. @@ -5190,7 +5142,7 @@ } ArrayRef canonProtocols; - SmallVector canonProtocolsVec; + SmallVector canonProtocolsVec; if (!protocolsSorted) { canonProtocolsVec.append(protocols.begin(), protocols.end()); SortAndUniqueProtocols(canonProtocolsVec); @@ -5210,9 +5162,8 @@ size += typeArgs.size() * sizeof(QualType); size += protocols.size() * sizeof(ObjCProtocolDecl *); void *mem = Allocate(size, TypeAlignment); - auto *T = - new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, - isKindOf); + auto *T = new (mem) + ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols, isKindOf); Types.push_back(T); ObjCObjectTypes.InsertNode(T, InsertPos); @@ -5222,45 +5173,39 @@ /// Apply Objective-C protocol qualifiers to the given type. /// If this is for the canonical type of a type parameter, we can apply /// protocol qualifiers on the ObjCObjectPointerType. -QualType -ASTContext::applyObjCProtocolQualifiers(QualType type, - ArrayRef protocols, bool &hasError, - bool allowOnPointerType) const { +QualType ASTContext::applyObjCProtocolQualifiers( + QualType type, ArrayRef protocols, bool &hasError, + bool allowOnPointerType) const { hasError = false; - if (const auto *objT = dyn_cast(type.getTypePtr())) { + if (auto const *objT = dyn_cast(type.getTypePtr())) { return getObjCTypeParamType(objT->getDecl(), protocols); } // Apply protocol qualifiers to ObjCObjectPointerType. if (allowOnPointerType) { - if (const auto *objPtr = + if (auto const *objPtr = dyn_cast(type.getTypePtr())) { - const ObjCObjectType *objT = objPtr->getObjectType(); + ObjCObjectType const *objT = objPtr->getObjectType(); // Merge protocol lists and construct ObjCObjectType. - SmallVector protocolsVec; - protocolsVec.append(objT->qual_begin(), - objT->qual_end()); + SmallVector protocolsVec; + protocolsVec.append(objT->qual_begin(), objT->qual_end()); protocolsVec.append(protocols.begin(), protocols.end()); ArrayRef protocols = protocolsVec; - type = getObjCObjectType( - objT->getBaseType(), - objT->getTypeArgsAsWritten(), - protocols, - objT->isKindOfTypeAsWritten()); + type = + getObjCObjectType(objT->getBaseType(), objT->getTypeArgsAsWritten(), + protocols, objT->isKindOfTypeAsWritten()); return getObjCObjectPointerType(type); } } // Apply protocol qualifiers to ObjCObjectType. - if (const auto *objT = dyn_cast(type.getTypePtr())){ + if (auto const *objT = dyn_cast(type.getTypePtr())) { // FIXME: Check for protocols to which the class type is already // known to conform. - return getObjCObjectType(objT->getBaseType(), - objT->getTypeArgsAsWritten(), - protocols, - objT->isKindOfTypeAsWritten()); + return getObjCObjectType(objT->getBaseType(), objT->getTypeArgsAsWritten(), + protocols, objT->isKindOfTypeAsWritten()); } // If the canonical type is ObjCObjectType, ... @@ -5275,17 +5220,17 @@ // id if (type->isObjCIdType()) { - const auto *objPtr = type->castAs(); + auto const *objPtr = type->castAs(); type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols, - objPtr->isKindOfType()); + objPtr->isKindOfType()); return getObjCObjectPointerType(type); } // Class if (type->isObjCClassType()) { - const auto *objPtr = type->castAs(); + auto const *objPtr = type->castAs(); type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols, - objPtr->isKindOfType()); + objPtr->isKindOfType()); return getObjCObjectPointerType(type); } @@ -5294,14 +5239,14 @@ } QualType -ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl, +ASTContext::getObjCTypeParamType(ObjCTypeParamDecl const *Decl, ArrayRef protocols) const { // Look in the folding set for an existing type. llvm::FoldingSetNodeID ID; ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols); void *InsertPos = nullptr; if (ObjCTypeParamType *TypeParam = - ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) + ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(TypeParam, 0); // We canonicalize to the underlying type. @@ -5324,7 +5269,7 @@ return QualType(newType, 0); } -void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, +void ASTContext::adjustObjCTypeParamBoundType(ObjCTypeParamDecl const *Orig, ObjCTypeParamDecl *New) const { New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType())); // Update TypeForDecl after updating TypeSourceInfo. @@ -5343,7 +5288,7 @@ if (!QT->isObjCQualifiedIdType()) return false; - if (const auto *OPT = QT->getAs()) { + if (auto const *OPT = QT->getAs()) { // If both the right and left sides have qualifiers. for (auto *Proto : OPT->quals()) { if (!IC->ClassImplementsProtocol(Proto, false)) @@ -5357,11 +5302,11 @@ /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in /// QT's qualified-id protocol list adopt all protocols in IDecl's list /// of protocols. -bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, - ObjCInterfaceDecl *IDecl) { +bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols( + QualType QT, ObjCInterfaceDecl *IDecl) { if (!QT->isObjCQualifiedIdType()) return false; - const auto *OPT = QT->getAs(); + auto const *OPT = QT->getAs(); if (!OPT) return false; if (!IDecl->hasDefinition()) @@ -5409,7 +5354,7 @@ void *InsertPos = nullptr; if (ObjCObjectPointerType *QT = - ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) + ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) return QualType(QT, 0); // Find the canonical object type. @@ -5423,8 +5368,7 @@ // No match. void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); - auto *QType = - new (Mem) ObjCObjectPointerType(Canonical, ObjectT); + auto *QType = new (Mem) ObjCObjectPointerType(Canonical, ObjectT); Types.push_back(QType); ObjCObjectPointerTypes.InsertNode(QType, InsertPos); @@ -5433,7 +5377,7 @@ /// getObjCInterfaceType - Return the unique reference to the type for the /// specified ObjC interface decl. The list of protocols is optional. -QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, +QualType ASTContext::getObjCInterfaceType(ObjCInterfaceDecl const *Decl, ObjCInterfaceDecl *PrevDecl) const { if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); @@ -5445,7 +5389,7 @@ } // Prefer the definition, if there is one. - if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) + if (ObjCInterfaceDecl const *Def = Decl->getDefinition()) Decl = Def; void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); @@ -5467,17 +5411,17 @@ DependentTypeOfExprType::Profile(ID, *this, tofExpr); void *InsertPos = nullptr; - DependentTypeOfExprType *Canon - = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); + DependentTypeOfExprType *Canon = + DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); if (Canon) { // We already have a "canonical" version of an identical, dependent // typeof(expr) type. Use that as our canonical type. - toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, - QualType((TypeOfExprType*)Canon, 0)); + toe = new (*this, TypeAlignment) + TypeOfExprType(tofExpr, QualType((TypeOfExprType *)Canon, 0)); } else { // Build a new, canonical typeof(expr) type. - Canon - = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); + Canon = + new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); toe = Canon; } @@ -5504,7 +5448,7 @@ /// getReferenceQualifiedType - Given an expr, will return the type for /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions /// and class member access into account. -QualType ASTContext::getReferenceQualifiedType(const Expr *E) const { +QualType ASTContext::getReferenceQualifiedType(Expr const *E) const { // C++11 [dcl.type.simple]p4: // [...] QualType T = E->getType(); @@ -5540,8 +5484,8 @@ DependentDecltypeType::Profile(ID, *this, e); void *InsertPos = nullptr; - DependentDecltypeType *Canon - = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); + DependentDecltypeType *Canon = + DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); if (!Canon) { // Build a new, canonical decltype(expr) type. Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); @@ -5559,10 +5503,9 @@ /// getUnaryTransformationType - We don't unique these, since the memory /// savings are minimal and these are rare. -QualType ASTContext::getUnaryTransformType(QualType BaseType, - QualType UnderlyingType, - UnaryTransformType::UTTKind Kind) - const { +QualType +ASTContext::getUnaryTransformType(QualType BaseType, QualType UnderlyingType, + UnaryTransformType::UTTKind Kind) const { UnaryTransformType *ut = nullptr; if (BaseType->isDependentType()) { @@ -5571,24 +5514,21 @@ DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind); void *InsertPos = nullptr; - DependentUnaryTransformType *Canon - = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); + DependentUnaryTransformType *Canon = + DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos); if (!Canon) { // Build a new, canonical __underlying_type(type) type. Canon = new (*this, TypeAlignment) - DependentUnaryTransformType(*this, getCanonicalType(BaseType), - Kind); + DependentUnaryTransformType(*this, getCanonicalType(BaseType), Kind); DependentUnaryTransformTypes.InsertNode(Canon, InsertPos); } - ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, - QualType(), Kind, - QualType(Canon, 0)); + ut = new (*this, TypeAlignment) + UnaryTransformType(BaseType, QualType(), Kind, QualType(Canon, 0)); } else { QualType CanonType = getCanonicalType(UnderlyingType); - ut = new (*this, TypeAlignment) UnaryTransformType (BaseType, - UnderlyingType, Kind, - CanonType); + ut = new (*this, TypeAlignment) + UnaryTransformType(BaseType, UnderlyingType, Kind, CanonType); } Types.push_back(ut); return QualType(ut, 0); @@ -5616,7 +5556,7 @@ return QualType(AT, 0); void *Mem = Allocate(sizeof(AutoType) + - sizeof(TemplateArgument) * TypeConstraintArgs.size(), + sizeof(TemplateArgument) * TypeConstraintArgs.size(), TypeAlignment); auto *AT = new (Mem) AutoType( DeducedType, Keyword, @@ -5672,7 +5612,8 @@ // Get the new insert position for the node we care about. AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); - assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; + assert(!NewIP && "Shouldn't be in the map!"); + (void)NewIP; } auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical); Types.push_back(New); @@ -5701,11 +5642,11 @@ /// getTagDeclType - Return the unique reference to the type for the /// specified TagDecl (struct/union/class/enum) decl. -QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { +QualType ASTContext::getTagDeclType(TagDecl const *Decl) const { assert(Decl); // FIXME: What is the design on getTagDeclType when it requires casting // away const? mutable? - return getTypeDeclType(const_cast(Decl)); + return getTypeDeclType(const_cast(Decl)); } /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result @@ -5781,10 +5722,10 @@ // qualifiers. T = getCanonicalType(T); T = getVariableArrayDecayedType(T); - const Type *Ty = T.getTypePtr(); + Type const *Ty = T.getTypePtr(); QualType Result; if (isa(Ty)) { - Result = getArrayDecayedType(QualType(Ty,0)); + Result = getArrayDecayedType(QualType(Ty, 0)); } else if (isa(Ty)) { Result = getPointerType(QualType(Ty, 0)); } else { @@ -5794,15 +5735,14 @@ return CanQualType::CreateUnsafe(Result); } -QualType ASTContext::getUnqualifiedArrayType(QualType type, - Qualifiers &quals) { +QualType ASTContext::getUnqualifiedArrayType(QualType type, Qualifiers &quals) { SplitQualType splitType = type.getSplitUnqualifiedType(); // FIXME: getSplitUnqualifiedType() actually walks all the way to // the unqualified desugared type and then drops it on the floor. // We then have to strip that sugar back off with // getUnqualifiedDesugaredType(), which is silly. - const auto *AT = + auto const *AT = dyn_cast(splitType.Ty->getUnqualifiedDesugaredType()); // If we don't have an array, just use the results in splitType. @@ -5827,27 +5767,24 @@ // build the type back up. quals.addConsistentQualifiers(splitType.Quals); - if (const auto *CAT = dyn_cast(AT)) { + if (auto const *CAT = dyn_cast(AT)) { return getConstantArrayType(unqualElementType, CAT->getSize(), CAT->getSizeExpr(), CAT->getSizeModifier(), 0); } - if (const auto *IAT = dyn_cast(AT)) { + if (auto const *IAT = dyn_cast(AT)) { return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); } - if (const auto *VAT = dyn_cast(AT)) { - return getVariableArrayType(unqualElementType, - VAT->getSizeExpr(), - VAT->getSizeModifier(), - VAT->getIndexTypeCVRQualifiers(), - VAT->getBracketsRange()); + if (auto const *VAT = dyn_cast(AT)) { + return getVariableArrayType( + unqualElementType, VAT->getSizeExpr(), VAT->getSizeModifier(), + VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange()); } - const auto *DSAT = cast(AT); + auto const *DSAT = cast(AT); return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), - DSAT->getSizeModifier(), 0, - SourceRange()); + DSAT->getSizeModifier(), 0, SourceRange()); } /// Attempt to unwrap two types that may both be array types with the same bound @@ -5894,16 +5831,16 @@ bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) { UnwrapSimilarArrayTypes(T1, T2); - const auto *T1PtrType = T1->getAs(); - const auto *T2PtrType = T2->getAs(); + auto const *T1PtrType = T1->getAs(); + auto const *T2PtrType = T2->getAs(); if (T1PtrType && T2PtrType) { T1 = T1PtrType->getPointeeType(); T2 = T2PtrType->getPointeeType(); return true; } - const auto *T1MPType = T1->getAs(); - const auto *T2MPType = T2->getAs(); + auto const *T1MPType = T1->getAs(); + auto const *T2MPType = T2->getAs(); if (T1MPType && T2MPType && hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), QualType(T2MPType->getClass(), 0))) { @@ -5913,8 +5850,8 @@ } if (getLangOpts().ObjC) { - const auto *T1OPType = T1->getAs(); - const auto *T2OPType = T2->getAs(); + auto const *T1OPType = T1->getAs(); + auto const *T2OPType = T2->getAs(); if (T1OPType && T2OPType) { T1 = T1OPType->getPointeeType(); T2 = T2OPType->getPointeeType(); @@ -5995,15 +5932,14 @@ } case TemplateName::SubstTemplateTemplateParm: { - SubstTemplateTemplateParmStorage *subst - = Name.getAsSubstTemplateTemplateParm(); - return DeclarationNameInfo(subst->getParameter()->getDeclName(), - NameLoc); + SubstTemplateTemplateParmStorage *subst = + Name.getAsSubstTemplateTemplateParm(); + return DeclarationNameInfo(subst->getParameter()->getDeclName(), NameLoc); } case TemplateName::SubstTemplateTemplateParmPack: { - SubstTemplateTemplateParmPackStorage *subst - = Name.getAsSubstTemplateTemplateParmPack(); + SubstTemplateTemplateParmPackStorage *subst = + Name.getAsSubstTemplateTemplateParmPack(); return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), NameLoc); } @@ -6017,7 +5953,7 @@ case TemplateName::QualifiedTemplate: case TemplateName::Template: { TemplateDecl *Template = Name.getAsTemplateDecl(); - if (auto *TTP = dyn_cast(Template)) + if (auto *TTP = dyn_cast(Template)) Template = getCanonicalTemplateTemplateParmDecl(TTP); // The canonical template name is the canonical template declaration. @@ -6035,18 +5971,18 @@ } case TemplateName::SubstTemplateTemplateParm: { - SubstTemplateTemplateParmStorage *subst - = Name.getAsSubstTemplateTemplateParm(); + SubstTemplateTemplateParmStorage *subst = + Name.getAsSubstTemplateTemplateParm(); return getCanonicalTemplateName(subst->getReplacement()); } case TemplateName::SubstTemplateTemplateParmPack: { - SubstTemplateTemplateParmPackStorage *subst - = Name.getAsSubstTemplateTemplateParmPack(); - TemplateTemplateParmDecl *canonParameter - = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); - TemplateArgument canonArgPack - = getCanonicalTemplateArgument(subst->getArgumentPack()); + SubstTemplateTemplateParmPackStorage *subst = + Name.getAsSubstTemplateTemplateParmPack(); + TemplateTemplateParmDecl *canonParameter = + getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); + TemplateArgument canonArgPack = + getCanonicalTemplateArgument(subst->getArgumentPack()); return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); } } @@ -6061,50 +5997,50 @@ } TemplateArgument -ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { +ASTContext::getCanonicalTemplateArgument(TemplateArgument const &Arg) const { switch (Arg.getKind()) { - case TemplateArgument::Null: - return Arg; + case TemplateArgument::Null: + return Arg; - case TemplateArgument::Expression: - return Arg; + case TemplateArgument::Expression: + return Arg; - case TemplateArgument::Declaration: { - auto *D = cast(Arg.getAsDecl()->getCanonicalDecl()); - return TemplateArgument(D, Arg.getParamTypeForDecl()); - } + case TemplateArgument::Declaration: { + auto *D = cast(Arg.getAsDecl()->getCanonicalDecl()); + return TemplateArgument(D, Arg.getParamTypeForDecl()); + } - case TemplateArgument::NullPtr: - return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), - /*isNullPtr*/true); + case TemplateArgument::NullPtr: + return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), + /*isNullPtr*/ true); - case TemplateArgument::Template: - return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); + case TemplateArgument::Template: + return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); - case TemplateArgument::TemplateExpansion: - return TemplateArgument(getCanonicalTemplateName( - Arg.getAsTemplateOrTemplatePattern()), - Arg.getNumTemplateExpansions()); + case TemplateArgument::TemplateExpansion: + return TemplateArgument( + getCanonicalTemplateName(Arg.getAsTemplateOrTemplatePattern()), + Arg.getNumTemplateExpansions()); - case TemplateArgument::Integral: - return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); + case TemplateArgument::Integral: + return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); - case TemplateArgument::Type: - return TemplateArgument(getCanonicalType(Arg.getAsType())); + case TemplateArgument::Type: + return TemplateArgument(getCanonicalType(Arg.getAsType())); - case TemplateArgument::Pack: { - if (Arg.pack_size() == 0) - return Arg; + case TemplateArgument::Pack: { + if (Arg.pack_size() == 0) + return Arg; - auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; - unsigned Idx = 0; - for (TemplateArgument::pack_iterator A = Arg.pack_begin(), - AEnd = Arg.pack_end(); - A != AEnd; (void)++A, ++Idx) - CanonArgs[Idx] = getCanonicalTemplateArgument(*A); + auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()]; + unsigned Idx = 0; + for (TemplateArgument::pack_iterator A = Arg.pack_begin(), + AEnd = Arg.pack_end(); + A != AEnd; (void)++A, ++Idx) + CanonArgs[Idx] = getCanonicalTemplateArgument(*A); - return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); - } + return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size())); + } } // Silence GCC warning @@ -6119,28 +6055,28 @@ switch (NNS->getKind()) { case NestedNameSpecifier::Identifier: // Canonicalize the prefix but keep the identifier the same. - return NestedNameSpecifier::Create(*this, - getCanonicalNestedNameSpecifier(NNS->getPrefix()), - NNS->getAsIdentifier()); + return NestedNameSpecifier::Create( + *this, getCanonicalNestedNameSpecifier(NNS->getPrefix()), + NNS->getAsIdentifier()); case NestedNameSpecifier::Namespace: // A namespace is canonical; build a nested-name-specifier with // this namespace and no prefix. - return NestedNameSpecifier::Create(*this, nullptr, - NNS->getAsNamespace()->getOriginalNamespace()); + return NestedNameSpecifier::Create( + *this, nullptr, NNS->getAsNamespace()->getOriginalNamespace()); case NestedNameSpecifier::NamespaceAlias: // A namespace is canonical; build a nested-name-specifier with // this namespace and no prefix. - return NestedNameSpecifier::Create(*this, nullptr, - NNS->getAsNamespaceAlias()->getNamespace() - ->getOriginalNamespace()); + return NestedNameSpecifier::Create( + *this, nullptr, + NNS->getAsNamespaceAlias()->getNamespace()->getOriginalNamespace()); // The difference between TypeSpec and TypeSpecWithTemplate is that the // latter will have the 'template' keyword when printed. case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { - const Type *T = getCanonicalType(NNS->getAsType()); + Type const *T = getCanonicalType(NNS->getAsType()); // If we have some kind of dependent-named type (e.g., "typename T::type"), // break it apart into its prefix and identifier, then reconsititute those @@ -6149,11 +6085,11 @@ // types, e.g., // typedef typename T::type T1; // typedef typename T1::type T2; - if (const auto *DNT = T->getAs()) + if (auto const *DNT = T->getAs()) return NestedNameSpecifier::Create( *this, DNT->getQualifier(), const_cast(DNT->getIdentifier())); - if (const auto *DTST = T->getAs()) + if (auto const *DTST = T->getAs()) return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true, const_cast(T)); @@ -6171,11 +6107,11 @@ llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); } -const ArrayType *ASTContext::getAsArrayType(QualType T) const { +ArrayType const *ASTContext::getAsArrayType(QualType T) const { // Handle the non-qualified case efficiently. if (!T.hasLocalQualifiers()) { // Handle the common positive case fast. - if (const auto *AT = dyn_cast(T)) + if (auto const *AT = dyn_cast(T)) return AT; } @@ -6195,7 +6131,7 @@ Qualifiers qs = split.Quals; // If we have a simple case, just return now. - const auto *ATy = dyn_cast(split.Ty); + auto const *ATy = dyn_cast(split.Ty); if (!ATy || qs.empty()) return ATy; @@ -6203,30 +6139,23 @@ // qualifiers into the array element type and return a new array type. QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); - if (const auto *CAT = dyn_cast(ATy)) - return cast(getConstantArrayType(NewEltTy, CAT->getSize(), - CAT->getSizeExpr(), - CAT->getSizeModifier(), - CAT->getIndexTypeCVRQualifiers())); - if (const auto *IAT = dyn_cast(ATy)) - return cast(getIncompleteArrayType(NewEltTy, - IAT->getSizeModifier(), - IAT->getIndexTypeCVRQualifiers())); - - if (const auto *DSAT = dyn_cast(ATy)) - return cast( - getDependentSizedArrayType(NewEltTy, - DSAT->getSizeExpr(), - DSAT->getSizeModifier(), - DSAT->getIndexTypeCVRQualifiers(), - DSAT->getBracketsRange())); - - const auto *VAT = cast(ATy); - return cast(getVariableArrayType(NewEltTy, - VAT->getSizeExpr(), - VAT->getSizeModifier(), - VAT->getIndexTypeCVRQualifiers(), - VAT->getBracketsRange())); + if (auto const *CAT = dyn_cast(ATy)) + return cast(getConstantArrayType( + NewEltTy, CAT->getSize(), CAT->getSizeExpr(), CAT->getSizeModifier(), + CAT->getIndexTypeCVRQualifiers())); + if (auto const *IAT = dyn_cast(ATy)) + return cast(getIncompleteArrayType( + NewEltTy, IAT->getSizeModifier(), IAT->getIndexTypeCVRQualifiers())); + + if (auto const *DSAT = dyn_cast(ATy)) + return cast(getDependentSizedArrayType( + NewEltTy, DSAT->getSizeExpr(), DSAT->getSizeModifier(), + DSAT->getIndexTypeCVRQualifiers(), DSAT->getBracketsRange())); + + auto const *VAT = cast(ATy); + return cast(getVariableArrayType( + NewEltTy, VAT->getSizeExpr(), VAT->getSizeModifier(), + VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange())); } QualType ASTContext::getAdjustedParameterType(QualType T) const { @@ -6265,14 +6194,14 @@ // typedefs in the element type of the array. This also handles propagation // of type qualifiers from the array type into the element type if present // (C99 6.7.3p8). - const ArrayType *PrettyArrayType = getAsArrayType(Ty); + ArrayType const *PrettyArrayType = getAsArrayType(Ty); assert(PrettyArrayType && "Not an array type!"); QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); // int x[restrict 4] -> int *restrict - QualType Result = getQualifiedType(PtrTy, - PrettyArrayType->getIndexTypeQualifiers()); + QualType Result = + getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); // int x[_Nullable] -> int * _Nullable if (auto Nullability = Ty->getNullability(*this)) { @@ -6282,7 +6211,7 @@ return Result; } -QualType ASTContext::getBaseElementType(const ArrayType *array) const { +QualType ASTContext::getBaseElementType(ArrayType const *array) const { return getBaseElementType(array->getElementType()); } @@ -6290,8 +6219,9 @@ Qualifiers qs; while (true) { SplitQualType split = type.getSplitDesugaredType(); - const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); - if (!array) break; + ArrayType const *array = split.Ty->getAsArrayTypeUnsafe(); + if (!array) + break; type = array->getElementType(); qs.addConsistentQualifiers(split.Quals); @@ -6302,12 +6232,12 @@ /// getConstantArrayElementCount - Returns number of constant array elements. uint64_t -ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { +ASTContext::getConstantArrayElementCount(ConstantArrayType const *CA) const { uint64_t ElementCount = 1; do { ElementCount *= CA->getSize().getZExtValue(); CA = dyn_cast_or_null( - CA->getElementType()->getAsArrayTypeUnsafe()); + CA->getElementType()->getAsArrayTypeUnsafe()); } while (CA); return ElementCount; } @@ -6315,19 +6245,28 @@ /// getFloatingRank - Return a relative rank for floating point types. /// This routine will assert if passed a built-in type that isn't a float. static FloatingRank getFloatingRank(QualType T) { - if (const auto *CT = T->getAs()) + if (auto const *CT = T->getAs()) return getFloatingRank(CT->getElementType()); switch (T->castAs()->getKind()) { - default: llvm_unreachable("getFloatingRank(): not a floating type"); - case BuiltinType::Float16: return Float16Rank; - case BuiltinType::Half: return HalfRank; - case BuiltinType::Float: return FloatRank; - case BuiltinType::Double: return DoubleRank; - case BuiltinType::LongDouble: return LongDoubleRank; - case BuiltinType::Float128: return Float128Rank; - case BuiltinType::BFloat16: return BFloat16Rank; - case BuiltinType::Ibm128: return Ibm128Rank; + default: + llvm_unreachable("getFloatingRank(): not a floating type"); + case BuiltinType::Float16: + return Float16Rank; + case BuiltinType::Half: + return HalfRank; + case BuiltinType::Float: + return FloatRank; + case BuiltinType::Double: + return DoubleRank; + case BuiltinType::LongDouble: + return LongDoubleRank; + case BuiltinType::Float128: + return Float128Rank; + case BuiltinType::BFloat16: + return BFloat16Rank; + case BuiltinType::Ibm128: + return Ibm128Rank; } } @@ -6340,26 +6279,40 @@ FloatingRank EltRank = getFloatingRank(Size); if (Domain->isComplexType()) { switch (EltRank) { - case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported"); + case BFloat16Rank: + llvm_unreachable("Complex bfloat16 is not supported"); case Float16Rank: - case HalfRank: llvm_unreachable("Complex half is not supported"); - case Ibm128Rank: llvm_unreachable("Complex __ibm128 is not supported"); - case FloatRank: return FloatComplexTy; - case DoubleRank: return DoubleComplexTy; - case LongDoubleRank: return LongDoubleComplexTy; - case Float128Rank: return Float128ComplexTy; + case HalfRank: + llvm_unreachable("Complex half is not supported"); + case Ibm128Rank: + llvm_unreachable("Complex __ibm128 is not supported"); + case FloatRank: + return FloatComplexTy; + case DoubleRank: + return DoubleComplexTy; + case LongDoubleRank: + return LongDoubleComplexTy; + case Float128Rank: + return Float128ComplexTy; } } assert(Domain->isRealFloatingType() && "Unknown domain!"); switch (EltRank) { - case Float16Rank: return HalfTy; - case BFloat16Rank: return BFloat16Ty; - case HalfRank: return HalfTy; - case FloatRank: return FloatTy; - case DoubleRank: return DoubleTy; - case LongDoubleRank: return LongDoubleTy; - case Float128Rank: return Float128Ty; + case Float16Rank: + return HalfTy; + case BFloat16Rank: + return BFloat16Ty; + case HalfRank: + return HalfTy; + case FloatRank: + return FloatTy; + case DoubleRank: + return DoubleTy; + case LongDoubleRank: + return LongDoubleTy; + case Float128Rank: + return Float128Ty; case Ibm128Rank: return Ibm128Ty; } @@ -6390,16 +6343,17 @@ /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This /// routine will assert if passed a built-in type that isn't an integer or enum, /// or if it is not canonicalized. -unsigned ASTContext::getIntegerRank(const Type *T) const { +unsigned ASTContext::getIntegerRank(Type const *T) const { assert(T->isCanonicalUnqualified() && "T should be canonicalized"); // Results in this 'losing' to any type of the same size, but winning if // larger. - if (const auto *EIT = dyn_cast(T)) + if (auto const *EIT = dyn_cast(T)) return 0 + (EIT->getNumBits() << 3); switch (cast(T)->getKind()) { - default: llvm_unreachable("getIntegerRank(): not a built-in integer"); + default: + llvm_unreachable("getIntegerRank(): not a built-in integer"); case BuiltinType::Bool: return 1 + (getIntWidth(BoolTy) << 3); case BuiltinType::Char_S: @@ -6488,10 +6442,10 @@ QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { assert(!Promotable.isNull()); assert(Promotable->isPromotableIntegerType()); - if (const auto *ET = Promotable->getAs()) + if (auto const *ET = Promotable->getAs()) return ET->getDecl()->getPromotionType(); - if (const auto *BT = Promotable->getAs()) { + if (auto const *BT = Promotable->getAs()) { // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t // (3.9.1) can be converted to a prvalue of the first of the following // types that can represent all the values of its underlying type: @@ -6505,8 +6459,9 @@ BT->getKind() == BuiltinType::Char32) { bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; uint64_t FromSize = getTypeSize(BT); - QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, - LongLongTy, UnsignedLongLongTy }; + QualType PromoteTypes[] = {IntTy, UnsignedIntTy, + LongTy, UnsignedLongTy, + LongLongTy, UnsignedLongLongTy}; for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); if (FromSize < ToSize || @@ -6535,9 +6490,9 @@ return T.getObjCLifetime(); if (T->isArrayType()) T = getBaseElementType(T); - else if (const auto *PT = T->getAs()) + else if (auto const *PT = T->getAs()) T = PT->getPointeeType(); - else if (const auto *RT = T->getAs()) + else if (auto const *RT = T->getAs()) T = RT->getPointeeType(); else break; @@ -6546,7 +6501,7 @@ return Qualifiers::OCL_None; } -static const Type *getIntegerTypeForEnum(const EnumType *ET) { +static Type const *getIntegerTypeForEnum(EnumType const *ET) { // Incomplete enum types are not treated as integer types. // FIXME: In C++, enum types are never integer types. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) @@ -6558,16 +6513,17 @@ /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If /// LHS < RHS, return -1. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { - const Type *LHSC = getCanonicalType(LHS).getTypePtr(); - const Type *RHSC = getCanonicalType(RHS).getTypePtr(); + Type const *LHSC = getCanonicalType(LHS).getTypePtr(); + Type const *RHSC = getCanonicalType(RHS).getTypePtr(); // Unwrap enums to their underlying type. - if (const auto *ET = dyn_cast(LHSC)) + if (auto const *ET = dyn_cast(LHSC)) LHSC = getIntegerTypeForEnum(ET); - if (const auto *ET = dyn_cast(RHSC)) + if (auto const *ET = dyn_cast(RHSC)) RHSC = getIntegerTypeForEnum(ET); - if (LHSC == RHSC) return 0; + if (LHSC == RHSC) + return 0; bool LHSUnsigned = LHSC->isUnsignedIntegerType(); bool RHSUnsigned = RHSC->isUnsignedIntegerType(); @@ -6575,8 +6531,9 @@ unsigned LHSRank = getIntegerRank(LHSC); unsigned RHSRank = getIntegerRank(RHSC); - if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. - if (LHSRank == RHSRank) return 0; + if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. + if (LHSRank == RHSRank) + return 0; return LHSRank > RHSRank ? 1 : -1; } @@ -6613,7 +6570,7 @@ struct { QualType Type; - const char *Name; + char const *Name; } Fields[5]; unsigned Count = 0; @@ -6646,32 +6603,31 @@ /// uintptr_t _length; /// } __NSConstantString; - const auto CFRuntime = getLangOpts().CFRuntime; + auto const CFRuntime = getLangOpts().CFRuntime; if (static_cast(CFRuntime) < static_cast(LangOptions::CoreFoundationABI::Swift)) { - Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" }; - Fields[Count++] = { IntTy, "flags" }; - Fields[Count++] = { getPointerType(CharTy.withConst()), "str" }; - Fields[Count++] = { LongTy, "length" }; + Fields[Count++] = {getPointerType(IntTy.withConst()), "isa"}; + Fields[Count++] = {IntTy, "flags"}; + Fields[Count++] = {getPointerType(CharTy.withConst()), "str"}; + Fields[Count++] = {LongTy, "length"}; } else { - Fields[Count++] = { getUIntPtrType(), "_cfisa" }; - Fields[Count++] = { getUIntPtrType(), "_swift_rc" }; - Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" }; - Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" }; + Fields[Count++] = {getUIntPtrType(), "_cfisa"}; + Fields[Count++] = {getUIntPtrType(), "_swift_rc"}; + Fields[Count++] = {getFromTargetType(Target->getUInt64Type()), "_swift_rc"}; + Fields[Count++] = {getPointerType(CharTy.withConst()), "_ptr"}; if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) - Fields[Count++] = { IntTy, "_ptr" }; + Fields[Count++] = {IntTy, "_ptr"}; else - Fields[Count++] = { getUIntPtrType(), "_ptr" }; + Fields[Count++] = {getUIntPtrType(), "_ptr"}; } // Create fields for (unsigned i = 0; i < Count; ++i) { - FieldDecl *Field = - FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(), - SourceLocation(), &Idents.get(Fields[i].Name), - Fields[i].Type, /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + *this, CFConstantStringTagDecl, SourceLocation(), SourceLocation(), + &Idents.get(Fields[i].Name), Fields[i].Type, /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); CFConstantStringTagDecl->addDecl(Field); } @@ -6707,9 +6663,9 @@ } void ASTContext::setCFConstantStringType(QualType T) { - const auto *TD = T->castAs(); + auto const *TD = T->castAs(); CFConstantStringTypeDecl = cast(TD->getDecl()); - const auto *TagType = + auto const *TagType = CFConstantStringTypeDecl->getUnderlyingType()->castAs(); CFConstantStringTagDecl = TagType->getDecl(); } @@ -6724,14 +6680,11 @@ RD->startDefinition(); QualType FieldTypes[] = { - UnsignedLongTy, - UnsignedLongTy, + UnsignedLongTy, + UnsignedLongTy, }; - static const char *const FieldNames[] = { - "reserved", - "Size" - }; + static char const *const FieldNames[] = {"reserved", "Size"}; for (size_t i = 0; i < 2; ++i) { FieldDecl *Field = FieldDecl::Create( @@ -6758,19 +6711,12 @@ RD = buildImplicitRecord("__block_descriptor_withcopydispose"); RD->startDefinition(); - QualType FieldTypes[] = { - UnsignedLongTy, - UnsignedLongTy, - getPointerType(VoidPtrTy), - getPointerType(VoidPtrTy) - }; + QualType FieldTypes[] = {UnsignedLongTy, UnsignedLongTy, + getPointerType(VoidPtrTy), + getPointerType(VoidPtrTy)}; - static const char *const FieldNames[] = { - "reserved", - "Size", - "CopyFuncPtr", - "DestroyFuncPtr" - }; + static char const *const FieldNames[] = {"reserved", "Size", "CopyFuncPtr", + "DestroyFuncPtr"}; for (size_t i = 0; i < 4; ++i) { FieldDecl *Field = FieldDecl::Create( @@ -6788,8 +6734,8 @@ return getTagDeclType(BlockDescriptorExtendedType); } -OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const { - const auto *BT = dyn_cast(T); +OpenCLTypeKind ASTContext::getOpenCLTypeKind(Type const *T) const { + auto const *BT = dyn_cast(T); if (!BT) { if (isa(T)) @@ -6824,18 +6770,18 @@ } } -LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const { +LangAS ASTContext::getOpenCLTypeAddrSpace(Type const *T) const { return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)); } /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" /// requires copy/dispose. Note that this must match the logic /// in buildByrefHelpers. -bool ASTContext::BlockRequiresCopying(QualType Ty, - const VarDecl *D) { - if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { - const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); - if (!copyExpr && record->hasTrivialDestructor()) return false; +bool ASTContext::BlockRequiresCopying(QualType Ty, VarDecl const *D) { + if (CXXRecordDecl const *record = Ty->getAsCXXRecordDecl()) { + Expr const *copyExpr = getBlockVarCopyInit(D).getCopyExpr(); + if (!copyExpr && record->hasTrivialDestructor()) + return false; return true; } @@ -6845,25 +6791,27 @@ if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType()) return true; - if (!Ty->isObjCRetainableType()) return false; + if (!Ty->isObjCRetainableType()) + return false; Qualifiers qs = Ty.getQualifiers(); // If we have lifetime, that dominates. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { switch (lifetime) { - case Qualifiers::OCL_None: llvm_unreachable("impossible"); + case Qualifiers::OCL_None: + llvm_unreachable("impossible"); - // These are just bits as far as the runtime is concerned. - case Qualifiers::OCL_ExplicitNone: - case Qualifiers::OCL_Autoreleasing: - return false; + // These are just bits as far as the runtime is concerned. + case Qualifiers::OCL_ExplicitNone: + case Qualifiers::OCL_Autoreleasing: + return false; - // These cases should have been taken care of when checking the type's - // non-triviality. - case Qualifiers::OCL_Weak: - case Qualifiers::OCL_Strong: - llvm_unreachable("impossible"); + // These cases should have been taken care of when checking the type's + // non-triviality. + case Qualifiers::OCL_Weak: + case Qualifiers::OCL_Strong: + llvm_unreachable("impossible"); } llvm_unreachable("fell out of lifetime switch!"); } @@ -6872,10 +6820,9 @@ } bool ASTContext::getByrefLifetime(QualType Ty, - Qualifiers::ObjCLifetime &LifeTime, - bool &HasByrefExtendedLayout) const { - if (!getLangOpts().ObjC || - getLangOpts().getGC() != LangOptions::NonGC) + Qualifiers::ObjCLifetime &LifeTime, + bool &HasByrefExtendedLayout) const { + if (!getLangOpts().ObjC || getLangOpts().getGC() != LangOptions::NonGC) return false; HasByrefExtendedLayout = false; @@ -6895,7 +6842,7 @@ CanQualType ASTContext::getNSUIntegerType() const { assert(Target && "Expected target to be initialized"); - const llvm::Triple &T = Target->getTriple(); + llvm::Triple const &T = Target->getTriple(); // Windows is LLP64 rather than LP64 if (T.isOSWindows() && T.isArch64Bit()) return UnsignedLongLongTy; @@ -6904,7 +6851,7 @@ CanQualType ASTContext::getNSIntegerType() const { assert(Target && "Expected target to be initialized"); - const llvm::Triple &T = Target->getTriple(); + llvm::Triple const &T = Target->getTriple(); // Windows is LLP64 rather than LP64 if (T.isOSWindows() && T.isArch64Bit()) return LongLongTy; @@ -6921,7 +6868,7 @@ // This returns true if a type has been typedefed to BOOL: // typedef BOOL; static bool isTypeTypedefedAsBOOL(QualType T) { - if (const auto *TT = dyn_cast(T)) + if (auto const *TT = dyn_cast(T)) if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) return II->isStr("BOOL"); @@ -6945,7 +6892,7 @@ return sz; } -bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { +bool ASTContext::isMSStaticDataMemberInlineDefinition(VarDecl const *VD) const { return getTargetInfo().getCXXABI().isMicrosoft() && VD->isStaticDataMember() && VD->getType()->isIntegralOrEnumerationType() && @@ -6953,7 +6900,7 @@ } ASTContext::InlineVariableDefinitionKind -ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const { +ASTContext::getInlineVariableDefinitionKind(VarDecl const *VD) const { if (!VD->isInline()) return InlineVariableDefinitionKind::None; @@ -6973,16 +6920,16 @@ return InlineVariableDefinitionKind::WeakUnknown; } -static std::string charUnitsToString(const CharUnits &CU) { +static std::string charUnitsToString(CharUnits const &CU) { return llvm::itostr(CU.getQuantity()); } /// getObjCEncodingForBlock - Return the encoded type for this block /// declaration. -std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { +std::string ASTContext::getObjCEncodingForBlock(BlockExpr const *Expr) const { std::string S; - const BlockDecl *Decl = Expr->getBlockDecl(); + BlockDecl const *Decl = Expr->getBlockDecl(); QualType BlockTy = Expr->getType()->castAs()->getPointeeType(); QualType BlockReturnTy = BlockTy->castAs()->getReturnType(); @@ -7014,7 +6961,7 @@ ParmOffset = PtrSize; for (auto PVDecl : Decl->parameters()) { QualType PType = PVDecl->getOriginalType(); - if (const auto *AT = + if (auto const *AT = dyn_cast(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of // elements. @@ -7023,8 +6970,8 @@ } else if (PType->isFunctionType()) PType = PVDecl->getType(); if (getLangOpts().EncodeExtendedBlockSig) - getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, - S, true /*Extended*/); + getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, S, + true /*Extended*/); else getObjCEncodingForType(PType, S); S += charUnitsToString(ParmOffset); @@ -7035,7 +6982,7 @@ } std::string -ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const { +ASTContext::getObjCEncodingForFunctionDecl(FunctionDecl const *Decl) const { std::string S; // Encode result type. getObjCEncodingForType(Decl->getReturnType(), S); @@ -7057,7 +7004,7 @@ // Argument types. for (auto PVDecl : Decl->parameters()) { QualType PType = PVDecl->getOriginalType(); - if (const auto *AT = + if (auto const *AT = dyn_cast(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of // elements. @@ -7077,7 +7024,7 @@ /// method parameter or return type. If Extended, include class names and /// block object types. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, - QualType T, std::string& S, + QualType T, std::string &S, bool Extended) const { // Encode type qualifer, 'in', 'inout', etc. for the parameter. getObjCEncodingForTypeQualifier(QT, S); @@ -7093,7 +7040,7 @@ /// getObjCEncodingForMethodDecl - Return the encoded type for this method /// declaration. -std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, +std::string ASTContext::getObjCEncodingForMethodDecl(ObjCMethodDecl const *Decl, bool Extended) const { // FIXME: This is not very efficient. // Encode return type. @@ -7108,7 +7055,8 @@ // their size. CharUnits ParmOffset = 2 * PtrSize; for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), - E = Decl->sel_param_end(); PI != E; ++PI) { + E = Decl->sel_param_end(); + PI != E; ++PI) { QualType PType = (*PI)->getType(); CharUnits sz = getObjCEncodingTypeSize(PType); if (sz.isZero()) @@ -7125,10 +7073,11 @@ // Argument types. ParmOffset = 2 * PtrSize; for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), - E = Decl->sel_param_end(); PI != E; ++PI) { - const ParmVarDecl *PVDecl = *PI; + E = Decl->sel_param_end(); + PI != E; ++PI) { + ParmVarDecl const *PVDecl = *PI; QualType PType = PVDecl->getOriginalType(); - if (const auto *AT = + if (auto const *AT = dyn_cast(PType->getCanonicalTypeInternal())) { // Use array's original type only if it has known number of // elements. @@ -7136,8 +7085,8 @@ PType = PVDecl->getType(); } else if (PType->isFunctionType()) PType = PVDecl->getType(); - getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), - PType, S, Extended); + getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), PType, S, + Extended); S += charUnitsToString(ParmOffset); ParmOffset += getObjCEncodingTypeSize(PType); } @@ -7145,18 +7094,16 @@ return S; } -ObjCPropertyImplDecl * -ASTContext::getObjCPropertyImplDeclForPropertyDecl( - const ObjCPropertyDecl *PD, - const Decl *Container) const { +ObjCPropertyImplDecl *ASTContext::getObjCPropertyImplDeclForPropertyDecl( + ObjCPropertyDecl const *PD, Decl const *Container) const { if (!Container) return nullptr; - if (const auto *CID = dyn_cast(Container)) { + if (auto const *CID = dyn_cast(Container)) { for (auto *PID : CID->property_impls()) if (PID->getPropertyDecl() == PD) return PID; } else { - const auto *OID = cast(Container); + auto const *OID = cast(Container); for (auto *PID : OID->property_impls()) if (PID->getPropertyDecl() == PD) return PID; @@ -7190,15 +7137,16 @@ /// }; /// @endcode std::string -ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, - const Decl *Container) const { +ASTContext::getObjCEncodingForPropertyDecl(ObjCPropertyDecl const *PD, + Decl const *Container) const { // Collect information from the property implementation decl(s). bool Dynamic = false; ObjCPropertyImplDecl *SynthesizePID = nullptr; if (ObjCPropertyImplDecl *PropertyImpDecl = - getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { - if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) + getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { + if (PropertyImpDecl->getPropertyImplementation() == + ObjCPropertyImplDecl::Dynamic) Dynamic = true; else SynthesizePID = PropertyImpDecl; @@ -7222,10 +7170,17 @@ S += ",W"; } else { switch (PD->getSetterKind()) { - case ObjCPropertyDecl::Assign: break; - case ObjCPropertyDecl::Copy: S += ",C"; break; - case ObjCPropertyDecl::Retain: S += ",&"; break; - case ObjCPropertyDecl::Weak: S += ",W"; break; + case ObjCPropertyDecl::Assign: + break; + case ObjCPropertyDecl::Copy: + S += ",C"; + break; + case ObjCPropertyDecl::Retain: + S += ",&"; + break; + case ObjCPropertyDecl::Weak: + S += ",W"; + break; } } @@ -7248,7 +7203,7 @@ } if (SynthesizePID) { - const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); + ObjCIvarDecl const *OID = SynthesizePID->getPropertyIvarDecl(); S += ",V"; S += OID->getNameAsString(); } @@ -7261,20 +7216,20 @@ /// Another legacy compatibility encoding: 32-bit longs are encoded as /// 'l' or 'L' , but not always. For typedefs, we need to use /// 'i' or 'I' instead if encoding a struct field, or a pointer! -void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { +void ASTContext::getLegacyIntegralTypeEncoding(QualType &PointeeTy) const { if (isa(PointeeTy.getTypePtr())) { - if (const auto *BT = PointeeTy->getAs()) { + if (auto const *BT = PointeeTy->getAs()) { if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) PointeeTy = UnsignedIntTy; - else - if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) - PointeeTy = IntTy; + else if (BT->getKind() == BuiltinType::Long && + getIntWidth(PointeeTy) == 32) + PointeeTy = IntTy; } } } -void ASTContext::getObjCEncodingForType(QualType T, std::string& S, - const FieldDecl *Field, +void ASTContext::getObjCEncodingForType(QualType T, std::string &S, + FieldDecl const *Field, QualType *NotEncodedT) const { // We follow the behavior of gcc, expanding structures which are // directly pointed to, and expanding embedded structures. Note that @@ -7289,7 +7244,7 @@ } void ASTContext::getObjCEncodingForPropertyType(QualType T, - std::string& S) const { + std::string &S) const { // Encode result type. // GCC has some special rules regarding encoding of properties which // closely resembles encoding of ivars. @@ -7302,114 +7257,126 @@ /*Field=*/nullptr); } -static char getObjCEncodingForPrimitiveType(const ASTContext *C, - const BuiltinType *BT) { - BuiltinType::Kind kind = BT->getKind(); - switch (kind) { - case BuiltinType::Void: return 'v'; - case BuiltinType::Bool: return 'B'; - case BuiltinType::Char8: - case BuiltinType::Char_U: - case BuiltinType::UChar: return 'C'; - case BuiltinType::Char16: - case BuiltinType::UShort: return 'S'; - case BuiltinType::Char32: - case BuiltinType::UInt: return 'I'; - case BuiltinType::ULong: - return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; - case BuiltinType::UInt128: return 'T'; - case BuiltinType::ULongLong: return 'Q'; - case BuiltinType::Char_S: - case BuiltinType::SChar: return 'c'; - case BuiltinType::Short: return 's'; - case BuiltinType::WChar_S: - case BuiltinType::WChar_U: - case BuiltinType::Int: return 'i'; - case BuiltinType::Long: - return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; - case BuiltinType::LongLong: return 'q'; - case BuiltinType::Int128: return 't'; - case BuiltinType::Float: return 'f'; - case BuiltinType::Double: return 'd'; - case BuiltinType::LongDouble: return 'D'; - case BuiltinType::NullPtr: return '*'; // like char* +static char getObjCEncodingForPrimitiveType(ASTContext const *C, + BuiltinType const *BT) { + BuiltinType::Kind kind = BT->getKind(); + switch (kind) { + case BuiltinType::Void: + return 'v'; + case BuiltinType::Bool: + return 'B'; + case BuiltinType::Char8: + case BuiltinType::Char_U: + case BuiltinType::UChar: + return 'C'; + case BuiltinType::Char16: + case BuiltinType::UShort: + return 'S'; + case BuiltinType::Char32: + case BuiltinType::UInt: + return 'I'; + case BuiltinType::ULong: + return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; + case BuiltinType::UInt128: + return 'T'; + case BuiltinType::ULongLong: + return 'Q'; + case BuiltinType::Char_S: + case BuiltinType::SChar: + return 'c'; + case BuiltinType::Short: + return 's'; + case BuiltinType::WChar_S: + case BuiltinType::WChar_U: + case BuiltinType::Int: + return 'i'; + case BuiltinType::Long: + return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; + case BuiltinType::LongLong: + return 'q'; + case BuiltinType::Int128: + return 't'; + case BuiltinType::Float: + return 'f'; + case BuiltinType::Double: + return 'd'; + case BuiltinType::LongDouble: + return 'D'; + case BuiltinType::NullPtr: + return '*'; // like char* - case BuiltinType::BFloat16: - case BuiltinType::Float16: - case BuiltinType::Float128: - case BuiltinType::Ibm128: - case BuiltinType::Half: - case BuiltinType::ShortAccum: - case BuiltinType::Accum: - case BuiltinType::LongAccum: - case BuiltinType::UShortAccum: - case BuiltinType::UAccum: - case BuiltinType::ULongAccum: - case BuiltinType::ShortFract: - case BuiltinType::Fract: - case BuiltinType::LongFract: - case BuiltinType::UShortFract: - case BuiltinType::UFract: - case BuiltinType::ULongFract: - case BuiltinType::SatShortAccum: - case BuiltinType::SatAccum: - case BuiltinType::SatLongAccum: - case BuiltinType::SatUShortAccum: - case BuiltinType::SatUAccum: - case BuiltinType::SatULongAccum: - case BuiltinType::SatShortFract: - case BuiltinType::SatFract: - case BuiltinType::SatLongFract: - case BuiltinType::SatUShortFract: - case BuiltinType::SatUFract: - case BuiltinType::SatULongFract: - // FIXME: potentially need @encodes for these! - return ' '; + case BuiltinType::BFloat16: + case BuiltinType::Float16: + case BuiltinType::Float128: + case BuiltinType::Ibm128: + case BuiltinType::Half: + case BuiltinType::ShortAccum: + case BuiltinType::Accum: + case BuiltinType::LongAccum: + case BuiltinType::UShortAccum: + case BuiltinType::UAccum: + case BuiltinType::ULongAccum: + case BuiltinType::ShortFract: + case BuiltinType::Fract: + case BuiltinType::LongFract: + case BuiltinType::UShortFract: + case BuiltinType::UFract: + case BuiltinType::ULongFract: + case BuiltinType::SatShortAccum: + case BuiltinType::SatAccum: + case BuiltinType::SatLongAccum: + case BuiltinType::SatUShortAccum: + case BuiltinType::SatUAccum: + case BuiltinType::SatULongAccum: + case BuiltinType::SatShortFract: + case BuiltinType::SatFract: + case BuiltinType::SatLongFract: + case BuiltinType::SatUShortFract: + case BuiltinType::SatUFract: + case BuiltinType::SatULongFract: + // FIXME: potentially need @encodes for these! + return ' '; -#define SVE_TYPE(Name, Id, SingletonId) \ - case BuiltinType::Id: +#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: #include "clang/Basic/AArch64SVEACLETypes.def" #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: #include "clang/Basic/RISCVVTypes.def" - { - DiagnosticsEngine &Diags = C->getDiagnostics(); - unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, - "cannot yet @encode type %0"); - Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); - return ' '; - } + { + DiagnosticsEngine &Diags = C->getDiagnostics(); + unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, + "cannot yet @encode type %0"); + Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy()); + return ' '; + } - case BuiltinType::ObjCId: - case BuiltinType::ObjCClass: - case BuiltinType::ObjCSel: - llvm_unreachable("@encoding ObjC primitive type"); + case BuiltinType::ObjCId: + case BuiltinType::ObjCClass: + case BuiltinType::ObjCSel: + llvm_unreachable("@encoding ObjC primitive type"); // OpenCL and placeholder types don't need @encodings. -#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ - case BuiltinType::Id: +#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ + case BuiltinType::Id: #include "clang/Basic/OpenCLImageTypes.def" -#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ - case BuiltinType::Id: +#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id: #include "clang/Basic/OpenCLExtensionTypes.def" - case BuiltinType::OCLEvent: - case BuiltinType::OCLClkEvent: - case BuiltinType::OCLQueue: - case BuiltinType::OCLReserveID: - case BuiltinType::OCLSampler: - case BuiltinType::Dependent: -#define PPC_VECTOR_TYPE(Name, Id, Size) \ - case BuiltinType::Id: + case BuiltinType::OCLEvent: + case BuiltinType::OCLClkEvent: + case BuiltinType::OCLQueue: + case BuiltinType::OCLReserveID: + case BuiltinType::OCLSampler: + case BuiltinType::Dependent: +#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id: #include "clang/Basic/PPCTypes.def" #define BUILTIN_TYPE(KIND, ID) -#define PLACEHOLDER_TYPE(KIND, ID) \ - case BuiltinType::KIND: +#define PLACEHOLDER_TYPE(KIND, ID) case BuiltinType::KIND: #include "clang/AST/BuiltinTypes.def" - llvm_unreachable("invalid builtin type for @encode"); - } - llvm_unreachable("invalid BuiltinType::Kind value"); + llvm_unreachable("invalid builtin type for @encode"); + } + llvm_unreachable("invalid BuiltinType::Kind value"); } -static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { +static char ObjCEncodingForEnumType(ASTContext const *C, EnumType const *ET) { EnumDecl *Enum = ET->getDecl(); // The encoding of an non-fixed enum type is always 'i', regardless of size. @@ -7417,12 +7384,12 @@ return 'i'; // The encoding of a fixed enum type matches its fixed underlying type. - const auto *BT = Enum->getIntegerType()->castAs(); + auto const *BT = Enum->getIntegerType()->castAs(); return getObjCEncodingForPrimitiveType(C, BT); } -static void EncodeBitField(const ASTContext *Ctx, std::string& S, - QualType T, const FieldDecl *FD) { +static void EncodeBitField(ASTContext const *Ctx, std::string &S, QualType T, + FieldDecl const *FD) { assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); S += 'b'; // The NeXT runtime encodes bit fields as b followed by the number of bits. @@ -7443,21 +7410,21 @@ if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { uint64_t Offset; - if (const auto *IVD = dyn_cast(FD)) { + if (auto const *IVD = dyn_cast(FD)) { Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr, IVD); } else { - const RecordDecl *RD = FD->getParent(); - const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); + RecordDecl const *RD = FD->getParent(); + ASTRecordLayout const &RL = Ctx->getASTRecordLayout(RD); Offset = RL.getFieldOffset(FD->getFieldIndex()); } S += llvm::utostr(Offset); - if (const auto *ET = T->getAs()) + if (auto const *ET = T->getAs()) S += ObjCEncodingForEnumType(Ctx, ET); else { - const auto *BT = T->castAs(); + auto const *BT = T->castAs(); S += getObjCEncodingForPrimitiveType(Ctx, BT); } } @@ -7466,7 +7433,7 @@ // Helper function for determining whether the encoded type string would include // a template specialization type. -static bool hasTemplateSpecializationInEncodedString(const Type *T, +static bool hasTemplateSpecializationInEncodedString(Type const *T, bool VisitBasesAndFields) { T = T->getBaseElementTypeUnsafe(); @@ -7501,7 +7468,7 @@ // FIXME: Use SmallString for accumulating string. void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S, const ObjCEncOptions Options, - const FieldDecl *FD, + FieldDecl const *FD, QualType *NotEncodedT) const { CanQualType CT = getCanonicalType(T); switch (CT->getTypeClass()) { @@ -7509,7 +7476,7 @@ case Type::Enum: if (FD && FD->isBitField()) return EncodeBitField(this, S, T, FD); - if (const auto *BT = dyn_cast(CT)) + if (auto const *BT = dyn_cast(CT)) S += getObjCEncodingForPrimitiveType(this, BT); else S += ObjCEncodingForEnumType(this, cast(CT)); @@ -7535,7 +7502,7 @@ case Type::RValueReference: { QualType PointeeTy; if (isa(CT)) { - const auto *PT = T->castAs(); + auto const *PT = T->castAs(); if (PT->isObjCSelType()) { S += ':'; return; @@ -7569,7 +7536,7 @@ // combinations need to be rearranged. // Rewrite "in const" from "nr" to "rn" if (StringRef(S).endswith("nr")) - S.replace(S.end()-2, S.end(), "rn"); + S.replace(S.end() - 2, S.end(), "rn"); } if (PointeeTy->isCharType()) { @@ -7579,7 +7546,7 @@ S += '*'; return; } - } else if (const auto *RTy = PointeeTy->getAs()) { + } else if (auto const *RTy = PointeeTy->getAs()) { // GCC binary compat: Need to convert "struct objc_class *" to "#". if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { S += '#'; @@ -7615,7 +7582,7 @@ case Type::ConstantArray: case Type::IncompleteArray: case Type::VariableArray: { - const auto *AT = cast(CT); + auto const *AT = cast(CT); if (isa(AT) && !Options.IsStructField()) { // Incomplete arrays are encoded as a pointer to the array element. @@ -7627,10 +7594,11 @@ } else { S += '['; - if (const auto *CAT = dyn_cast(AT)) + if (auto const *CAT = dyn_cast(AT)) S += llvm::utostr(CAT->getSize().getZExtValue()); else { - //Variable length arrays are encoded as a regular array with 0 elements. + // Variable length arrays are encoded as a regular array with 0 + // elements. assert((isa(AT) || isa(AT)) && "Unknown array type!"); S += '0'; @@ -7654,10 +7622,10 @@ RecordDecl *RDecl = cast(CT)->getDecl(); S += RDecl->isUnion() ? '(' : '{'; // Anonymous structures print as '?' - if (const IdentifierInfo *II = RDecl->getIdentifier()) { + if (IdentifierInfo const *II = RDecl->getIdentifier()) { S += II->getName(); - if (const auto *Spec = dyn_cast(RDecl)) { - const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); + if (auto const *Spec = dyn_cast(RDecl)) { + TemplateArgumentList const &TemplateArgs = Spec->getTemplateArgs(); llvm::raw_string_ostream OS(S); printTemplateArgumentList(OS, TemplateArgs.asArray(), getPrintingPolicy()); @@ -7670,7 +7638,7 @@ if (!RDecl->isUnion()) { getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); } else { - for (const auto *Field : RDecl->fields()) { + for (auto const *Field : RDecl->fields()) { if (FD) { S += '"'; S += Field->getNameAsString(); @@ -7698,10 +7666,10 @@ } case Type::BlockPointer: { - const auto *BT = T->castAs(); + auto const *BT = T->castAs(); S += "@?"; // Unlike a pointer-to-function, which is "^?". if (Options.EncodeBlockParameters()) { - const auto *FT = BT->getPointeeType()->castAs(); + auto const *FT = BT->getPointeeType()->castAs(); S += '<'; // Block return type @@ -7710,8 +7678,8 @@ // Block self S += "@?"; // Block parameters - if (const auto *FPT = dyn_cast(FT)) { - for (const auto &I : FPT->param_types()) + if (auto const *FPT = dyn_cast(FT)) { + for (auto const &I : FPT->param_types()) getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD, NotEncodedT); } @@ -7726,8 +7694,7 @@ if (Ty->isObjCIdType()) { S += "{objc_object=}"; return; - } - else if (Ty->isObjCClassType()) { + } else if (Ty->isObjCClassType()) { S += "{objc_class=}"; return; } @@ -7743,10 +7710,10 @@ S += OI->getObjCRuntimeNameAsString(); if (Options.ExpandStructures()) { S += '='; - SmallVector Ivars; + SmallVector Ivars; DeepCollectObjCIvars(OI, true, Ivars); for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { - const FieldDecl *Field = Ivars[i]; + FieldDecl const *Field = Ivars[i]; if (Field->isBitField()) getObjCEncodingForTypeImpl(Field->getType(), S, ObjCEncOptions().setExpandStructures(), @@ -7762,7 +7729,7 @@ } case Type::ObjCObjectPointer: { - const auto *OPT = T->castAs(); + auto const *OPT = T->castAs(); if (OPT->isObjCIdType()) { S += '@'; return; @@ -7787,7 +7754,7 @@ // Note that we do extended encoding of protocol qualifer list // Only when doing ivar or property encoding. S += '"'; - for (const auto *I : OPT->quals()) { + for (auto const *I : OPT->quals()) { S += '<'; S += I->getObjCRuntimeNameAsString(); S += '>'; @@ -7802,7 +7769,7 @@ (FD || Options.EncodingProperty() || Options.EncodeClassNames())) { S += '"'; S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString(); - for (const auto *I : OPT->quals()) { + for (auto const *I : OPT->quals()) { S += '<'; S += I->getObjCRuntimeNameAsString(); S += '>'; @@ -7816,10 +7783,10 @@ // FIXME: we should do better than that. 'M' is available. case Type::MemberPointer: // This matches gcc's encoding, even though technically it is insufficient. - //FIXME. We should do a better job than gcc. + // FIXME. We should do a better job than gcc. case Type::Vector: case Type::ExtVector: - // Until we have a coherent encoding of these three types, issue warning. + // Until we have a coherent encoding of these three types, issue warning. if (NotEncodedT) *NotEncodedT = T; return; @@ -7839,12 +7806,9 @@ case Type::ExtInt: #define ABSTRACT_TYPE(KIND, BASE) #define TYPE(KIND, BASE) -#define DEPENDENT_TYPE(KIND, BASE) \ - case Type::KIND: -#define NON_CANONICAL_TYPE(KIND, BASE) \ - case Type::KIND: -#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ - case Type::KIND: +#define DEPENDENT_TYPE(KIND, BASE) case Type::KIND: +#define NON_CANONICAL_TYPE(KIND, BASE) case Type::KIND: +#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) case Type::KIND: #include "clang/AST/TypeNodes.inc" llvm_unreachable("@encode for dependent type!"); } @@ -7853,7 +7817,7 @@ void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, std::string &S, - const FieldDecl *FD, + FieldDecl const *FD, bool includeVBases, QualType *NotEncodedT) const { assert(RDecl && "Expected non-null RecordDecl"); @@ -7861,12 +7825,12 @@ if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl()) return; - const auto *CXXRec = dyn_cast(RDecl); + auto const *CXXRec = dyn_cast(RDecl); std::multimap FieldOrBaseOffsets; - const ASTRecordLayout &layout = getASTRecordLayout(RDecl); + ASTRecordLayout const &layout = getASTRecordLayout(RDecl); if (CXXRec) { - for (const auto &BI : CXXRec->bases()) { + for (auto const &BI : CXXRec->bases()) { if (!BI.isVirtual()) { CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); if (base->isEmpty()) @@ -7889,7 +7853,7 @@ } if (CXXRec && includeVBases) { - for (const auto &BI : CXXRec->vbases()) { + for (auto const &BI : CXXRec->vbases()) { CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); if (base->isEmpty()) continue; @@ -7911,15 +7875,16 @@ #ifndef NDEBUG uint64_t CurOffs = 0; #endif - std::multimap::iterator - CurLayObj = FieldOrBaseOffsets.begin(); + std::multimap::iterator CurLayObj = + FieldOrBaseOffsets.begin(); if (CXXRec && CXXRec->isDynamicClass() && (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { if (FD) { S += "\"_vptr$"; std::string recname = CXXRec->getNameAsString(); - if (recname.empty()) recname = "?"; + if (recname.empty()) + recname = "?"; S += recname; S += '"'; } @@ -7961,14 +7926,14 @@ // in the initial structure. Note that this differs from gcc which // expands virtual bases each time one is encountered in the hierarchy, // making the encoding type bigger than it really is. - getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, + getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/ false, NotEncodedT); assert(!base->isEmpty()); #ifndef NDEBUG CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); #endif } else { - const auto *field = cast(dcl); + auto const *field = cast(dcl); if (FD) { S += '"'; S += field->getNameAsString(); @@ -7995,7 +7960,7 @@ } void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, - std::string& S) const { + std::string &S) const { if (QT & Decl::OBJC_TQ_In) S += 'n'; if (QT & Decl::OBJC_TQ_Inout) @@ -8038,13 +8003,11 @@ ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { if (!ObjCProtocolClassDecl) { - ObjCProtocolClassDecl - = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), - SourceLocation(), - &Idents.get("Protocol"), + ObjCProtocolClassDecl = + ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), + SourceLocation(), &Idents.get("Protocol"), /*typeParamList=*/nullptr, - /*PrevDecl=*/nullptr, - SourceLocation(), true); + /*PrevDecl=*/nullptr, SourceLocation(), true); } return ObjCProtocolClassDecl; @@ -8054,29 +8017,29 @@ // __builtin_va_list Construction Functions //===----------------------------------------------------------------------===// -static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context, +static TypedefDecl *CreateCharPtrNamedVaListDecl(ASTContext const *Context, StringRef Name) { // typedef char* __builtin[_ms]_va_list; QualType T = Context->getPointerType(Context->CharTy); return Context->buildImplicitTypedef(T, Name); } -static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) { +static TypedefDecl *CreateMSVaListDecl(ASTContext const *Context) { return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list"); } -static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { +static TypedefDecl *CreateCharPtrBuiltinVaListDecl(ASTContext const *Context) { return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list"); } -static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { +static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(ASTContext const *Context) { // typedef void* __builtin_va_list; QualType T = Context->getPointerType(Context->VoidTy); return Context->buildImplicitTypedef(T, "__builtin_va_list"); } static TypedefDecl * -CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { +CreateAArch64ABIBuiltinVaListDecl(ASTContext const *Context) { RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); // namespace std { struct __va_list { // Note that we create the namespace even in C. This is intentional so that @@ -8097,7 +8060,7 @@ const size_t NumFields = 5; QualType FieldTypes[NumFields]; - const char *FieldNames[NumFields]; + char const *FieldNames[NumFields]; // void *__stack; FieldTypes[0] = Context->getPointerType(Context->VoidTy); @@ -8121,15 +8084,12 @@ // Create fields for (unsigned i = 0; i < NumFields; ++i) { - FieldDecl *Field = FieldDecl::Create(const_cast(*Context), - VaListTagDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + const_cast(*Context), VaListTagDecl, SourceLocation(), + SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], + /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } @@ -8141,7 +8101,7 @@ return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); } -static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { +static TypedefDecl *CreatePowerABIBuiltinVaListDecl(ASTContext const *Context) { // typedef struct __va_list_tag { RecordDecl *VaListTagDecl; @@ -8150,7 +8110,7 @@ const size_t NumFields = 5; QualType FieldTypes[NumFields]; - const char *FieldNames[NumFields]; + char const *FieldNames[NumFields]; // unsigned char gpr; FieldTypes[0] = Context->UnsignedCharTy; @@ -8174,14 +8134,11 @@ // Create fields for (unsigned i = 0; i < NumFields; ++i) { - FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + *Context, VaListTagDecl, SourceLocation(), SourceLocation(), + &Context->Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } @@ -8193,19 +8150,17 @@ TypedefDecl *VaListTagTypedefDecl = Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); - QualType VaListTagTypedefType = - Context->getTypedefType(VaListTagTypedefDecl); + QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl); // typedef __va_list_tag __builtin_va_list[1]; llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); - QualType VaListTagArrayType - = Context->getConstantArrayType(VaListTagTypedefType, - Size, nullptr, ArrayType::Normal, 0); + QualType VaListTagArrayType = Context->getConstantArrayType( + VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0); return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); } static TypedefDecl * -CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { +CreateX86_64ABIBuiltinVaListDecl(ASTContext const *Context) { // struct __va_list_tag { RecordDecl *VaListTagDecl; VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); @@ -8213,7 +8168,7 @@ const size_t NumFields = 4; QualType FieldTypes[NumFields]; - const char *FieldNames[NumFields]; + char const *FieldNames[NumFields]; // unsigned gp_offset; FieldTypes[0] = Context->UnsignedIntTy; @@ -8233,15 +8188,12 @@ // Create fields for (unsigned i = 0; i < NumFields; ++i) { - FieldDecl *Field = FieldDecl::Create(const_cast(*Context), - VaListTagDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + const_cast(*Context), VaListTagDecl, SourceLocation(), + SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], + /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } @@ -8258,7 +8210,7 @@ return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); } -static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { +static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(ASTContext const *Context) { // typedef int __builtin_va_list[4]; llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); QualType IntArrayType = Context->getConstantArrayType( @@ -8266,8 +8218,7 @@ return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); } -static TypedefDecl * -CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { +static TypedefDecl *CreateAAPCSABIBuiltinVaListDecl(ASTContext const *Context) { // struct __va_list RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); if (Context->getLangOpts().CPlusPlus) { @@ -8275,7 +8226,7 @@ NamespaceDecl *NS; NS = NamespaceDecl::Create(const_cast(*Context), Context->getTranslationUnitDecl(), - /*Inline*/false, SourceLocation(), + /*Inline*/ false, SourceLocation(), SourceLocation(), &Context->Idents.get("std"), /*PrevDecl*/ nullptr); NS->setImplicit(); @@ -8285,16 +8236,13 @@ VaListDecl->startDefinition(); // void * __ap; - FieldDecl *Field = FieldDecl::Create(const_cast(*Context), - VaListDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get("__ap"), - Context->getPointerType(Context->VoidTy), - /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + const_cast(*Context), VaListDecl, SourceLocation(), + SourceLocation(), &Context->Idents.get("__ap"), + Context->getPointerType(Context->VoidTy), + /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListDecl->addDecl(Field); @@ -8307,8 +8255,7 @@ return Context->buildImplicitTypedef(T, "__builtin_va_list"); } -static TypedefDecl * -CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { +static TypedefDecl *CreateSystemZBuiltinVaListDecl(ASTContext const *Context) { // struct __va_list_tag { RecordDecl *VaListTagDecl; VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); @@ -8316,7 +8263,7 @@ const size_t NumFields = 4; QualType FieldTypes[NumFields]; - const char *FieldNames[NumFields]; + char const *FieldNames[NumFields]; // long __gpr; FieldTypes[0] = Context->LongTy; @@ -8336,15 +8283,12 @@ // Create fields for (unsigned i = 0; i < NumFields; ++i) { - FieldDecl *Field = FieldDecl::Create(const_cast(*Context), - VaListTagDecl, - SourceLocation(), - SourceLocation(), - &Context->Idents.get(FieldNames[i]), - FieldTypes[i], /*TInfo=*/nullptr, - /*BitWidth=*/nullptr, - /*Mutable=*/false, - ICIS_NoInit); + FieldDecl *Field = FieldDecl::Create( + const_cast(*Context), VaListTagDecl, SourceLocation(), + SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i], + /*TInfo=*/nullptr, + /*BitWidth=*/nullptr, + /*Mutable=*/false, ICIS_NoInit); Field->setAccess(AS_public); VaListTagDecl->addDecl(Field); } @@ -8362,7 +8306,7 @@ return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); } -static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) { +static TypedefDecl *CreateHexagonBuiltinVaListDecl(ASTContext const *Context) { // typedef struct __va_list_tag { RecordDecl *VaListTagDecl; VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); @@ -8370,7 +8314,7 @@ const size_t NumFields = 3; QualType FieldTypes[NumFields]; - const char *FieldNames[NumFields]; + char const *FieldNames[NumFields]; // void *CurrentSavedRegisterArea; FieldTypes[0] = Context->getPointerType(Context->VoidTy); @@ -8413,7 +8357,7 @@ return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); } -static TypedefDecl *CreateVaListDecl(const ASTContext *Context, +static TypedefDecl *CreateVaListDecl(ASTContext const *Context, TargetInfo::BuiltinVaListKind Kind) { switch (Kind) { case TargetInfo::CharPtrBuiltinVaList: @@ -8464,7 +8408,7 @@ return BuiltinMSVaListDecl; } -bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const { +bool ASTContext::canBuiltinBeRedeclared(FunctionDecl const *FD) const { return BuiltinInfo.canBeRedeclared(FD->getBuiltinID()); } @@ -8484,14 +8428,13 @@ assert(size > 1 && "set is not overloaded!"); void *memory = Allocate(sizeof(OverloadedTemplateStorage) + - size * sizeof(FunctionTemplateDecl*)); + size * sizeof(FunctionTemplateDecl *)); auto *OT = new (memory) OverloadedTemplateStorage(size); NamedDecl **Storage = OT->getStorage(); for (UnresolvedSetIterator I = Begin; I != End; ++I) { NamedDecl *D = *I; - assert(isa(D) || - isa(D) || + assert(isa(D) || isa(D) || (isa(D) && isa(D->getUnderlyingDecl()))); *Storage++ = D; @@ -8521,7 +8464,7 @@ void *InsertPos = nullptr; QualifiedTemplateName *QTN = - QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); + QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); if (!QTN) { QTN = new (*this, alignof(QualifiedTemplateName)) QualifiedTemplateName(NNS, TemplateKeyword, Template); @@ -8535,7 +8478,7 @@ /// template name such as \c MetaFun::template apply. TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, - const IdentifierInfo *Name) const { + IdentifierInfo const *Name) const { assert((!NNS || NNS->isDependent()) && "Nested name specifier must be dependent"); @@ -8544,7 +8487,7 @@ void *InsertPos = nullptr; DependentTemplateName *QTN = - DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); + DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); if (QTN) return TemplateName(QTN); @@ -8558,7 +8501,7 @@ QTN = new (*this, alignof(DependentTemplateName)) DependentTemplateName(NNS, Name, Canon); DependentTemplateName *CheckQTN = - DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); + DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); assert(!CheckQTN && "Dependent type name canonicalization broken"); (void)CheckQTN; } @@ -8579,8 +8522,8 @@ DependentTemplateName::Profile(ID, NNS, Operator); void *InsertPos = nullptr; - DependentTemplateName *QTN - = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); + DependentTemplateName *QTN = + DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); if (QTN) return TemplateName(QTN); @@ -8594,8 +8537,8 @@ QTN = new (*this, alignof(DependentTemplateName)) DependentTemplateName(NNS, Operator, Canon); - DependentTemplateName *CheckQTN - = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); + DependentTemplateName *CheckQTN = + DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); assert(!CheckQTN && "Dependent template name canonicalization broken"); (void)CheckQTN; } @@ -8611,8 +8554,8 @@ SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); void *insertPos = nullptr; - SubstTemplateTemplateParmStorage *subst - = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); + SubstTemplateTemplateParmStorage *subst = + SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); if (!subst) { subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); @@ -8622,21 +8565,19 @@ return TemplateName(subst); } -TemplateName -ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, - const TemplateArgument &ArgPack) const { +TemplateName ASTContext::getSubstTemplateTemplateParmPack( + TemplateTemplateParmDecl *Param, TemplateArgument const &ArgPack) const { auto &Self = const_cast(*this); llvm::FoldingSetNodeID ID; SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); void *InsertPos = nullptr; - SubstTemplateTemplateParmPackStorage *Subst - = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); + SubstTemplateTemplateParmPackStorage *Subst = + SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); if (!Subst) { - Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, - ArgPack.pack_size(), - ArgPack.pack_begin()); + Subst = new (*this) SubstTemplateTemplateParmPackStorage( + Param, ArgPack.pack_size(), ArgPack.pack_begin()); SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); } @@ -8648,17 +8589,28 @@ /// is actually a value of type @c TargetInfo::IntType. CanQualType ASTContext::getFromTargetType(unsigned Type) const { switch (Type) { - case TargetInfo::NoInt: return {}; - case TargetInfo::SignedChar: return SignedCharTy; - case TargetInfo::UnsignedChar: return UnsignedCharTy; - case TargetInfo::SignedShort: return ShortTy; - case TargetInfo::UnsignedShort: return UnsignedShortTy; - case TargetInfo::SignedInt: return IntTy; - case TargetInfo::UnsignedInt: return UnsignedIntTy; - case TargetInfo::SignedLong: return LongTy; - case TargetInfo::UnsignedLong: return UnsignedLongTy; - case TargetInfo::SignedLongLong: return LongLongTy; - case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; + case TargetInfo::NoInt: + return {}; + case TargetInfo::SignedChar: + return SignedCharTy; + case TargetInfo::UnsignedChar: + return UnsignedCharTy; + case TargetInfo::SignedShort: + return ShortTy; + case TargetInfo::UnsignedShort: + return UnsignedShortTy; + case TargetInfo::SignedInt: + return IntTy; + case TargetInfo::UnsignedInt: + return UnsignedIntTy; + case TargetInfo::SignedLong: + return LongTy; + case TargetInfo::UnsignedLong: + return UnsignedLongTy; + case TargetInfo::SignedLongLong: + return LongLongTy; + case TargetInfo::UnsignedLongLong: + return UnsignedLongLongTy; } llvm_unreachable("Unhandled TargetInfo::IntType value"); @@ -8691,7 +8643,7 @@ // pointer. #ifndef NDEBUG QualType CT = Ty->getCanonicalTypeInternal(); - while (const auto *AT = dyn_cast(CT)) + while (auto const *AT = dyn_cast(CT)) CT = AT->getElementType(); assert(CT->isAnyPointerType() || CT->isBlockPointerType()); #endif @@ -8705,8 +8657,7 @@ /// areCompatVectorTypes - Return true if the two specified vector types are /// compatible. -static bool areCompatVectorTypes(const VectorType *LHS, - const VectorType *RHS) { +static bool areCompatVectorTypes(VectorType const *LHS, VectorType const *RHS) { assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); return LHS->getElementType() == RHS->getElementType() && LHS->getNumElements() == RHS->getNumElements(); @@ -8714,8 +8665,8 @@ /// areCompatMatrixTypes - Return true if the two specified matrix types are /// compatible. -static bool areCompatMatrixTypes(const ConstantMatrixType *LHS, - const ConstantMatrixType *RHS) { +static bool areCompatMatrixTypes(ConstantMatrixType const *LHS, + ConstantMatrixType const *RHS) { assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); return LHS->getElementType() == RHS->getElementType() && LHS->getNumRows() == RHS->getNumRows() && @@ -8732,8 +8683,8 @@ // Treat Neon vector types and most AltiVec vector types as if they are the // equivalent GCC vector types. - const auto *First = FirstVec->castAs(); - const auto *Second = SecondVec->castAs(); + auto const *First = FirstVec->castAs(); + auto const *Second = SecondVec->castAs(); if (First->getNumElements() == Second->getNumElements() && hasSameType(First->getElementType(), Second->getElementType()) && First->getVectorKind() != VectorType::AltiVecPixel && @@ -8750,7 +8701,7 @@ } /// getSVETypeSize - Return SVE vector or predicate register size. -static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) { +static uint64_t getSVETypeSize(ASTContext &Context, BuiltinType const *Ty) { assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type"); return Ty->getKind() == BuiltinType::SveBool ? Context.getLangOpts().ArmSveVectorBits / Context.getCharWidth() @@ -8841,19 +8792,19 @@ bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const { while (true) { // __strong id - if (const AttributedType *Attr = dyn_cast(Ty)) { + if (AttributedType const *Attr = dyn_cast(Ty)) { if (Attr->getAttrKind() == attr::ObjCOwnership) return true; Ty = Attr->getModifiedType(); - // X *__strong (...) - } else if (const ParenType *Paren = dyn_cast(Ty)) { + // X *__strong (...) + } else if (ParenType const *Paren = dyn_cast(Ty)) { Ty = Paren->getInnerType(); - // We do not want to look through typedefs, typeof(expr), - // typeof(type), or any other way that the type is somehow - // abstracted. + // We do not want to look through typedefs, typeof(expr), + // typeof(type), or any other way that the type is somehow + // abstracted. } else { return false; } @@ -8866,9 +8817,8 @@ /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the /// inheritance hierarchy of 'rProto'. -bool -ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, - ObjCProtocolDecl *rProto) const { +bool ASTContext::ProtocolCompatibleWithProtocol( + ObjCProtocolDecl *lProto, ObjCProtocolDecl *rProto) const { if (declaresSameEntity(lProto, rProto)) return true; for (auto *PI : rProto->protocols()) @@ -8880,7 +8830,7 @@ /// ObjCQualifiedClassTypesAreCompatible - compare Class and /// Class. bool ASTContext::ObjCQualifiedClassTypesAreCompatible( - const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) { + ObjCObjectPointerType const *lhs, ObjCObjectPointerType const *rhs) { for (auto *lhsProto : lhs->quals()) { bool match = false; for (auto *rhsProto : rhs->quals()) { @@ -8898,7 +8848,7 @@ /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an /// ObjCQualifiedIDType. bool ASTContext::ObjCQualifiedIdTypesAreCompatible( - const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs, + ObjCObjectPointerType const *lhs, ObjCObjectPointerType const *rhs, bool compare) { // Allow id and an 'id' in all cases. if (lhs->isObjCIdType() || rhs->isObjCIdType()) @@ -8983,7 +8933,8 @@ } // Static class's protocols, or its super class or category protocols - // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. + // must be found, direct or indirect in rhs's qualifier list or it is a + // mismatch. if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) { llvm::SmallPtrSet LHSInheritedProtocols; CollectInheritedProtocols(lhsID, LHSInheritedProtocols); @@ -9013,10 +8964,10 @@ /// canAssignObjCInterfaces - Return true if the two interface types are /// compatible for assignment from RHS to LHS. This handles validation of any /// protocol qualifiers on the LHS or RHS. -bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, - const ObjCObjectPointerType *RHSOPT) { - const ObjCObjectType* LHS = LHSOPT->getObjectType(); - const ObjCObjectType* RHS = RHSOPT->getObjectType(); +bool ASTContext::canAssignObjCInterfaces(ObjCObjectPointerType const *LHSOPT, + ObjCObjectPointerType const *RHSOPT) { + ObjCObjectType const *LHS = LHSOPT->getObjectType(); + ObjCObjectType const *RHS = RHSOPT->getObjectType(); // If either type represents the built-in 'id' type, return true. if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId()) @@ -9067,9 +9018,8 @@ /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is /// not OK. For the return type, the opposite is not OK. bool ASTContext::canAssignObjCInterfacesInBlockPointer( - const ObjCObjectPointerType *LHSOPT, - const ObjCObjectPointerType *RHSOPT, - bool BlockReturnType) { + ObjCObjectPointerType const *LHSOPT, ObjCObjectPointerType const *RHSOPT, + bool BlockReturnType) { // Function object that propagates a successful result or handles // __kindof types. @@ -9084,9 +9034,8 @@ // Strip off __kindof and protocol qualifiers, then check whether // we can assign the other way. return canAssignObjCInterfacesInBlockPointer( - RHSOPT->stripObjCKindOfTypeAndQuals(*this), - LHSOPT->stripObjCKindOfTypeAndQuals(*this), - BlockReturnType); + RHSOPT->stripObjCKindOfTypeAndQuals(*this), + LHSOPT->stripObjCKindOfTypeAndQuals(*this), BlockReturnType); }; if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) @@ -9110,16 +9059,15 @@ (BlockReturnType ? RHSOPT : LHSOPT), false)); } - const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); - const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); - if (LHS && RHS) { // We have 2 user-defined types. + ObjCInterfaceType const *LHS = LHSOPT->getInterfaceType(); + ObjCInterfaceType const *RHS = RHSOPT->getInterfaceType(); + if (LHS && RHS) { // We have 2 user-defined types. if (LHS != RHS) { if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) return finish(BlockReturnType); if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) return finish(!BlockReturnType); - } - else + } else return true; } return false; @@ -9127,8 +9075,8 @@ /// Comparison routine for Objective-C protocols to be used with /// llvm::array_pod_sort. -static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, - ObjCProtocolDecl * const *rhs) { +static int compareObjCProtocolsByName(ObjCProtocolDecl *const *lhs, + ObjCProtocolDecl *const *rhs) { return (*lhs)->getName().compare((*rhs)->getName()); } @@ -9137,15 +9085,13 @@ /// the given common base. /// It is used to build composite qualifier list of the composite type of /// the conditional expression involving two objective-c pointer objects. -static -void getIntersectionOfProtocols(ASTContext &Context, - const ObjCInterfaceDecl *CommonBase, - const ObjCObjectPointerType *LHSOPT, - const ObjCObjectPointerType *RHSOPT, - SmallVectorImpl &IntersectionSet) { - - const ObjCObjectType* LHS = LHSOPT->getObjectType(); - const ObjCObjectType* RHS = RHSOPT->getObjectType(); +static void getIntersectionOfProtocols( + ASTContext &Context, ObjCInterfaceDecl const *CommonBase, + ObjCObjectPointerType const *LHSOPT, ObjCObjectPointerType const *RHSOPT, + SmallVectorImpl &IntersectionSet) { + + ObjCObjectType const *LHS = LHSOPT->getObjectType(); + ObjCObjectType const *RHS = RHSOPT->getObjectType(); assert(LHS->getInterface() && "LHS must have an interface base"); assert(RHS->getInterface() && "RHS must have an interface base"); @@ -9185,12 +9131,11 @@ // Remove any implied protocols from the list of inherited protocols. if (!ImpliedProtocols.empty()) { IntersectionSet.erase( - std::remove_if(IntersectionSet.begin(), - IntersectionSet.end(), - [&](ObjCProtocolDecl *proto) -> bool { - return ImpliedProtocols.count(proto) > 0; - }), - IntersectionSet.end()); + std::remove_if(IntersectionSet.begin(), IntersectionSet.end(), + [&](ObjCProtocolDecl *proto) -> bool { + return ImpliedProtocols.count(proto) > 0; + }), + IntersectionSet.end()); } // Sort the remaining protocols by name. @@ -9202,14 +9147,14 @@ static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs, QualType rhs) { // Common case: two object pointers. - const auto *lhsOPT = lhs->getAs(); - const auto *rhsOPT = rhs->getAs(); + auto const *lhsOPT = lhs->getAs(); + auto const *rhsOPT = rhs->getAs(); if (lhsOPT && rhsOPT) return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT); // Two block pointers. - const auto *lhsBlock = lhs->getAs(); - const auto *rhsBlock = rhs->getAs(); + auto const *lhsBlock = lhs->getAs(); + auto const *rhsBlock = rhs->getAs(); if (lhsBlock && rhsBlock) return ctx.typesAreBlockPointerCompatible(lhs, rhs); @@ -9223,11 +9168,9 @@ } // Check that the given Objective-C type argument lists are equivalent. -static bool sameObjCTypeArgs(ASTContext &ctx, - const ObjCInterfaceDecl *iface, +static bool sameObjCTypeArgs(ASTContext &ctx, ObjCInterfaceDecl const *iface, ArrayRef lhsArgs, - ArrayRef rhsArgs, - bool stripKindOf) { + ArrayRef rhsArgs, bool stripKindOf) { if (lhsArgs.size() != rhsArgs.size()) return false; @@ -9260,13 +9203,13 @@ return true; } -QualType ASTContext::areCommonBaseCompatible( - const ObjCObjectPointerType *Lptr, - const ObjCObjectPointerType *Rptr) { - const ObjCObjectType *LHS = Lptr->getObjectType(); - const ObjCObjectType *RHS = Rptr->getObjectType(); - const ObjCInterfaceDecl* LDecl = LHS->getInterface(); - const ObjCInterfaceDecl* RDecl = RHS->getInterface(); +QualType +ASTContext::areCommonBaseCompatible(ObjCObjectPointerType const *Lptr, + ObjCObjectPointerType const *Rptr) { + ObjCObjectType const *LHS = Lptr->getObjectType(); + ObjCObjectType const *RHS = Rptr->getObjectType(); + ObjCInterfaceDecl const *LDecl = LHS->getInterface(); + ObjCInterfaceDecl const *RDecl = RHS->getInterface(); if (!LDecl || !RDecl) return {}; @@ -9278,8 +9221,8 @@ // Follow the left-hand side up the class hierarchy until we either hit a // root or find the RHS. Record the ancestors in case we don't find it. - llvm::SmallDenseMap - LHSAncestors; + llvm::SmallDenseMap + LHSAncestors; while (true) { // Record this ancestor. We'll need this if the common type isn't in the // path from the LHS to the root. @@ -9291,8 +9234,8 @@ bool anyChanges = false; if (LHS->isSpecialized() && RHS->isSpecialized()) { // Both have type arguments, compare them. - if (!sameObjCTypeArgs(*this, LHS->getInterface(), - LHS->getTypeArgs(), RHS->getTypeArgs(), + if (!sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(), + RHS->getTypeArgs(), /*stripKindOf=*/true)) return {}; } else if (LHS->isSpecialized() != RHS->isSpecialized()) { @@ -9342,8 +9285,8 @@ bool anyChanges = false; if (LHS->isSpecialized() && RHS->isSpecialized()) { // Both have type arguments, compare them. - if (!sameObjCTypeArgs(*this, LHS->getInterface(), - LHS->getTypeArgs(), RHS->getTypeArgs(), + if (!sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(), + RHS->getTypeArgs(), /*stripKindOf=*/true)) return {}; } else if (LHS->isSpecialized() != RHS->isSpecialized()) { @@ -9383,8 +9326,8 @@ return {}; } -bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, - const ObjCObjectType *RHS) { +bool ASTContext::canAssignObjCInterfaces(ObjCObjectType const *LHS, + ObjCObjectType const *RHS) { assert(LHS->getInterface() && "LHS is not an interface type"); assert(RHS->getInterface() && "RHS is not an interface type"); @@ -9404,16 +9347,17 @@ // in LHS's protocol list. Example, SuperObj = lhs is ok. // But not SuperObj = lhs. llvm::SmallPtrSet SuperClassInheritedProtocols; - CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); - // Also, if RHS has explicit quelifiers, include them for comparing with LHS's - // qualifiers. + CollectInheritedProtocols(RHS->getInterface(), + SuperClassInheritedProtocols); + // Also, if RHS has explicit quelifiers, include them for comparing with + // LHS's qualifiers. for (auto *RHSPI : RHS->quals()) CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols); // If there is no protocols associated with RHS, it is not a match. if (SuperClassInheritedProtocols.empty()) return false; - for (const auto *LHSProto : LHS->quals()) { + for (auto const *LHSProto : LHS->quals()) { bool SuperImplementsProtocol = false; for (auto *SuperClassProto : SuperClassInheritedProtocols) if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { @@ -9429,14 +9373,14 @@ if (LHS->isSpecialized()) { // Follow the superclass chain until we've matched the LHS class in the // hierarchy. This substitutes type arguments through. - const ObjCObjectType *RHSSuper = RHS; + ObjCObjectType const *RHSSuper = RHS; while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface)) RHSSuper = RHSSuper->getSuperClassType()->castAs(); // If the RHS is specializd, compare type arguments. if (RHSSuper->isSpecialized() && - !sameObjCTypeArgs(*this, LHS->getInterface(), - LHS->getTypeArgs(), RHSSuper->getTypeArgs(), + !sameObjCTypeArgs(*this, LHS->getInterface(), LHS->getTypeArgs(), + RHSSuper->getTypeArgs(), /*stripKindOf=*/true)) { return false; } @@ -9447,8 +9391,8 @@ bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { // get the "pointed to" types - const auto *LHSOPT = LHS->getAs(); - const auto *RHSOPT = RHS->getAs(); + auto const *LHSOPT = LHS->getAs(); + auto const *RHSOPT = RHS->getAs(); if (!LHSOPT || !RHSOPT) return false; @@ -9489,10 +9433,10 @@ QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, bool OfBlockPointer, bool Unqualified) { - if (const RecordType *UT = T->getAsUnionType()) { + if (RecordType const *UT = T->getAsUnionType()) { RecordDecl *UD = UT->getDecl(); if (UD->hasAttr()) { - for (const auto *I : UD->fields()) { + for (auto const *I : UD->fields()) { QualType ET = I->getType().getUnqualifiedType(); QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); if (!MT.isNull()) @@ -9512,13 +9456,13 @@ // GNU extension: two types are compatible if they appear as a function // argument, one of the types is a transparent union type and the other // type is compatible with a union member - QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, - Unqualified); + QualType lmerge = + mergeTransparentUnionType(lhs, rhs, OfBlockPointer, Unqualified); if (!lmerge.isNull()) return lmerge; - QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, - Unqualified); + QualType rmerge = + mergeTransparentUnionType(rhs, lhs, OfBlockPointer, Unqualified); if (!rmerge.isNull()) return rmerge; @@ -9528,10 +9472,10 @@ QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, bool OfBlockPointer, bool Unqualified, bool AllowCXX) { - const auto *lbase = lhs->castAs(); - const auto *rbase = rhs->castAs(); - const auto *lproto = dyn_cast(lbase); - const auto *rproto = dyn_cast(rbase); + auto const *lbase = lhs->castAs(); + auto const *rbase = rhs->castAs(); + auto const *lproto = dyn_cast(lbase); + auto const *rproto = dyn_cast(rbase); bool allLTypes = true; bool allRTypes = true; @@ -9544,8 +9488,7 @@ if (!UnqualifiedResult) UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); - } - else + } else retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, Unqualified); if (retType.isNull()) @@ -9569,7 +9512,8 @@ // FIXME: double check this // FIXME: should we error if lbase->getRegParmAttr() != 0 && // rbase->getRegParmAttr() != 0 && - // lbase->getRegParmAttr() != rbase->getRegParmAttr()? + // lbase->getRegParmAttr() != + // rbase->getRegParmAttr()? FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); @@ -9651,8 +9595,10 @@ allRTypes = false; } - if (allLTypes) return lhs; - if (allRTypes) return rhs; + if (allLTypes) + return lhs; + if (allRTypes) + return rhs; FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); EPI.ExtInfo = einfo; @@ -9661,10 +9607,12 @@ return getFunctionType(retType, types, EPI); } - if (lproto) allRTypes = false; - if (rproto) allLTypes = false; + if (lproto) + allRTypes = false; + if (rproto) + allLTypes = false; - const FunctionProtoType *proto = lproto ? lproto : rproto; + FunctionProtoType const *proto = lproto ? lproto : rproto; if (proto) { assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here"); if (proto->isVariadic()) @@ -9679,7 +9627,7 @@ // Look at the converted type of enum types, since that is the type used // to pass enum values. - if (const auto *Enum = paramTy->getAs()) { + if (auto const *Enum = paramTy->getAs()) { paramTy = Enum->getDecl()->getIntegerType(); if (paramTy.isNull()) return {}; @@ -9690,21 +9638,25 @@ return {}; } - if (allLTypes) return lhs; - if (allRTypes) return rhs; + if (allLTypes) + return lhs; + if (allRTypes) + return rhs; FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); EPI.ExtInfo = einfo; return getFunctionType(retType, proto->getParamTypes(), EPI); } - if (allLTypes) return lhs; - if (allRTypes) return rhs; + if (allLTypes) + return lhs; + if (allRTypes) + return rhs; return getFunctionNoProtoType(retType, einfo); } /// Given that we have an enum type and a non-enum type, try to merge them. -static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, +static QualType mergeEnumWithInteger(ASTContext &Context, EnumType const *ET, QualType other, bool isBlockReturnType) { // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, // a signed integer type, or an unsigned integer type. @@ -9725,8 +9677,7 @@ return {}; } -QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, - bool OfBlockPointer, +QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer, bool Unqualified, bool BlockReturnType) { // For C++ we will not reach this code with reference types (see below), // for OpenMP variant call overloading we might. @@ -9749,8 +9700,7 @@ RHS = RHS.getUnqualifiedType(); } - QualType LHSCan = getCanonicalType(LHS), - RHSCan = getCanonicalType(RHS); + QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS); // If two types are identical, they are compatible. if (LHSCan == RHSCan) @@ -9796,8 +9746,10 @@ // We want to consider the two function types to be the same for these // comparisons, just force one to the other. - if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; - if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; + if (LHSClass == Type::FunctionProto) + LHSClass = Type::FunctionNoProto; + if (RHSClass == Type::FunctionProto) + RHSClass = Type::FunctionNoProto; // Same as above for arrays if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) @@ -9806,27 +9758,31 @@ RHSClass = Type::ConstantArray; // ObjCInterfaces are just specialized ObjCObjects. - if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; - if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; + if (LHSClass == Type::ObjCInterface) + LHSClass = Type::ObjCObject; + if (RHSClass == Type::ObjCInterface) + RHSClass = Type::ObjCObject; // Canonicalize ExtVector -> Vector. - if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; - if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; + if (LHSClass == Type::ExtVector) + LHSClass = Type::Vector; + if (RHSClass == Type::ExtVector) + RHSClass = Type::Vector; // If the canonical type classes don't match. if (LHSClass != RHSClass) { // Note that we only have special rules for turning block enum // returns into block int returns, not vice-versa. - if (const auto *ETy = LHS->getAs()) { + if (auto const *ETy = LHS->getAs()) { return mergeEnumWithInteger(*this, ETy, RHS, false); } - if (const EnumType* ETy = RHS->getAs()) { + if (EnumType const *ETy = RHS->getAs()) { return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); } // allow block pointer type to match an 'id' type. if (OfBlockPointer && !BlockReturnType) { - if (LHS->isObjCIdType() && RHS->isBlockPointerType()) - return LHS; + if (LHS->isObjCIdType() && RHS->isBlockPointerType()) + return LHS; if (RHS->isObjCIdType() && LHS->isBlockPointerType()) return RHS; } @@ -9858,8 +9814,7 @@ case Type::ExtVector: llvm_unreachable("Types are eliminated above"); - case Type::Pointer: - { + case Type::Pointer: { // Merge two pointer types, while trying to preserve typedef info QualType LHSPointee = LHS->castAs()->getPointeeType(); QualType RHSPointee = RHS->castAs()->getPointeeType(); @@ -9867,8 +9822,8 @@ LHSPointee = LHSPointee.getUnqualifiedType(); RHSPointee = RHSPointee.getUnqualifiedType(); } - QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, - Unqualified); + QualType ResultType = + mergeTypes(LHSPointee, RHSPointee, false, Unqualified); if (ResultType.isNull()) return {}; if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) @@ -9877,8 +9832,7 @@ return RHS; return getPointerType(ResultType); } - case Type::BlockPointer: - { + case Type::BlockPointer: { // Merge two block pointer types, while trying to preserve typedef info QualType LHSPointee = LHS->castAs()->getPointeeType(); QualType RHSPointee = RHS->castAs()->getPointeeType(); @@ -9900,8 +9854,8 @@ RHSPointee = QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue()); } - QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, - Unqualified); + QualType ResultType = + mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, Unqualified); if (ResultType.isNull()) return {}; if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) @@ -9910,8 +9864,7 @@ return RHS; return getBlockPointerType(ResultType); } - case Type::Atomic: - { + case Type::Atomic: { // Merge two pointer types, while trying to preserve typedef info QualType LHSValue = LHS->castAs()->getValueType(); QualType RHSValue = RHS->castAs()->getValueType(); @@ -9919,8 +9872,7 @@ LHSValue = LHSValue.getUnqualifiedType(); RHSValue = RHSValue.getUnqualifiedType(); } - QualType ResultType = mergeTypes(LHSValue, RHSValue, false, - Unqualified); + QualType ResultType = mergeTypes(LHSValue, RHSValue, false, Unqualified); if (ResultType.isNull()) return {}; if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) @@ -9929,10 +9881,9 @@ return RHS; return getAtomicType(ResultType); } - case Type::ConstantArray: - { - const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); - const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); + case Type::ConstantArray: { + ConstantArrayType const *LCAT = getAsConstantArrayType(LHS); + ConstantArrayType const *RCAT = getAsConstantArrayType(RHS); if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) return {}; @@ -9947,15 +9898,15 @@ if (ResultType.isNull()) return {}; - const VariableArrayType* LVAT = getAsVariableArrayType(LHS); - const VariableArrayType* RVAT = getAsVariableArrayType(RHS); + VariableArrayType const *LVAT = getAsVariableArrayType(LHS); + VariableArrayType const *RVAT = getAsVariableArrayType(RHS); // If either side is a variable array, and both are complete, check whether // the current dimension is definite. if (LVAT || RVAT) { - auto SizeFetch = [this](const VariableArrayType* VAT, - const ConstantArrayType* CAT) - -> std::pair { + auto SizeFetch = + [this](VariableArrayType const *VAT, + ConstantArrayType const *CAT) -> std::pair { if (VAT) { Optional TheInt; Expr *E = VAT->getSizeExpr(); @@ -10004,10 +9955,12 @@ // has to be different. return RHS; } - if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; - if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; - return getIncompleteArrayType(ResultType, - ArrayType::ArraySizeModifier(), 0); + if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) + return LHS; + if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) + return RHS; + return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(), + 0); } case Type::FunctionNoProto: return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); @@ -10058,7 +10011,7 @@ return {}; case Type::ExtInt: { // Merge two ext-int types, while trying to preserve typedef info. - bool LHSUnsigned = LHS->castAs()->isUnsigned(); + bool LHSUnsigned = LHS->castAs()->isUnsigned(); bool RHSUnsigned = RHS->castAs()->isUnsigned(); unsigned LHSBits = LHS->castAs()->getNumBits(); unsigned RHSBits = RHS->castAs()->getNumBits(); @@ -10077,7 +10030,7 @@ } bool ASTContext::mergeExtParameterInfo( - const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType, + FunctionProtoType const *FirstFnType, FunctionProtoType const *SecondFnType, bool &CanUseFirst, bool &CanUseSecond, SmallVectorImpl &NewParamInfos) { assert(NewParamInfos.empty() && "param info list not empty"); @@ -10123,7 +10076,7 @@ return true; } -void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) { +void ASTContext::ResetObjCLayout(ObjCContainerDecl const *CD) { ObjCLayouts[CD] = nullptr; } @@ -10131,8 +10084,7 @@ /// 'RHS' attributes and returns the merged version; including for function /// return types. QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { - QualType LHSCan = getCanonicalType(LHS), - RHSCan = getCanonicalType(RHS); + QualType LHSCan = getCanonicalType(LHS), RHSCan = getCanonicalType(RHS); // If two types are identical, they are compatible. if (LHSCan == RHSCan) return LHS; @@ -10144,14 +10096,14 @@ QualType NewReturnType = cast(LHSCan.getTypePtr())->getReturnType(); QualType ResReturnType = - mergeObjCGCQualifiers(NewReturnType, OldReturnType); + mergeObjCGCQualifiers(NewReturnType, OldReturnType); if (ResReturnType.isNull()) return {}; if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); // In either case, use OldReturnType to build the new function type. - const auto *F = LHS->castAs(); - if (const auto *FPT = cast(F)) { + auto const *F = LHS->castAs(); + if (auto const *FPT = cast(F)) { FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); EPI.ExtInfo = getFunctionExtInfo(LHS); QualType ResultType = @@ -10207,11 +10159,11 @@ //===----------------------------------------------------------------------===// unsigned ASTContext::getIntWidth(QualType T) const { - if (const auto *ET = T->getAs()) + if (auto const *ET = T->getAs()) T = ET->getDecl()->getIntegerType(); if (T->isBooleanType()) return 1; - if(const auto *EIT = T->getAs()) + if (auto const *EIT = T->getAs()) return EIT->getNumBits(); // For builtin types, just use the standard type sizing method return (unsigned)getTypeSize(T); @@ -10222,17 +10174,17 @@ "Unexpected type"); // Turn <4 x signed int> -> <4 x unsigned int> - if (const auto *VTy = T->getAs()) + if (auto const *VTy = T->getAs()) return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), VTy->getNumElements(), VTy->getVectorKind()); // For _ExtInt, return an unsigned _ExtInt with same width. - if (const auto *EITy = T->getAs()) + if (auto const *EITy = T->getAs()) return getExtIntType(/*IsUnsigned=*/true, EITy->getNumBits()); // For enums, get the underlying integer type of the enum, and let the general // integer type signchanging code handle it. - if (const auto *ETy = T->getAs()) + if (auto const *ETy = T->getAs()) T = ETy->getDecl()->getIntegerType(); switch (T->castAs()->getKind()) { @@ -10290,17 +10242,17 @@ "Unexpected type"); // Turn <4 x unsigned int> -> <4 x signed int> - if (const auto *VTy = T->getAs()) + if (auto const *VTy = T->getAs()) return getVectorType(getCorrespondingSignedType(VTy->getElementType()), VTy->getNumElements(), VTy->getVectorKind()); // For _ExtInt, return a signed _ExtInt with same width. - if (const auto *EITy = T->getAs()) + if (auto const *EITy = T->getAs()) return getExtIntType(/*IsUnsigned=*/false, EITy->getNumBits()); // For enums, get the underlying integer type of the enum, and let the general // integer type signchanging code handle it. - if (const auto *ETy = T->getAs()) + if (auto const *ETy = T->getAs()) T = ETy->getDecl()->getIntegerType(); switch (T->castAs()->getKind()) { @@ -10354,7 +10306,7 @@ ASTMutationListener::~ASTMutationListener() = default; -void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, +void ASTMutationListener::DeducedReturnType(FunctionDecl const *FD, QualType ReturnType) {} //===----------------------------------------------------------------------===// @@ -10369,10 +10321,9 @@ /// /// RequiresICE is filled in on return to indicate whether the value is required /// to be an Integer Constant Expression. -static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, +static QualType DecodeTypeFromStr(char const *&Str, ASTContext const &Context, ASTContext::GetBuiltinTypeError &Error, - bool &RequiresICE, - bool AllowTypeModifiers) { + bool &RequiresICE, bool AllowTypeModifiers) { // Modifiers. int HowLong = 0; bool Signed = false, Unsigned = false; @@ -10380,12 +10331,15 @@ // Read the prefixed modifiers first. bool Done = false; - #ifndef NDEBUG +#ifndef NDEBUG bool IsSpecial = false; - #endif +#endif while (!Done) { switch (*Str++) { - default: Done = true; --Str; break; + default: + Done = true; + --Str; + break; case 'I': RequiresICE = true; break; @@ -10408,9 +10362,9 @@ // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!"); - #ifndef NDEBUG +#ifndef NDEBUG IsSpecial = true; - #endif +#endif if (Context.getTargetInfo().getLongWidth() == 32) ++HowLong; break; @@ -10418,9 +10372,9 @@ // This modifier represents int64 type. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); - #ifndef NDEBUG +#ifndef NDEBUG IsSpecial = true; - #endif +#endif switch (Context.getTargetInfo().getInt64Type()) { default: llvm_unreachable("Unexpected integer type"); @@ -10436,9 +10390,9 @@ // This modifier represents int32 type. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!"); - #ifndef NDEBUG +#ifndef NDEBUG IsSpecial = true; - #endif +#endif switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) { default: llvm_unreachable("Unexpected integer type"); @@ -10456,9 +10410,9 @@ case 'O': assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!"); assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!"); - #ifndef NDEBUG +#ifndef NDEBUG IsSpecial = true; - #endif +#endif if (Context.getLangOpts().OpenCL) HowLong = 1; else @@ -10471,7 +10425,8 @@ // Read the base type. switch (*Str++) { - default: llvm_unreachable("Unknown builtin type letter!"); + default: + llvm_unreachable("Unknown builtin type letter!"); case 'x': assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers used with 'x'!"); @@ -10537,11 +10492,11 @@ assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); Type = Context.BoolTy; break; - case 'z': // size_t. + case 'z': // size_t. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); Type = Context.getSizeType(); break; - case 'w': // wchar_t. + case 'w': // wchar_t. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!"); Type = Context.getWideCharType(); break; @@ -10583,8 +10538,8 @@ assert(End != Str && "Missing vector size"); Str = End; - QualType ElementType = DecodeTypeFromStr(Str, Context, Error, - RequiresICE, false); + QualType ElementType = + DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); assert(!RequiresICE && "Can't require vector ICE"); Type = Context.getScalableVectorType(ElementType, NumElements); @@ -10596,8 +10551,8 @@ assert(End != Str && "Missing vector size"); Str = End; - QualType ElementType = DecodeTypeFromStr(Str, Context, Error, - RequiresICE, false); + QualType ElementType = + DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); assert(!RequiresICE && "Can't require vector ICE"); // TODO: No way to make AltiVec vectors in builtins yet. @@ -10613,14 +10568,14 @@ Str = End; - QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, - false); + QualType ElementType = + DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); Type = Context.getExtVectorType(ElementType, NumElements); break; } case 'X': { - QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, - false); + QualType ElementType = + DecodeTypeFromStr(Str, Context, Error, RequiresICE, false); assert(!RequiresICE && "Can't require complex ICE"); Type = Context.getComplexType(ElementType); break; @@ -10664,7 +10619,10 @@ Done = !AllowTypeModifiers; while (!Done) { switch (char c = *Str++) { - default: Done = true; --Str; break; + default: + Done = true; + --Str; + break; case '*': case '&': { // Both pointers and references can have their pointee types @@ -10674,8 +10632,7 @@ if (End != Str) { // Note AddrSpace == 0 is not the same as an unspecified address space. Type = Context.getAddrSpaceQualType( - Type, - Context.getLangASForBuiltinAddressSpace(AddrSpace)); + Type, Context.getLangASForBuiltinAddressSpace(AddrSpace)); Str = End; } if (c == '*') @@ -10709,17 +10666,16 @@ // descriptor decoding to define builtins mixing target-dependent and target- // independent types. This function allows decoding one type descriptor with // default decoding. -QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context, +QualType ASTContext::DecodeTypeStr(char const *&Str, ASTContext const &Context, GetBuiltinTypeError &Error, bool &RequireICE, bool AllowTypeModifiers) const { return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers); } /// GetBuiltinType - Return the type for the specified builtin. -QualType ASTContext::GetBuiltinType(unsigned Id, - GetBuiltinTypeError &Error, +QualType ASTContext::GetBuiltinType(unsigned Id, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs) const { - const char *TypeStr = BuiltinInfo.getTypeString(Id); + char const *TypeStr = BuiltinInfo.getTypeString(Id); if (TypeStr[0] == '\0') { Error = GE_Missing_type; return {}; @@ -10729,8 +10685,8 @@ bool RequiresICE = false; Error = GE_None; - QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, - RequiresICE, true); + QualType ResType = + DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); if (Error != GE_None) return {}; @@ -10763,8 +10719,8 @@ FunctionType::ExtInfo EI(getDefaultCallingConvention( Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); - if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); - + if (BuiltinInfo.isNoReturn(Id)) + EI = EI.withNoReturn(true); // We really shouldn't be making a no-proto type here. if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus) @@ -10780,14 +10736,14 @@ return getFunctionType(ResType, ArgTypes, EPI); } -static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, - const FunctionDecl *FD) { +static GVALinkage basicGVALinkageForFunction(ASTContext const &Context, + FunctionDecl const *FD) { if (!FD->isExternallyVisible()) return GVA_Internal; // Non-user-provided functions get emitted as weak definitions with every // use, no matter whether they've been explicitly instantiated etc. - if (const auto *MD = dyn_cast(FD)) + if (auto const *MD = dyn_cast(FD)) if (!MD->isUserProvided()) return GVA_DiscardableODR; @@ -10842,8 +10798,8 @@ return GVA_DiscardableODR; } -static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context, - const Decl *D, GVALinkage L) { +static GVALinkage adjustGVALinkageForAttributes(ASTContext const &Context, + Decl const *D, GVALinkage L) { // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx // dllexport/dllimport on inline functions. if (D->hasAttr()) { @@ -10873,7 +10829,7 @@ /// Adjust the GVALinkage for a declaration based on what an external AST source /// knows about whether there can be other definitions of this declaration. static GVALinkage -adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D, +adjustGVALinkageForExternalDefinitionKind(ASTContext const &Ctx, Decl const *D, GVALinkage L) { ExternalASTSource *Source = Ctx.getExternalSource(); if (!Source) @@ -10895,19 +10851,20 @@ return L; } -GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const { - return adjustGVALinkageForExternalDefinitionKind(*this, FD, - adjustGVALinkageForAttributes(*this, FD, - basicGVALinkageForFunction(*this, FD))); +GVALinkage ASTContext::GetGVALinkageForFunction(FunctionDecl const *FD) const { + return adjustGVALinkageForExternalDefinitionKind( + *this, FD, + adjustGVALinkageForAttributes(*this, FD, + basicGVALinkageForFunction(*this, FD))); } -static GVALinkage basicGVALinkageForVariable(const ASTContext &Context, - const VarDecl *VD) { +static GVALinkage basicGVALinkageForVariable(ASTContext const &Context, + VarDecl const *VD) { if (!VD->isExternallyVisible()) return GVA_Internal; if (VD->isStaticLocal()) { - const DeclContext *LexicalContext = VD->getParentFunctionOrMethod(); + DeclContext const *LexicalContext = VD->getParentFunctionOrMethod(); while (LexicalContext && !isa(LexicalContext)) LexicalContext = LexicalContext->getLexicalParent(); @@ -10978,14 +10935,15 @@ llvm_unreachable("Invalid Linkage!"); } -GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { - return adjustGVALinkageForExternalDefinitionKind(*this, VD, - adjustGVALinkageForAttributes(*this, VD, - basicGVALinkageForVariable(*this, VD))); +GVALinkage ASTContext::GetGVALinkageForVariable(VarDecl const *VD) { + return adjustGVALinkageForExternalDefinitionKind( + *this, VD, + adjustGVALinkageForAttributes(*this, VD, + basicGVALinkageForVariable(*this, VD))); } -bool ASTContext::DeclMustBeEmitted(const Decl *D) { - if (const auto *VD = dyn_cast(D)) { +bool ASTContext::DeclMustBeEmitted(Decl const *D) { + if (auto const *VD = dyn_cast(D)) { if (!VD->isFileVarDecl()) return false; // Global named register variables (GNU extension) are never emitted. @@ -10994,7 +10952,7 @@ if (VD->getDescribedVarTemplate() || isa(VD)) return false; - } else if (const auto *FD = dyn_cast(D)) { + } else if (auto const *FD = dyn_cast(D)) { // We never need to emit an uninstantiated function template. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) return false; @@ -11027,7 +10985,7 @@ if (D->hasAttr() || D->hasAttr()) return true; - if (const auto *FD = dyn_cast(D)) { + if (auto const *FD = dyn_cast(D)) { // Forward declarations aren't required. if (!FD->doesThisDeclarationHaveABody()) return FD->doesDeclarationForceExternallyVisibleDefinition(); @@ -11039,10 +10997,10 @@ // The key function for a class is required. This rule only comes // into play when inline functions can be key functions, though. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { - if (const auto *MD = dyn_cast(FD)) { - const CXXRecordDecl *RD = MD->getParent(); + if (auto const *MD = dyn_cast(FD)) { + CXXRecordDecl const *RD = MD->getParent(); if (MD->isOutOfLine() && RD->isDynamicClass()) { - const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD); + CXXMethodDecl const *KeyFunc = getCurrentKeyFunction(RD); if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) return true; } @@ -11057,7 +11015,7 @@ return !isDiscardableGVALinkage(Linkage); } - const auto *VD = cast(D); + auto const *VD = cast(D); assert(VD->isFileVarDecl() && "Expected file scoped var"); // If the decl is marked as `declare target to`, it should be emitted for the @@ -11091,9 +11049,9 @@ // Likewise, variables with tuple-like bindings are required if their // bindings have side-effects. - if (const auto *DD = dyn_cast(VD)) - for (const auto *BD : DD->bindings()) - if (const auto *BindingVD = BD->getHoldingVar()) + if (auto const *DD = dyn_cast(VD)) + for (auto const *BD : DD->bindings()) + if (auto const *BindingVD = BD->getHoldingVar()) if (DeclMustBeEmitted(BindingVD)) return true; @@ -11101,10 +11059,10 @@ } void ASTContext::forEachMultiversionedFunctionVersion( - const FunctionDecl *FD, + FunctionDecl const *FD, llvm::function_ref Pred) const { assert(FD->isMultiVersion() && "Only valid for multiversioned functions"); - llvm::SmallDenseSet SeenDecls; + llvm::SmallDenseSet SeenDecls; FD = FD->getMostRecentDecl(); // FIXME: The order of traversal here matters and depends on the order of // lookup results, which happens to be (mostly) oldest-to-newest, but we @@ -11158,7 +11116,7 @@ return Target->getDefaultCallingConv(); } -bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { +bool ASTContext::isNearlyEmpty(CXXRecordDecl const *RD) const { // Pass through to the C++ ABI object return ABI->isNearlyEmpty(RD); } @@ -11178,7 +11136,7 @@ return VTContext.get(); } -MangleContext *ASTContext::createMangleContext(const TargetInfo *T) { +MangleContext *ASTContext::createMangleContext(TargetInfo const *T) { if (!T) T = Target; switch (T->getCXXABI().getKind()) { @@ -11199,7 +11157,7 @@ llvm_unreachable("Unsupported ABI"); } -MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) { +MangleContext *ASTContext::createDeviceMangleContext(TargetInfo const &T) { assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft && "Device mangle context does not support Microsoft mangling."); switch (T.getCXXABI().getKind()) { @@ -11215,7 +11173,7 @@ case TargetCXXABI::XL: return ItaniumMangleContext::create( *this, getDiagnostics(), - [](ASTContext &, const NamedDecl *ND) -> llvm::Optional { + [](ASTContext &, NamedDecl const *ND) -> llvm::Optional { if (const auto *RD = dyn_cast(ND)) return RD->getDeviceLambdaManglingNumber(); return llvm::None; @@ -11282,29 +11240,29 @@ llvm_unreachable("Unhandled TargetInfo::RealType value"); } -void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) { +void ASTContext::setManglingNumber(NamedDecl const *ND, unsigned Number) { if (Number > 1) MangleNumbers[ND] = Number; } -unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const { +unsigned ASTContext::getManglingNumber(NamedDecl const *ND) const { auto I = MangleNumbers.find(ND); return I != MangleNumbers.end() ? I->second : 1; } -void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) { +void ASTContext::setStaticLocalNumber(VarDecl const *VD, unsigned Number) { if (Number > 1) StaticLocalNumbers[VD] = Number; } -unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const { +unsigned ASTContext::getStaticLocalNumber(VarDecl const *VD) const { auto I = StaticLocalNumbers.find(VD); return I != StaticLocalNumbers.end() ? I->second : 1; } MangleNumberingContext & -ASTContext::getManglingNumberContext(const DeclContext *DC) { - assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. +ASTContext::getManglingNumberContext(DeclContext const *DC) { + assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. std::unique_ptr &MCtx = MangleNumberingContexts[DC]; if (!MCtx) MCtx = createMangleNumberingContext(); @@ -11312,7 +11270,7 @@ } MangleNumberingContext & -ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) { +ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, Decl const *D) { assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C. std::unique_ptr &MCtx = ExtraMangleNumberingContexts[D]; @@ -11326,7 +11284,7 @@ return ABI->createMangleNumberingContext(); } -const CXXConstructorDecl * +CXXConstructorDecl const * ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) { return ABI->getCopyConstructorForExceptionObject( cast(RD->getFirstDecl())); @@ -11345,7 +11303,7 @@ } TypedefNameDecl * -ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) { +ASTContext::getTypedefNameForUnnamedTagDecl(TagDecl const *TD) { return ABI->getTypedefNameForUnnamedTagDecl(TD); } @@ -11354,15 +11312,15 @@ return ABI->addDeclaratorForUnnamedTagDecl(TD, DD); } -DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) { +DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(TagDecl const *TD) { return ABI->getDeclaratorForUnnamedTagDecl(TD); } -void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { +void ASTContext::setParameterIndex(ParmVarDecl const *D, unsigned int index) { ParamIndices[D] = index; } -unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { +unsigned ASTContext::getParameterIndex(ParmVarDecl const *D) const { ParameterIndexTable::const_iterator I = ParamIndices.find(D); assert(I != ParamIndices.end() && "ParmIndices lacks entry set by ParmVarDecl"); @@ -11394,8 +11352,7 @@ return Result; } -MSGuidDecl * -ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { +MSGuidDecl *ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const { assert(MSGuidTagDecl && "building MS GUID without MS extensions?"); llvm::FoldingSetNodeID ID; @@ -11412,7 +11369,7 @@ } TemplateParamObjectDecl * -ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const { +ASTContext::getTemplateParamObjectDecl(QualType T, APValue const &V) const { assert(T->isRecordType() && "template param object of unexpected type"); // C++ [temp.param]p8: @@ -11432,8 +11389,8 @@ return New; } -bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const { - const llvm::Triple &T = getTargetInfo().getTriple(); +bool ASTContext::AtomicUsesUnsupportedLibcall(AtomicExpr const *E) const { + llvm::Triple const &T = getTargetInfo().getTriple(); if (!T.isOSDarwin()) return false; @@ -11450,15 +11407,13 @@ return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits); } -bool -ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl, - const ObjCMethodDecl *MethodImpl) { +bool ASTContext::ObjCMethodsAreEqual(ObjCMethodDecl const *MethodDecl, + ObjCMethodDecl const *MethodImpl) { // No point trying to match an unavailable/deprecated mothod. - if (MethodDecl->hasAttr() - || MethodDecl->hasAttr()) + if (MethodDecl->hasAttr() || + MethodDecl->hasAttr()) return false; - if (MethodDecl->getObjCDeclQualifier() != - MethodImpl->getObjCDeclQualifier()) + if (MethodDecl->getObjCDeclQualifier() != MethodImpl->getObjCDeclQualifier()) return false; if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType())) return false; @@ -11467,11 +11422,12 @@ return false; for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(), - IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(), - EF = MethodDecl->param_end(); + IF = MethodDecl->param_begin(), + EM = MethodImpl->param_end(), + EF = MethodDecl->param_end(); IM != EM && IF != EF; ++IM, ++IF) { - const ParmVarDecl *DeclVar = (*IF); - const ParmVarDecl *ImplVar = (*IM); + ParmVarDecl const *DeclVar = (*IF); + ParmVarDecl const *ImplVar = (*IM); if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier()) return false; if (!hasSameType(DeclVar->getType(), ImplVar->getType())) @@ -11501,35 +11457,36 @@ QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const { assert(Ty->isFixedPointType()); - if (Ty->isSaturatedFixedPointType()) return Ty; + if (Ty->isSaturatedFixedPointType()) + return Ty; switch (Ty->castAs()->getKind()) { - default: - llvm_unreachable("Not a fixed point type!"); - case BuiltinType::ShortAccum: - return SatShortAccumTy; - case BuiltinType::Accum: - return SatAccumTy; - case BuiltinType::LongAccum: - return SatLongAccumTy; - case BuiltinType::UShortAccum: - return SatUnsignedShortAccumTy; - case BuiltinType::UAccum: - return SatUnsignedAccumTy; - case BuiltinType::ULongAccum: - return SatUnsignedLongAccumTy; - case BuiltinType::ShortFract: - return SatShortFractTy; - case BuiltinType::Fract: - return SatFractTy; - case BuiltinType::LongFract: - return SatLongFractTy; - case BuiltinType::UShortFract: - return SatUnsignedShortFractTy; - case BuiltinType::UFract: - return SatUnsignedFractTy; - case BuiltinType::ULongFract: - return SatUnsignedLongFractTy; + default: + llvm_unreachable("Not a fixed point type!"); + case BuiltinType::ShortAccum: + return SatShortAccumTy; + case BuiltinType::Accum: + return SatAccumTy; + case BuiltinType::LongAccum: + return SatLongAccumTy; + case BuiltinType::UShortAccum: + return SatUnsignedShortAccumTy; + case BuiltinType::UAccum: + return SatUnsignedAccumTy; + case BuiltinType::ULongAccum: + return SatUnsignedLongAccumTy; + case BuiltinType::ShortFract: + return SatShortFractTy; + case BuiltinType::Fract: + return SatFractTy; + case BuiltinType::LongFract: + return SatLongFractTy; + case BuiltinType::UShortFract: + return SatUnsignedShortFractTy; + case BuiltinType::UFract: + return SatUnsignedFractTy; + case BuiltinType::ULongFract: + return SatUnsignedLongFractTy; } } @@ -11545,97 +11502,96 @@ // Explicitly instantiate this in case a Redeclarable is used from a TU that // doesn't include ASTContext.h -template -clang::LazyGenerationalUpdatePtr< - const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType -clang::LazyGenerationalUpdatePtr< - const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue( - const clang::ASTContext &Ctx, Decl *Value); +template clang::LazyGenerationalUpdatePtr< + Decl const *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType +clang::LazyGenerationalUpdatePtr:: + makeValue(clang::ASTContext const &Ctx, Decl *Value); unsigned char ASTContext::getFixedPointScale(QualType Ty) const { assert(Ty->isFixedPointType()); - const TargetInfo &Target = getTargetInfo(); + TargetInfo const &Target = getTargetInfo(); switch (Ty->castAs()->getKind()) { - default: - llvm_unreachable("Not a fixed point type!"); - case BuiltinType::ShortAccum: - case BuiltinType::SatShortAccum: - return Target.getShortAccumScale(); - case BuiltinType::Accum: - case BuiltinType::SatAccum: - return Target.getAccumScale(); - case BuiltinType::LongAccum: - case BuiltinType::SatLongAccum: - return Target.getLongAccumScale(); - case BuiltinType::UShortAccum: - case BuiltinType::SatUShortAccum: - return Target.getUnsignedShortAccumScale(); - case BuiltinType::UAccum: - case BuiltinType::SatUAccum: - return Target.getUnsignedAccumScale(); - case BuiltinType::ULongAccum: - case BuiltinType::SatULongAccum: - return Target.getUnsignedLongAccumScale(); - case BuiltinType::ShortFract: - case BuiltinType::SatShortFract: - return Target.getShortFractScale(); - case BuiltinType::Fract: - case BuiltinType::SatFract: - return Target.getFractScale(); - case BuiltinType::LongFract: - case BuiltinType::SatLongFract: - return Target.getLongFractScale(); - case BuiltinType::UShortFract: - case BuiltinType::SatUShortFract: - return Target.getUnsignedShortFractScale(); - case BuiltinType::UFract: - case BuiltinType::SatUFract: - return Target.getUnsignedFractScale(); - case BuiltinType::ULongFract: - case BuiltinType::SatULongFract: - return Target.getUnsignedLongFractScale(); + default: + llvm_unreachable("Not a fixed point type!"); + case BuiltinType::ShortAccum: + case BuiltinType::SatShortAccum: + return Target.getShortAccumScale(); + case BuiltinType::Accum: + case BuiltinType::SatAccum: + return Target.getAccumScale(); + case BuiltinType::LongAccum: + case BuiltinType::SatLongAccum: + return Target.getLongAccumScale(); + case BuiltinType::UShortAccum: + case BuiltinType::SatUShortAccum: + return Target.getUnsignedShortAccumScale(); + case BuiltinType::UAccum: + case BuiltinType::SatUAccum: + return Target.getUnsignedAccumScale(); + case BuiltinType::ULongAccum: + case BuiltinType::SatULongAccum: + return Target.getUnsignedLongAccumScale(); + case BuiltinType::ShortFract: + case BuiltinType::SatShortFract: + return Target.getShortFractScale(); + case BuiltinType::Fract: + case BuiltinType::SatFract: + return Target.getFractScale(); + case BuiltinType::LongFract: + case BuiltinType::SatLongFract: + return Target.getLongFractScale(); + case BuiltinType::UShortFract: + case BuiltinType::SatUShortFract: + return Target.getUnsignedShortFractScale(); + case BuiltinType::UFract: + case BuiltinType::SatUFract: + return Target.getUnsignedFractScale(); + case BuiltinType::ULongFract: + case BuiltinType::SatULongFract: + return Target.getUnsignedLongFractScale(); } } unsigned char ASTContext::getFixedPointIBits(QualType Ty) const { assert(Ty->isFixedPointType()); - const TargetInfo &Target = getTargetInfo(); + TargetInfo const &Target = getTargetInfo(); switch (Ty->castAs()->getKind()) { - default: - llvm_unreachable("Not a fixed point type!"); - case BuiltinType::ShortAccum: - case BuiltinType::SatShortAccum: - return Target.getShortAccumIBits(); - case BuiltinType::Accum: - case BuiltinType::SatAccum: - return Target.getAccumIBits(); - case BuiltinType::LongAccum: - case BuiltinType::SatLongAccum: - return Target.getLongAccumIBits(); - case BuiltinType::UShortAccum: - case BuiltinType::SatUShortAccum: - return Target.getUnsignedShortAccumIBits(); - case BuiltinType::UAccum: - case BuiltinType::SatUAccum: - return Target.getUnsignedAccumIBits(); - case BuiltinType::ULongAccum: - case BuiltinType::SatULongAccum: - return Target.getUnsignedLongAccumIBits(); - case BuiltinType::ShortFract: - case BuiltinType::SatShortFract: - case BuiltinType::Fract: - case BuiltinType::SatFract: - case BuiltinType::LongFract: - case BuiltinType::SatLongFract: - case BuiltinType::UShortFract: - case BuiltinType::SatUShortFract: - case BuiltinType::UFract: - case BuiltinType::SatUFract: - case BuiltinType::ULongFract: - case BuiltinType::SatULongFract: - return 0; + default: + llvm_unreachable("Not a fixed point type!"); + case BuiltinType::ShortAccum: + case BuiltinType::SatShortAccum: + return Target.getShortAccumIBits(); + case BuiltinType::Accum: + case BuiltinType::SatAccum: + return Target.getAccumIBits(); + case BuiltinType::LongAccum: + case BuiltinType::SatLongAccum: + return Target.getLongAccumIBits(); + case BuiltinType::UShortAccum: + case BuiltinType::SatUShortAccum: + return Target.getUnsignedShortAccumIBits(); + case BuiltinType::UAccum: + case BuiltinType::SatUAccum: + return Target.getUnsignedAccumIBits(); + case BuiltinType::ULongAccum: + case BuiltinType::SatULongAccum: + return Target.getUnsignedLongAccumIBits(); + case BuiltinType::ShortFract: + case BuiltinType::SatShortFract: + case BuiltinType::Fract: + case BuiltinType::SatFract: + case BuiltinType::LongFract: + case BuiltinType::SatLongFract: + case BuiltinType::UShortFract: + case BuiltinType::SatUShortFract: + case BuiltinType::UFract: + case BuiltinType::SatUFract: + case BuiltinType::ULongFract: + case BuiltinType::SatULongFract: + return 0; } } @@ -11700,13 +11656,13 @@ } ParsedTargetAttr -ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const { +ASTContext::filterFunctionTargetAttrs(TargetAttr const *TD) const { assert(TD != nullptr); ParsedTargetAttr ParsedAttr = TD->parse(); ParsedAttr.Features.erase( llvm::remove_if(ParsedAttr.Features, - [&](const std::string &Feat) { + [&](std::string const &Feat) { return !Target->isValidFeatureName( StringRef{Feat}.substr(1)); }), @@ -11715,7 +11671,7 @@ } void ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap, - const FunctionDecl *FD) const { + FunctionDecl const *FD) const { if (FD) getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD)); else @@ -11729,8 +11685,8 @@ void ASTContext::getFunctionFeatureMap(llvm::StringMap &FeatureMap, GlobalDecl GD) const { StringRef TargetCPU = Target->getTargetOpts().CPU; - const FunctionDecl *FD = GD.getDecl()->getAsFunction(); - if (const auto *TD = FD->getAttr()) { + FunctionDecl const *FD = GD.getDecl()->getAsFunction(); + if (auto const *TD = FD->getAttr()) { ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); // Make a copy of the features as passed on the command line into the @@ -11750,7 +11706,7 @@ // the attribute. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, ParsedAttr.Features); - } else if (const auto *SD = FD->getAttr()) { + } else if (auto const *SD = FD->getAttr()) { llvm::SmallVector FeaturesTmp; Target->getCPUSpecificCPUDispatchFeatures( SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); @@ -11766,15 +11722,15 @@ return *OMPTraitInfoVector.back(); } -const StreamingDiagnostic &clang:: -operator<<(const StreamingDiagnostic &DB, - const ASTContext::SectionInfo &Section) { +StreamingDiagnostic const & +clang::operator<<(StreamingDiagnostic const &DB, + ASTContext::SectionInfo const &Section) { if (Section.Decl) return DB << Section.Decl; return DB << "a prior #pragma section"; } -bool ASTContext::mayExternalizeStaticVar(const Decl *D) const { +bool ASTContext::mayExternalizeStaticVar(Decl const *D) const { bool IsStaticVar = isa(D) && cast(D)->getStorageClass() == SC_Static; bool IsExplicitDeviceVar = (D->hasAttr() && @@ -11783,11 +11739,10 @@ !D->getAttr()->isImplicit()); // CUDA/HIP: static managed variables need to be externalized since it is // a declaration in IR, therefore cannot have internal linkage. - return IsStaticVar && - (D->hasAttr() || IsExplicitDeviceVar); + return IsStaticVar && (D->hasAttr() || IsExplicitDeviceVar); } -bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const { +bool ASTContext::shouldExternalizeStaticVar(Decl const *D) const { return mayExternalizeStaticVar(D) && (D->hasAttr() || CUDADeviceVarODRUsedByHost.count(cast(D))); @@ -11804,18 +11759,18 @@ // Get the closest named parent, so we can order the sycl naming decls somewhere // that mangling is meaningful. -static const DeclContext *GetNamedParent(const CXXRecordDecl *RD) { - const DeclContext *DC = RD->getDeclContext(); +static DeclContext const *GetNamedParent(CXXRecordDecl const *RD) { + DeclContext const *DC = RD->getDeclContext(); while (!isa(DC)) DC = DC->getParent(); return DC; } -void ASTContext::AddSYCLKernelNamingDecl(const CXXRecordDecl *RD) { +void ASTContext::AddSYCLKernelNamingDecl(CXXRecordDecl const *RD) { assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); RD = RD->getCanonicalDecl(); - const DeclContext *DC = GetNamedParent(RD); + DeclContext const *DC = GetNamedParent(RD); assert(RD->getLocation().isValid() && "Invalid location on kernel naming decl"); @@ -11823,13 +11778,13 @@ (void)SYCLKernelNamingTypes[DC].insert(RD); } -bool ASTContext::IsSYCLKernelNamingDecl(const NamedDecl *ND) const { +bool ASTContext::IsSYCLKernelNamingDecl(NamedDecl const *ND) const { assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); - const auto *RD = dyn_cast(ND); + auto const *RD = dyn_cast(ND); if (!RD) return false; RD = RD->getCanonicalDecl(); - const DeclContext *DC = GetNamedParent(RD); + DeclContext const *DC = GetNamedParent(RD); auto Itr = SYCLKernelNamingTypes.find(DC); @@ -11842,8 +11797,8 @@ // Filters the Decls list to those that share the lambda mangling with the // passed RD. void ASTContext::FilterSYCLKernelNamingDecls( - const CXXRecordDecl *RD, - llvm::SmallVectorImpl &Decls) { + CXXRecordDecl const *RD, + llvm::SmallVectorImpl &Decls) { if (!SYCLKernelFilterContext) SYCLKernelFilterContext.reset( @@ -11853,7 +11808,7 @@ llvm::raw_svector_ostream Out(LambdaSig); SYCLKernelFilterContext->mangleLambdaSig(RD, Out); - llvm::erase_if(Decls, [this, &LambdaSig](const CXXRecordDecl *LocalRD) { + llvm::erase_if(Decls, [this, &LambdaSig](CXXRecordDecl const *LocalRD) { llvm::SmallString<128> LocalLambdaSig; llvm::raw_svector_ostream LocalOut(LocalLambdaSig); SYCLKernelFilterContext->mangleLambdaSig(LocalRD, LocalOut); @@ -11861,24 +11816,24 @@ }); } -unsigned ASTContext::GetSYCLKernelNamingIndex(const NamedDecl *ND) { +unsigned ASTContext::GetSYCLKernelNamingIndex(NamedDecl const *ND) { assert(getLangOpts().isSYCL() && "Only valid for SYCL programs"); assert(IsSYCLKernelNamingDecl(ND) && "Lambda not involved in mangling asked for a naming index?"); - const CXXRecordDecl *RD = cast(ND)->getCanonicalDecl(); - const DeclContext *DC = GetNamedParent(RD); + CXXRecordDecl const *RD = cast(ND)->getCanonicalDecl(); + DeclContext const *DC = GetNamedParent(RD); auto Itr = SYCLKernelNamingTypes.find(DC); assert(Itr != SYCLKernelNamingTypes.end() && "Not a valid DeclContext?"); - const llvm::SmallPtrSet &Set = Itr->getSecond(); + llvm::SmallPtrSet const &Set = Itr->getSecond(); - llvm::SmallVector Decls{Set.begin(), Set.end()}; + llvm::SmallVector Decls{Set.begin(), Set.end()}; FilterSYCLKernelNamingDecls(RD, Decls); - llvm::sort(Decls, [](const CXXRecordDecl *LHS, const CXXRecordDecl *RHS) { + llvm::sort(Decls, [](CXXRecordDecl const *LHS, CXXRecordDecl const *RHS) { return LHS->getLambdaManglingNumber() < RHS->getLambdaManglingNumber(); }); Index: clang/lib/AST/ASTDiagnostic.cpp =================================================================== --- clang/lib/AST/ASTDiagnostic.cpp +++ clang/lib/AST/ASTDiagnostic.cpp @@ -30,41 +30,41 @@ QualifierCollector QC; while (true) { - const Type *Ty = QC.strip(QT); + Type const *Ty = QC.strip(QT); // Don't aka just because we saw an elaborated type... - if (const ElaboratedType *ET = dyn_cast(Ty)) { + if (ElaboratedType const *ET = dyn_cast(Ty)) { QT = ET->desugar(); continue; } // ... or a paren type ... - if (const ParenType *PT = dyn_cast(Ty)) { + if (ParenType const *PT = dyn_cast(Ty)) { QT = PT->desugar(); continue; } // ... or a macro defined type ... - if (const MacroQualifiedType *MDT = dyn_cast(Ty)) { + if (MacroQualifiedType const *MDT = dyn_cast(Ty)) { QT = MDT->desugar(); continue; } // ...or a substituted template type parameter ... - if (const SubstTemplateTypeParmType *ST = - dyn_cast(Ty)) { + if (SubstTemplateTypeParmType const *ST = + dyn_cast(Ty)) { QT = ST->desugar(); continue; } // ...or an attributed type... - if (const AttributedType *AT = dyn_cast(Ty)) { + if (AttributedType const *AT = dyn_cast(Ty)) { QT = AT->desugar(); continue; } // ...or an adjusted type... - if (const AdjustedType *AT = dyn_cast(Ty)) { + if (AdjustedType const *AT = dyn_cast(Ty)) { QT = AT->desugar(); continue; } // ... or an auto type. - if (const AutoType *AT = dyn_cast(Ty)) { + if (AutoType const *AT = dyn_cast(Ty)) { if (!AT->isSugared()) break; QT = AT->desugar(); @@ -73,7 +73,7 @@ // Desugar FunctionType if return type or any parameter type should be // desugared. Preserve nullability attribute on desugared types. - if (const FunctionType *FT = dyn_cast(Ty)) { + if (FunctionType const *FT = dyn_cast(Ty)) { bool DesugarReturn = false; QualType SugarRT = FT->getReturnType(); QualType RT = Desugar(Context, SugarRT, DesugarReturn); @@ -84,7 +84,7 @@ bool DesugarArgument = false; SmallVector Args; - const FunctionProtoType *FPT = dyn_cast(FT); + FunctionProtoType const *FPT = dyn_cast(FT); if (FPT) { for (QualType SugarPT : FPT->param_types()) { QualType PT = Desugar(Context, SugarPT, DesugarArgument); @@ -107,13 +107,13 @@ // Desugar template specializations if any template argument should be // desugared. - if (const TemplateSpecializationType *TST = + if (TemplateSpecializationType const *TST = dyn_cast(Ty)) { if (!TST->isTypeAlias()) { bool DesugarArgument = false; SmallVector Args; for (unsigned I = 0, N = TST->getNumArgs(); I != N; ++I) { - const TemplateArgument &Arg = TST->getArg(I); + TemplateArgument const &Arg = TST->getArg(I); if (Arg.getKind() == TemplateArgument::Type) Args.push_back(Desugar(Context, Arg.getAsType(), DesugarArgument)); else @@ -122,18 +122,18 @@ if (DesugarArgument) { ShouldAKA = true; - QT = Context.getTemplateSpecializationType( - TST->getTemplateName(), Args, QT); + QT = Context.getTemplateSpecializationType(TST->getTemplateName(), + Args, QT); } break; } } // Don't desugar magic Objective-C types. - if (QualType(Ty,0) == Context.getObjCIdType() || - QualType(Ty,0) == Context.getObjCClassType() || - QualType(Ty,0) == Context.getObjCSelType() || - QualType(Ty,0) == Context.getObjCProtoType()) + if (QualType(Ty, 0) == Context.getObjCIdType() || + QualType(Ty, 0) == Context.getObjCClassType() || + QualType(Ty, 0) == Context.getObjCSelType() || + QualType(Ty, 0) == Context.getObjCProtoType()) break; // Don't desugar va_list. @@ -146,15 +146,15 @@ bool IsSugar = false; switch (Ty->getTypeClass()) { #define ABSTRACT_TYPE(Class, Base) -#define TYPE(Class, Base) \ -case Type::Class: { \ -const Class##Type *CTy = cast(Ty); \ -if (CTy->isSugared()) { \ -IsSugar = true; \ -Underlying = CTy->desugar(); \ -} \ -break; \ -} +#define TYPE(Class, Base) \ + case Type::Class: { \ + const Class##Type *CTy = cast(Ty); \ + if (CTy->isSugared()) { \ + IsSugar = true; \ + Underlying = CTy->desugar(); \ + } \ + break; \ + } #include "clang/AST/TypeNodes.inc" } @@ -168,8 +168,8 @@ break; // Don't desugar through the primary typedef of an anonymous type. - if (const TagType *UTT = Underlying->getAs()) - if (const TypedefType *QTT = dyn_cast(QT)) + if (TagType const *UTT = Underlying->getAs()) + if (TypedefType const *QTT = dyn_cast(QT)) if (UTT->getDecl()->getTypedefNameForAnonDecl() == QTT->getDecl()) break; @@ -180,25 +180,25 @@ // If we have a pointer-like type, desugar the pointee as well. // FIXME: Handle other pointer-like types. - if (const PointerType *Ty = QT->getAs()) { - QT = Context.getPointerType(Desugar(Context, Ty->getPointeeType(), - ShouldAKA)); - } else if (const auto *Ty = QT->getAs()) { - QT = Context.getObjCObjectPointerType(Desugar(Context, Ty->getPointeeType(), - ShouldAKA)); - } else if (const LValueReferenceType *Ty = QT->getAs()) { - QT = Context.getLValueReferenceType(Desugar(Context, Ty->getPointeeType(), - ShouldAKA)); - } else if (const RValueReferenceType *Ty = QT->getAs()) { - QT = Context.getRValueReferenceType(Desugar(Context, Ty->getPointeeType(), - ShouldAKA)); - } else if (const auto *Ty = QT->getAs()) { + if (PointerType const *Ty = QT->getAs()) { + QT = Context.getPointerType( + Desugar(Context, Ty->getPointeeType(), ShouldAKA)); + } else if (auto const *Ty = QT->getAs()) { + QT = Context.getObjCObjectPointerType( + Desugar(Context, Ty->getPointeeType(), ShouldAKA)); + } else if (LValueReferenceType const *Ty = QT->getAs()) { + QT = Context.getLValueReferenceType( + Desugar(Context, Ty->getPointeeType(), ShouldAKA)); + } else if (RValueReferenceType const *Ty = QT->getAs()) { + QT = Context.getRValueReferenceType( + Desugar(Context, Ty->getPointeeType(), ShouldAKA)); + } else if (auto const *Ty = QT->getAs()) { if (Ty->getBaseType().getTypePtr() != Ty && !ShouldAKA) { QualType BaseType = Desugar(Context, Ty->getBaseType(), ShouldAKA); - QT = Context.getObjCObjectType(BaseType, Ty->getTypeArgsAsWritten(), - llvm::makeArrayRef(Ty->qual_begin(), - Ty->getNumProtocols()), - Ty->isKindOfTypeAsWritten()); + QT = Context.getObjCObjectType( + BaseType, Ty->getTypeArgsAsWritten(), + llvm::makeArrayRef(Ty->qual_begin(), Ty->getNumProtocols()), + Ty->isKindOfTypeAsWritten()); } } @@ -229,10 +229,10 @@ /// \param Ty the type to print /// \param QualTypeVals pointer values to QualTypes which are used in the /// diagnostic message -static std::string -ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty, - ArrayRef PrevArgs, - ArrayRef QualTypeVals) { +static std::string ConvertTypeToDiagnosticString( + ASTContext &Context, QualType Ty, + ArrayRef PrevArgs, + ArrayRef QualTypeVals) { // FIXME: Playing with std::string is really slow. bool ForceAKA = false; QualType CanTy = Ty.getCanonicalType(); @@ -241,27 +241,27 @@ for (unsigned I = 0, E = QualTypeVals.size(); I != E; ++I) { QualType CompareTy = - QualType::getFromOpaquePtr(reinterpret_cast(QualTypeVals[I])); + QualType::getFromOpaquePtr(reinterpret_cast(QualTypeVals[I])); if (CompareTy.isNull()) continue; if (CompareTy == Ty) - continue; // Same types + continue; // Same types QualType CompareCanTy = CompareTy.getCanonicalType(); if (CompareCanTy == CanTy) - continue; // Same canonical types + continue; // Same canonical types std::string CompareS = CompareTy.getAsString(Context.getPrintingPolicy()); bool ShouldAKA = false; QualType CompareDesugar = Desugar(Context, CompareTy, ShouldAKA); std::string CompareDesugarStr = CompareDesugar.getAsString(Context.getPrintingPolicy()); if (CompareS != S && CompareDesugarStr != S) - continue; // The type string is different than the comparison string - // and the desugared comparison string. + continue; // The type string is different than the comparison string + // and the desugared comparison string. std::string CompareCanS = CompareCanTy.getAsString(Context.getPrintingPolicy()); if (CompareCanS == CanS) - continue; // No new info from canonical type + continue; // No new info from canonical type ForceAKA = true; break; @@ -273,7 +273,7 @@ for (unsigned i = 0, e = PrevArgs.size(); i != e; ++i) { // TODO: Handle ak_declcontext case. if (PrevArgs[i].first == DiagnosticsEngine::ak_qualtype) { - void *Ptr = (void*)PrevArgs[i].second; + void *Ptr = (void *)PrevArgs[i].second; QualType PrevTy(QualType::getFromOpaquePtr(Ptr)); if (PrevTy == Ty) { Repeated = true; @@ -301,10 +301,10 @@ // Give some additional info on vector types. These are either not desugared // or displaying complex __attribute__ expressions so add details of the // type and element count. - if (const auto *VTy = Ty->getAs()) { + if (auto const *VTy = Ty->getAs()) { std::string DecoratedString; llvm::raw_string_ostream OS(DecoratedString); - const char *Values = VTy->getNumElements() > 1 ? "values" : "value"; + char const *Values = VTy->getNumElements() > 1 ? "values" : "value"; OS << "'" << S << "' (vector of " << VTy->getNumElements() << " '" << VTy->getElementType().getAsString(Context.getPrintingPolicy()) << "' " << Values << ")"; @@ -322,165 +322,161 @@ bool ShowColors, raw_ostream &OS); void clang::FormatASTNodeDiagnosticArgument( - DiagnosticsEngine::ArgumentKind Kind, - intptr_t Val, - StringRef Modifier, - StringRef Argument, - ArrayRef PrevArgs, - SmallVectorImpl &Output, - void *Cookie, + DiagnosticsEngine::ArgumentKind Kind, intptr_t Val, StringRef Modifier, + StringRef Argument, ArrayRef PrevArgs, + SmallVectorImpl &Output, void *Cookie, ArrayRef QualTypeVals) { - ASTContext &Context = *static_cast(Cookie); + ASTContext &Context = *static_cast(Cookie); size_t OldEnd = Output.size(); llvm::raw_svector_ostream OS(Output); bool NeedQuotes = true; switch (Kind) { - default: llvm_unreachable("unknown ArgumentKind"); - case DiagnosticsEngine::ak_addrspace: { - assert(Modifier.empty() && Argument.empty() && - "Invalid modifier for Qualfiers argument"); - - auto S = Qualifiers::getAddrSpaceAsString(static_cast(Val)); - if (S.empty()) { - OS << (Context.getLangOpts().OpenCL ? "default" : "generic"); - OS << " address space"; - } else { - OS << "address space"; - OS << " '" << S << "'"; - } + default: + llvm_unreachable("unknown ArgumentKind"); + case DiagnosticsEngine::ak_addrspace: { + assert(Modifier.empty() && Argument.empty() && + "Invalid modifier for Qualfiers argument"); + + auto S = Qualifiers::getAddrSpaceAsString(static_cast(Val)); + if (S.empty()) { + OS << (Context.getLangOpts().OpenCL ? "default" : "generic"); + OS << " address space"; + } else { + OS << "address space"; + OS << " '" << S << "'"; + } + NeedQuotes = false; + break; + } + case DiagnosticsEngine::ak_qual: { + assert(Modifier.empty() && Argument.empty() && + "Invalid modifier for Qualfiers argument"); + + Qualifiers Q(Qualifiers::fromOpaqueValue(Val)); + auto S = Q.getAsString(); + if (S.empty()) { + OS << "unqualified"; NeedQuotes = false; - break; + } else { + OS << S; } - case DiagnosticsEngine::ak_qual: { - assert(Modifier.empty() && Argument.empty() && - "Invalid modifier for Qualfiers argument"); - - Qualifiers Q(Qualifiers::fromOpaqueValue(Val)); - auto S = Q.getAsString(); - if (S.empty()) { - OS << "unqualified"; - NeedQuotes = false; - } else { - OS << S; - } + break; + } + case DiagnosticsEngine::ak_qualtype_pair: { + TemplateDiffTypes &TDT = *reinterpret_cast(Val); + QualType FromType = + QualType::getFromOpaquePtr(reinterpret_cast(TDT.FromType)); + QualType ToType = + QualType::getFromOpaquePtr(reinterpret_cast(TDT.ToType)); + + if (FormatTemplateTypeDiff(Context, FromType, ToType, TDT.PrintTree, + TDT.PrintFromType, TDT.ElideType, TDT.ShowColors, + OS)) { + NeedQuotes = !TDT.PrintTree; + TDT.TemplateDiffUsed = true; break; } - case DiagnosticsEngine::ak_qualtype_pair: { - TemplateDiffTypes &TDT = *reinterpret_cast(Val); - QualType FromType = - QualType::getFromOpaquePtr(reinterpret_cast(TDT.FromType)); - QualType ToType = - QualType::getFromOpaquePtr(reinterpret_cast(TDT.ToType)); - - if (FormatTemplateTypeDiff(Context, FromType, ToType, TDT.PrintTree, - TDT.PrintFromType, TDT.ElideType, - TDT.ShowColors, OS)) { - NeedQuotes = !TDT.PrintTree; - TDT.TemplateDiffUsed = true; - break; - } - // Don't fall-back during tree printing. The caller will handle - // this case. - if (TDT.PrintTree) - return; + // Don't fall-back during tree printing. The caller will handle + // this case. + if (TDT.PrintTree) + return; - // Attempting to do a template diff on non-templates. Set the variables - // and continue with regular type printing of the appropriate type. - Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType; - Modifier = StringRef(); - Argument = StringRef(); - // Fall through - LLVM_FALLTHROUGH; - } - case DiagnosticsEngine::ak_qualtype: { + // Attempting to do a template diff on non-templates. Set the variables + // and continue with regular type printing of the appropriate type. + Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType; + Modifier = StringRef(); + Argument = StringRef(); + // Fall through + LLVM_FALLTHROUGH; + } + case DiagnosticsEngine::ak_qualtype: { + assert(Modifier.empty() && Argument.empty() && + "Invalid modifier for QualType argument"); + + QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast(Val))); + OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, QualTypeVals); + NeedQuotes = false; + break; + } + case DiagnosticsEngine::ak_declarationname: { + if (Modifier == "objcclass" && Argument.empty()) + OS << '+'; + else if (Modifier == "objcinstance" && Argument.empty()) + OS << '-'; + else assert(Modifier.empty() && Argument.empty() && - "Invalid modifier for QualType argument"); + "Invalid modifier for DeclarationName argument"); - QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast(Val))); - OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, QualTypeVals); - NeedQuotes = false; - break; + OS << DeclarationName::getFromOpaqueInteger(Val); + break; + } + case DiagnosticsEngine::ak_nameddecl: { + bool Qualified; + if (Modifier == "q" && Argument.empty()) + Qualified = true; + else { + assert(Modifier.empty() && Argument.empty() && + "Invalid modifier for NamedDecl* argument"); + Qualified = false; } - case DiagnosticsEngine::ak_declarationname: { - if (Modifier == "objcclass" && Argument.empty()) - OS << '+'; - else if (Modifier == "objcinstance" && Argument.empty()) - OS << '-'; + NamedDecl const *ND = reinterpret_cast(Val); + ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), Qualified); + break; + } + case DiagnosticsEngine::ak_nestednamespec: { + NestedNameSpecifier *NNS = reinterpret_cast(Val); + NNS->print(OS, Context.getPrintingPolicy()); + NeedQuotes = false; + break; + } + case DiagnosticsEngine::ak_declcontext: { + DeclContext *DC = reinterpret_cast(Val); + assert(DC && "Should never have a null declaration context"); + NeedQuotes = false; + + // FIXME: Get the strings for DeclContext from some localized place + if (DC->isTranslationUnit()) { + if (Context.getLangOpts().CPlusPlus) + OS << "the global namespace"; else - assert(Modifier.empty() && Argument.empty() && - "Invalid modifier for DeclarationName argument"); - - OS << DeclarationName::getFromOpaqueInteger(Val); - break; - } - case DiagnosticsEngine::ak_nameddecl: { - bool Qualified; - if (Modifier == "q" && Argument.empty()) - Qualified = true; - else { - assert(Modifier.empty() && Argument.empty() && - "Invalid modifier for NamedDecl* argument"); - Qualified = false; - } - const NamedDecl *ND = reinterpret_cast(Val); - ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), Qualified); - break; - } - case DiagnosticsEngine::ak_nestednamespec: { - NestedNameSpecifier *NNS = reinterpret_cast(Val); - NNS->print(OS, Context.getPrintingPolicy()); - NeedQuotes = false; - break; - } - case DiagnosticsEngine::ak_declcontext: { - DeclContext *DC = reinterpret_cast (Val); - assert(DC && "Should never have a null declaration context"); - NeedQuotes = false; - - // FIXME: Get the strings for DeclContext from some localized place - if (DC->isTranslationUnit()) { - if (Context.getLangOpts().CPlusPlus) - OS << "the global namespace"; - else - OS << "the global scope"; - } else if (DC->isClosure()) { - OS << "block literal"; - } else if (isLambdaCallOperator(DC)) { - OS << "lambda expression"; - } else if (TypeDecl *Type = dyn_cast(DC)) { - OS << ConvertTypeToDiagnosticString(Context, - Context.getTypeDeclType(Type), - PrevArgs, QualTypeVals); - } else { - assert(isa(DC) && "Expected a NamedDecl"); - NamedDecl *ND = cast(DC); - if (isa(ND)) - OS << "namespace "; - else if (isa(ND)) - OS << "method "; - else if (isa(ND)) - OS << "function "; - - OS << '\''; - ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true); - OS << '\''; - } - break; - } - case DiagnosticsEngine::ak_attr: { - const Attr *At = reinterpret_cast(Val); - assert(At && "Received null Attr object!"); - OS << '\'' << At->getSpelling() << '\''; - NeedQuotes = false; - break; + OS << "the global scope"; + } else if (DC->isClosure()) { + OS << "block literal"; + } else if (isLambdaCallOperator(DC)) { + OS << "lambda expression"; + } else if (TypeDecl *Type = dyn_cast(DC)) { + OS << ConvertTypeToDiagnosticString( + Context, Context.getTypeDeclType(Type), PrevArgs, QualTypeVals); + } else { + assert(isa(DC) && "Expected a NamedDecl"); + NamedDecl *ND = cast(DC); + if (isa(ND)) + OS << "namespace "; + else if (isa(ND)) + OS << "method "; + else if (isa(ND)) + OS << "function "; + + OS << '\''; + ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true); + OS << '\''; } + break; + } + case DiagnosticsEngine::ak_attr: { + Attr const *At = reinterpret_cast(Val); + assert(At && "Received null Attr object!"); + OS << '\'' << At->getSpelling() << '\''; + NeedQuotes = false; + break; + } } if (NeedQuotes) { - Output.insert(Output.begin()+OldEnd, '\''); + Output.insert(Output.begin() + OldEnd, '\''); Output.push_back('\''); } } @@ -648,7 +644,7 @@ SetDefault(FromDefault, ToDefault); } - void SetIntegerDiff(const llvm::APSInt &FromInt, const llvm::APSInt &ToInt, + void SetIntegerDiff(llvm::APSInt const &FromInt, llvm::APSInt const &ToInt, bool IsValidFromInt, bool IsValidToInt, QualType FromIntType, QualType ToIntType, Expr *FromExpr, Expr *ToExpr, bool FromDefault, @@ -685,7 +681,7 @@ void SetFromDeclarationAndToIntegerDiff( ValueDecl *FromValueDecl, bool FromAddressOf, bool FromNullPtr, - Expr *FromExpr, const llvm::APSInt &ToInt, bool IsValidToInt, + Expr *FromExpr, llvm::APSInt const &ToInt, bool IsValidToInt, QualType ToIntType, Expr *ToExpr, bool FromDefault, bool ToDefault) { assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty."); FlatTree[CurrentNode].Kind = FromDeclarationAndToInteger; @@ -701,7 +697,7 @@ } void SetFromIntegerAndToDeclarationDiff( - const llvm::APSInt &FromInt, bool IsValidFromInt, QualType FromIntType, + llvm::APSInt const &FromInt, bool IsValidFromInt, QualType FromIntType, Expr *FromExpr, ValueDecl *ToValueDecl, bool ToAddressOf, bool ToNullPtr, Expr *ToExpr, bool FromDefault, bool ToDefault) { assert(FlatTree[CurrentNode].Kind == Invalid && "Node is not empty."); @@ -719,20 +715,17 @@ /// SetDefault - Sets FromDefault and ToDefault flags of the current node. void SetDefault(bool FromDefault, bool ToDefault) { - assert((!FromDefault || !ToDefault) && "Both arguments cannot be default."); + assert((!FromDefault || !ToDefault) && + "Both arguments cannot be default."); FlatTree[CurrentNode].FromArgInfo.IsDefault = FromDefault; FlatTree[CurrentNode].ToArgInfo.IsDefault = ToDefault; } /// SetSame - Sets the same flag of the current node. - void SetSame(bool Same) { - FlatTree[CurrentNode].Same = Same; - } + void SetSame(bool Same) { FlatTree[CurrentNode].Same = Same; } /// SetKind - Sets the current node's type. - void SetKind(DiffKind Kind) { - FlatTree[CurrentNode].Kind = Kind; - } + void SetKind(DiffKind Kind) { FlatTree[CurrentNode].Kind = Kind; } /// Up - Changes the node to the parent of the current node. void Up() { @@ -773,9 +766,7 @@ } /// Parent - Move the current read node to its parent. - void Parent() { - ReadNode = FlatTree[ReadNode].ParentNode; - } + void Parent() { ReadNode = FlatTree[ReadNode].ParentNode; } void GetTemplateDiff(TemplateDecl *&FromTD, TemplateDecl *&ToTD, Qualifiers &FromQual, Qualifiers &ToQual) { @@ -867,29 +858,19 @@ } /// FromDefault - Return true if the from argument is the default. - bool FromDefault() { - return FlatTree[ReadNode].FromArgInfo.IsDefault; - } + bool FromDefault() { return FlatTree[ReadNode].FromArgInfo.IsDefault; } /// ToDefault - Return true if the to argument is the default. - bool ToDefault() { - return FlatTree[ReadNode].ToArgInfo.IsDefault; - } + bool ToDefault() { return FlatTree[ReadNode].ToArgInfo.IsDefault; } /// NodeIsSame - Returns true the arguments are the same. - bool NodeIsSame() { - return FlatTree[ReadNode].Same; - } + bool NodeIsSame() { return FlatTree[ReadNode].Same; } /// HasChildrend - Returns true if the node has children. - bool HasChildren() { - return FlatTree[ReadNode].ChildNode != 0; - } + bool HasChildren() { return FlatTree[ReadNode].ChildNode != 0; } /// MoveToChild - Moves from the current node to its child. - void MoveToChild() { - ReadNode = FlatTree[ReadNode].ChildNode; - } + void MoveToChild() { ReadNode = FlatTree[ReadNode].ChildNode; } /// AdvanceSibling - If there is a next sibling, advance to it and return /// true. Otherwise, return false. @@ -902,19 +883,13 @@ } /// HasNextSibling - Return true if the node has a next sibling. - bool HasNextSibling() { - return FlatTree[ReadNode].NextNode != 0; - } + bool HasNextSibling() { return FlatTree[ReadNode].NextNode != 0; } /// Empty - Returns true if the tree has no information. - bool Empty() { - return GetKind() == Invalid; - } + bool Empty() { return GetKind() == Invalid; } /// GetKind - Returns the current node's type. - DiffKind GetKind() { - return FlatTree[ReadNode].Kind; - } + DiffKind GetKind() { return FlatTree[ReadNode].Kind; } }; DiffTree Tree; @@ -924,8 +899,8 @@ /// The deseguared TemplateArgument should provide the canonical argument /// for comparisons. class TSTiterator { - typedef const TemplateArgument& reference; - typedef const TemplateArgument* pointer; + typedef TemplateArgument const &reference; + typedef TemplateArgument const *pointer; /// InternalIterator - an iterator that is used to enter a /// TemplateSpecializationType and read TemplateArguments inside template @@ -933,7 +908,7 @@ struct InternalIterator { /// TST - the template specialization whose arguments this iterator /// traverse over. - const TemplateSpecializationType *TST; + TemplateSpecializationType const *TST; /// Index - the index of the template argument in TST. unsigned Index; @@ -947,22 +922,26 @@ /// InternalIterator - Constructs an iterator and sets it to the first /// template argument. - InternalIterator(const TemplateSpecializationType *TST) + InternalIterator(TemplateSpecializationType const *TST) : TST(TST), Index(0), CurrentTA(nullptr), EndTA(nullptr) { - if (!TST) return; + if (!TST) + return; - if (isEnd()) return; + if (isEnd()) + return; // Set to first template argument. If not a parameter pack, done. TemplateArgument TA = TST->getArg(0); - if (TA.getKind() != TemplateArgument::Pack) return; + if (TA.getKind() != TemplateArgument::Pack) + return; // Start looking into the parameter pack. CurrentTA = TA.pack_begin(); EndTA = TA.pack_end(); // Found a valid template argument. - if (CurrentTA != EndTA) return; + if (CurrentTA != EndTA) + return; // Parameter pack is empty, use the increment to get to a valid // template argument. @@ -1035,7 +1014,7 @@ InternalIterator DesugaredIterator; public: - TSTiterator(ASTContext &Context, const TemplateSpecializationType *TST) + TSTiterator(ASTContext &Context, TemplateSpecializationType const *TST) : SugaredIterator(TST), DesugaredIterator( (TST->isSugared() && !TST->isTypeAlias()) @@ -1051,19 +1030,13 @@ } /// operator* - Returns the appropriate TemplateArgument. - reference operator*() const { - return *SugaredIterator; - } + reference operator*() const { return *SugaredIterator; } /// operator-> - Allow access to the underlying TemplateArgument. - pointer operator->() const { - return &operator*(); - } + pointer operator->() const { return &operator*(); } /// isEnd - Returns true if no more TemplateArguments are available. - bool isEnd() const { - return SugaredIterator.isEnd(); - } + bool isEnd() const { return SugaredIterator.isEnd(); } /// hasDesugaredTA - Returns true if there is another TemplateArgument /// available. @@ -1082,30 +1055,30 @@ // These functions build up the template diff tree, including functions to // retrieve and compare template arguments. - static const TemplateSpecializationType *GetTemplateSpecializationType( - ASTContext &Context, QualType Ty) { - if (const TemplateSpecializationType *TST = + static TemplateSpecializationType const * + GetTemplateSpecializationType(ASTContext &Context, QualType Ty) { + if (TemplateSpecializationType const *TST = Ty->getAs()) return TST; - if (const auto* SubstType = Ty->getAs()) + if (auto const *SubstType = Ty->getAs()) Ty = SubstType->getReplacementType(); - const RecordType *RT = Ty->getAs(); + RecordType const *RT = Ty->getAs(); if (!RT) return nullptr; - const ClassTemplateSpecializationDecl *CTSD = + ClassTemplateSpecializationDecl const *CTSD = dyn_cast(RT->getDecl()); if (!CTSD) return nullptr; Ty = Context.getTemplateSpecializationType( - TemplateName(CTSD->getSpecializedTemplate()), - CTSD->getTemplateArgs().asArray(), - Ty.getLocalUnqualifiedType().getCanonicalType()); + TemplateName(CTSD->getSpecializedTemplate()), + CTSD->getTemplateArgs().asArray(), + Ty.getLocalUnqualifiedType().getCanonicalType()); return Ty->getAs(); } @@ -1113,8 +1086,8 @@ /// Returns true if the DiffType is Type and false for Template. static bool OnlyPerformTypeDiff(ASTContext &Context, QualType FromType, QualType ToType, - const TemplateSpecializationType *&FromArgTST, - const TemplateSpecializationType *&ToArgTST) { + TemplateSpecializationType const *&FromArgTST, + TemplateSpecializationType const *&ToArgTST) { if (FromType.isNull() || ToType.isNull()) return true; @@ -1134,15 +1107,15 @@ } /// DiffTypes - Fills a DiffNode with information about a type difference. - void DiffTypes(const TSTiterator &FromIter, const TSTiterator &ToIter) { + void DiffTypes(TSTiterator const &FromIter, TSTiterator const &ToIter) { QualType FromType = GetType(FromIter); QualType ToType = GetType(ToIter); bool FromDefault = FromIter.isEnd() && !FromType.isNull(); bool ToDefault = ToIter.isEnd() && !ToType.isNull(); - const TemplateSpecializationType *FromArgTST = nullptr; - const TemplateSpecializationType *ToArgTST = nullptr; + TemplateSpecializationType const *FromArgTST = nullptr; + TemplateSpecializationType const *ToArgTST = nullptr; if (OnlyPerformTypeDiff(Context, FromType, ToType, FromArgTST, ToArgTST)) { Tree.SetTypeDiff(FromType, ToType, FromDefault, ToDefault); Tree.SetSame(!FromType.isNull() && !ToType.isNull() && @@ -1163,8 +1136,8 @@ /// DiffTemplateTemplates - Fills a DiffNode with information about a /// template template difference. - void DiffTemplateTemplates(const TSTiterator &FromIter, - const TSTiterator &ToIter) { + void DiffTemplateTemplates(TSTiterator const &FromIter, + TSTiterator const &ToIter) { TemplateDecl *FromDecl = GetTemplateDecl(FromIter); TemplateDecl *ToDecl = GetTemplateDecl(ToIter); Tree.SetTemplateTemplateDiff(FromDecl, ToDecl, FromIter.isEnd() && FromDecl, @@ -1175,7 +1148,7 @@ /// InitializeNonTypeDiffVariables - Helper function for DiffNonTypes static void InitializeNonTypeDiffVariables(ASTContext &Context, - const TSTiterator &Iter, + TSTiterator const &Iter, NonTypeTemplateParmDecl *Default, llvm::APSInt &Value, bool &HasInt, QualType &IntType, bool &IsNullPtr, @@ -1183,46 +1156,16 @@ bool &NeedAddressOf) { if (!Iter.isEnd()) { switch (Iter->getKind()) { - default: - llvm_unreachable("unknown ArgumentKind"); - case TemplateArgument::Integral: - Value = Iter->getAsIntegral(); - HasInt = true; - IntType = Iter->getIntegralType(); - return; - case TemplateArgument::Declaration: { - VD = Iter->getAsDecl(); - QualType ArgType = Iter->getParamTypeForDecl(); - QualType VDType = VD->getType(); - if (ArgType->isPointerType() && - Context.hasSameType(ArgType->getPointeeType(), VDType)) - NeedAddressOf = true; - return; - } - case TemplateArgument::NullPtr: - IsNullPtr = true; - return; - case TemplateArgument::Expression: - E = Iter->getAsExpr(); - } - } else if (!Default->isParameterPack()) { - E = Default->getDefaultArgument(); - } - - if (!Iter.hasDesugaredTA()) return; - - const TemplateArgument& TA = Iter.getDesugaredTA(); - switch (TA.getKind()) { default: llvm_unreachable("unknown ArgumentKind"); case TemplateArgument::Integral: - Value = TA.getAsIntegral(); + Value = Iter->getAsIntegral(); HasInt = true; - IntType = TA.getIntegralType(); + IntType = Iter->getIntegralType(); return; case TemplateArgument::Declaration: { - VD = TA.getAsDecl(); - QualType ArgType = TA.getParamTypeForDecl(); + VD = Iter->getAsDecl(); + QualType ArgType = Iter->getParamTypeForDecl(); QualType VDType = VD->getType(); if (ArgType->isPointerType() && Context.hasSameType(ArgType->getPointeeType(), VDType)) @@ -1233,18 +1176,49 @@ IsNullPtr = true; return; case TemplateArgument::Expression: - // TODO: Sometimes, the desugared template argument Expr differs from - // the sugared template argument Expr. It may be useful in the future - // but for now, it is just discarded. - if (!E) - E = TA.getAsExpr(); - return; + E = Iter->getAsExpr(); + } + } else if (!Default->isParameterPack()) { + E = Default->getDefaultArgument(); + } + + if (!Iter.hasDesugaredTA()) + return; + + TemplateArgument const &TA = Iter.getDesugaredTA(); + switch (TA.getKind()) { + default: + llvm_unreachable("unknown ArgumentKind"); + case TemplateArgument::Integral: + Value = TA.getAsIntegral(); + HasInt = true; + IntType = TA.getIntegralType(); + return; + case TemplateArgument::Declaration: { + VD = TA.getAsDecl(); + QualType ArgType = TA.getParamTypeForDecl(); + QualType VDType = VD->getType(); + if (ArgType->isPointerType() && + Context.hasSameType(ArgType->getPointeeType(), VDType)) + NeedAddressOf = true; + return; + } + case TemplateArgument::NullPtr: + IsNullPtr = true; + return; + case TemplateArgument::Expression: + // TODO: Sometimes, the desugared template argument Expr differs from + // the sugared template argument Expr. It may be useful in the future + // but for now, it is just discarded. + if (!E) + E = TA.getAsExpr(); + return; } } /// DiffNonTypes - Handles any template parameters not handled by DiffTypes /// of DiffTemplatesTemplates, such as integer and declaration parameters. - void DiffNonTypes(const TSTiterator &FromIter, const TSTiterator &ToIter, + void DiffNonTypes(TSTiterator const &FromIter, TSTiterator const &ToIter, NonTypeTemplateParmDecl *FromDefaultNonTypeDecl, NonTypeTemplateParmDecl *ToDefaultNonTypeDecl) { Expr *FromExpr = nullptr, *ToExpr = nullptr; @@ -1262,8 +1236,8 @@ bool FromDefault = FromIter.isEnd() && (FromExpr || FromValueDecl || HasFromInt || FromNullPtr); - bool ToDefault = ToIter.isEnd() && - (ToExpr || ToValueDecl || HasToInt || ToNullPtr); + bool ToDefault = + ToIter.isEnd() && (ToExpr || ToValueDecl || HasToInt || ToNullPtr); bool FromDeclaration = FromValueDecl || FromNullPtr; bool ToDeclaration = ToValueDecl || ToNullPtr; @@ -1274,7 +1248,6 @@ HasToInt, ToIntType, ToExpr, FromDefault, ToDefault); Tree.SetSame(false); return; - } if (HasFromInt && ToDeclaration) { @@ -1315,8 +1288,8 @@ /// DiffTemplate - recursively visits template arguments and stores the /// argument info into a tree. - void DiffTemplate(const TemplateSpecializationType *FromTST, - const TemplateSpecializationType *ToTST) { + void DiffTemplate(TemplateSpecializationType const *FromTST, + TemplateSpecializationType const *ToTST) { // Begin descent into diffing template tree. TemplateParameterList *ParamsFrom = FromTST->getTemplateName().getAsTemplateDecl()->getTemplateParameters(); @@ -1361,8 +1334,8 @@ /// makeTemplateList - Dump every template alias into the vector. static void makeTemplateList( - SmallVectorImpl &TemplateList, - const TemplateSpecializationType *TST) { + SmallVectorImpl &TemplateList, + TemplateSpecializationType const *TST) { while (TST) { TemplateList.push_back(TST); if (!TST->isTypeAlias()) @@ -1373,8 +1346,8 @@ /// hasSameBaseTemplate - Returns true when the base templates are the same, /// even if the template arguments are not. - static bool hasSameBaseTemplate(const TemplateSpecializationType *FromTST, - const TemplateSpecializationType *ToTST) { + static bool hasSameBaseTemplate(TemplateSpecializationType const *FromTST, + TemplateSpecializationType const *ToTST) { return FromTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl() == ToTST->getTemplateName().getAsTemplateDecl()->getCanonicalDecl(); } @@ -1383,22 +1356,23 @@ /// same template declaration. If they come from different template aliases, /// do a parallel ascension search to determine the highest template alias in /// common and set the arguments to them. - static bool hasSameTemplate(const TemplateSpecializationType *&FromTST, - const TemplateSpecializationType *&ToTST) { + static bool hasSameTemplate(TemplateSpecializationType const *&FromTST, + TemplateSpecializationType const *&ToTST) { // Check the top templates if they are the same. if (hasSameBaseTemplate(FromTST, ToTST)) return true; // Create vectors of template aliases. - SmallVector FromTemplateList, - ToTemplateList; + SmallVector FromTemplateList, + ToTemplateList; makeTemplateList(FromTemplateList, FromTST); makeTemplateList(ToTemplateList, ToTST); - SmallVectorImpl::reverse_iterator - FromIter = FromTemplateList.rbegin(), FromEnd = FromTemplateList.rend(), - ToIter = ToTemplateList.rbegin(), ToEnd = ToTemplateList.rend(); + SmallVectorImpl::reverse_iterator + FromIter = FromTemplateList.rbegin(), + FromEnd = FromTemplateList.rend(), ToIter = ToTemplateList.rbegin(), + ToEnd = ToTemplateList.rend(); // Check if the lowest template types are the same. If not, return. if (!hasSameBaseTemplate(*FromIter, *ToIter)) @@ -1420,7 +1394,7 @@ /// GetType - Retrieves the template type arguments, including default /// arguments. - static QualType GetType(const TSTiterator &Iter) { + static QualType GetType(TSTiterator const &Iter) { if (!Iter.isEnd()) return Iter->getAsType(); if (Iter.hasDesugaredTA()) @@ -1430,7 +1404,7 @@ /// GetTemplateDecl - Retrieves the template template arguments, including /// default arguments. - static TemplateDecl *GetTemplateDecl(const TSTiterator &Iter) { + static TemplateDecl *GetTemplateDecl(TSTiterator const &Iter) { if (!Iter.isEnd()) return Iter->getAsTemplate().getAsTemplateDecl(); if (Iter.hasDesugaredTA()) @@ -1469,137 +1443,137 @@ // Handle cases where the difference is not templates with different // arguments. switch (Tree.GetKind()) { - case DiffTree::Invalid: - llvm_unreachable("Template diffing failed with bad DiffNode"); - case DiffTree::Type: { - QualType FromType, ToType; - Tree.GetTypeDiff(FromType, ToType); - PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(), - Tree.NodeIsSame()); - return; - } - case DiffTree::Expression: { - Expr *FromExpr, *ToExpr; - Tree.GetExpressionDiff(FromExpr, ToExpr); - PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(), - Tree.NodeIsSame()); - return; - } - case DiffTree::TemplateTemplate: { - TemplateDecl *FromTD, *ToTD; - Tree.GetTemplateTemplateDiff(FromTD, ToTD); - PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(), - Tree.ToDefault(), Tree.NodeIsSame()); - return; - } - case DiffTree::Integer: { - llvm::APSInt FromInt, ToInt; - Expr *FromExpr, *ToExpr; - bool IsValidFromInt, IsValidToInt; - QualType FromIntType, ToIntType; - Tree.GetIntegerDiff(FromInt, ToInt, IsValidFromInt, IsValidToInt, - FromIntType, ToIntType, FromExpr, ToExpr); - PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt, FromIntType, - ToIntType, FromExpr, ToExpr, Tree.FromDefault(), - Tree.ToDefault(), Tree.NodeIsSame()); - return; - } - case DiffTree::Declaration: { - ValueDecl *FromValueDecl, *ToValueDecl; - bool FromAddressOf, ToAddressOf; - bool FromNullPtr, ToNullPtr; - Expr *FromExpr, *ToExpr; - Tree.GetDeclarationDiff(FromValueDecl, ToValueDecl, FromAddressOf, - ToAddressOf, FromNullPtr, ToNullPtr, FromExpr, - ToExpr); - PrintValueDecl(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf, - FromNullPtr, ToNullPtr, FromExpr, ToExpr, - Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame()); - return; - } - case DiffTree::FromDeclarationAndToInteger: { - ValueDecl *FromValueDecl; - bool FromAddressOf; - bool FromNullPtr; - Expr *FromExpr; - llvm::APSInt ToInt; - bool IsValidToInt; - QualType ToIntType; - Expr *ToExpr; - Tree.GetFromDeclarationAndToIntegerDiff( - FromValueDecl, FromAddressOf, FromNullPtr, FromExpr, ToInt, - IsValidToInt, ToIntType, ToExpr); - assert((FromValueDecl || FromNullPtr) && IsValidToInt); - PrintValueDeclAndInteger(FromValueDecl, FromAddressOf, FromNullPtr, - FromExpr, Tree.FromDefault(), ToInt, ToIntType, - ToExpr, Tree.ToDefault()); - return; - } - case DiffTree::FromIntegerAndToDeclaration: { - llvm::APSInt FromInt; - bool IsValidFromInt; - QualType FromIntType; - Expr *FromExpr; - ValueDecl *ToValueDecl; - bool ToAddressOf; - bool ToNullPtr; - Expr *ToExpr; - Tree.GetFromIntegerAndToDeclarationDiff( - FromInt, IsValidFromInt, FromIntType, FromExpr, ToValueDecl, - ToAddressOf, ToNullPtr, ToExpr); - assert(IsValidFromInt && (ToValueDecl || ToNullPtr)); - PrintIntegerAndValueDecl(FromInt, FromIntType, FromExpr, - Tree.FromDefault(), ToValueDecl, ToAddressOf, - ToNullPtr, ToExpr, Tree.ToDefault()); + case DiffTree::Invalid: + llvm_unreachable("Template diffing failed with bad DiffNode"); + case DiffTree::Type: { + QualType FromType, ToType; + Tree.GetTypeDiff(FromType, ToType); + PrintTypeNames(FromType, ToType, Tree.FromDefault(), Tree.ToDefault(), + Tree.NodeIsSame()); + return; + } + case DiffTree::Expression: { + Expr *FromExpr, *ToExpr; + Tree.GetExpressionDiff(FromExpr, ToExpr); + PrintExpr(FromExpr, ToExpr, Tree.FromDefault(), Tree.ToDefault(), + Tree.NodeIsSame()); + return; + } + case DiffTree::TemplateTemplate: { + TemplateDecl *FromTD, *ToTD; + Tree.GetTemplateTemplateDiff(FromTD, ToTD); + PrintTemplateTemplate(FromTD, ToTD, Tree.FromDefault(), Tree.ToDefault(), + Tree.NodeIsSame()); + return; + } + case DiffTree::Integer: { + llvm::APSInt FromInt, ToInt; + Expr *FromExpr, *ToExpr; + bool IsValidFromInt, IsValidToInt; + QualType FromIntType, ToIntType; + Tree.GetIntegerDiff(FromInt, ToInt, IsValidFromInt, IsValidToInt, + FromIntType, ToIntType, FromExpr, ToExpr); + PrintAPSInt(FromInt, ToInt, IsValidFromInt, IsValidToInt, FromIntType, + ToIntType, FromExpr, ToExpr, Tree.FromDefault(), + Tree.ToDefault(), Tree.NodeIsSame()); + return; + } + case DiffTree::Declaration: { + ValueDecl *FromValueDecl, *ToValueDecl; + bool FromAddressOf, ToAddressOf; + bool FromNullPtr, ToNullPtr; + Expr *FromExpr, *ToExpr; + Tree.GetDeclarationDiff(FromValueDecl, ToValueDecl, FromAddressOf, + ToAddressOf, FromNullPtr, ToNullPtr, FromExpr, + ToExpr); + PrintValueDecl(FromValueDecl, ToValueDecl, FromAddressOf, ToAddressOf, + FromNullPtr, ToNullPtr, FromExpr, ToExpr, + Tree.FromDefault(), Tree.ToDefault(), Tree.NodeIsSame()); + return; + } + case DiffTree::FromDeclarationAndToInteger: { + ValueDecl *FromValueDecl; + bool FromAddressOf; + bool FromNullPtr; + Expr *FromExpr; + llvm::APSInt ToInt; + bool IsValidToInt; + QualType ToIntType; + Expr *ToExpr; + Tree.GetFromDeclarationAndToIntegerDiff(FromValueDecl, FromAddressOf, + FromNullPtr, FromExpr, ToInt, + IsValidToInt, ToIntType, ToExpr); + assert((FromValueDecl || FromNullPtr) && IsValidToInt); + PrintValueDeclAndInteger(FromValueDecl, FromAddressOf, FromNullPtr, + FromExpr, Tree.FromDefault(), ToInt, ToIntType, + ToExpr, Tree.ToDefault()); + return; + } + case DiffTree::FromIntegerAndToDeclaration: { + llvm::APSInt FromInt; + bool IsValidFromInt; + QualType FromIntType; + Expr *FromExpr; + ValueDecl *ToValueDecl; + bool ToAddressOf; + bool ToNullPtr; + Expr *ToExpr; + Tree.GetFromIntegerAndToDeclarationDiff( + FromInt, IsValidFromInt, FromIntType, FromExpr, ToValueDecl, + ToAddressOf, ToNullPtr, ToExpr); + assert(IsValidFromInt && (ToValueDecl || ToNullPtr)); + PrintIntegerAndValueDecl(FromInt, FromIntType, FromExpr, + Tree.FromDefault(), ToValueDecl, ToAddressOf, + ToNullPtr, ToExpr, Tree.ToDefault()); + return; + } + case DiffTree::Template: { + // Node is root of template. Recurse on children. + TemplateDecl *FromTD, *ToTD; + Qualifiers FromQual, ToQual; + Tree.GetTemplateDiff(FromTD, ToTD, FromQual, ToQual); + + PrintQualifiers(FromQual, ToQual); + + if (!Tree.HasChildren()) { + // If we're dealing with a template specialization with zero + // arguments, there are no children; special-case this. + OS << FromTD->getDeclName() << "<>"; return; } - case DiffTree::Template: { - // Node is root of template. Recurse on children. - TemplateDecl *FromTD, *ToTD; - Qualifiers FromQual, ToQual; - Tree.GetTemplateDiff(FromTD, ToTD, FromQual, ToQual); - - PrintQualifiers(FromQual, ToQual); - - if (!Tree.HasChildren()) { - // If we're dealing with a template specialization with zero - // arguments, there are no children; special-case this. - OS << FromTD->getDeclName() << "<>"; - return; - } - OS << FromTD->getDeclName() << '<'; - Tree.MoveToChild(); - unsigned NumElideArgs = 0; - bool AllArgsElided = true; - do { - if (ElideType) { - if (Tree.NodeIsSame()) { - ++NumElideArgs; - continue; - } - AllArgsElided = false; - if (NumElideArgs > 0) { - PrintElideArgs(NumElideArgs, Indent); - NumElideArgs = 0; - OS << ", "; - } + OS << FromTD->getDeclName() << '<'; + Tree.MoveToChild(); + unsigned NumElideArgs = 0; + bool AllArgsElided = true; + do { + if (ElideType) { + if (Tree.NodeIsSame()) { + ++NumElideArgs; + continue; } - TreeToString(Indent); - if (Tree.HasNextSibling()) - OS << ", "; - } while (Tree.AdvanceSibling()); - if (NumElideArgs > 0) { - if (AllArgsElided) - OS << "..."; - else + AllArgsElided = false; + if (NumElideArgs > 0) { PrintElideArgs(NumElideArgs, Indent); + NumElideArgs = 0; + OS << ", "; + } } - - Tree.Parent(); - OS << ">"; - return; + TreeToString(Indent); + if (Tree.HasNextSibling()) + OS << ", "; + } while (Tree.AdvanceSibling()); + if (NumElideArgs > 0) { + if (AllArgsElided) + OS << "..."; + else + PrintElideArgs(NumElideArgs, Indent); } + + Tree.Parent(); + OS << ">"; + return; + } } } @@ -1628,8 +1602,8 @@ /// PrintTypeNames - prints the typenames, bolding differences. Will detect /// typenames that are the same and attempt to disambiguate them by using /// canonical typenames. - void PrintTypeNames(QualType FromType, QualType ToType, - bool FromDefault, bool ToDefault, bool Same) { + void PrintTypeNames(QualType FromType, QualType ToType, bool FromDefault, + bool ToDefault, bool Same) { assert((!FromType.isNull() || !ToType.isNull()) && "Only one template argument may be missing."); @@ -1640,7 +1614,7 @@ if (!FromType.isNull() && !ToType.isNull() && FromType.getLocalUnqualifiedType() == - ToType.getLocalUnqualifiedType()) { + ToType.getLocalUnqualifiedType()) { Qualifiers FromQual = FromType.getLocalQualifiers(), ToQual = ToType.getLocalQualifiers(); PrintQualifiers(FromQual, ToQual); @@ -1648,10 +1622,10 @@ return; } - std::string FromTypeStr = FromType.isNull() ? "(no argument)" - : FromType.getAsString(Policy); - std::string ToTypeStr = ToType.isNull() ? "(no argument)" - : ToType.getAsString(Policy); + std::string FromTypeStr = + FromType.isNull() ? "(no argument)" : FromType.getAsString(Policy); + std::string ToTypeStr = + ToType.isNull() ? "(no argument)" : ToType.getAsString(Policy); // Switch to canonical typename if it is better. // TODO: merge this with other aka printing above. if (FromTypeStr == ToTypeStr) { @@ -1664,7 +1638,8 @@ } } - if (PrintTree) OS << '['; + if (PrintTree) + OS << '['; OS << (FromDefault ? "(default) " : ""); Bold(); OS << FromTypeStr; @@ -1680,10 +1655,10 @@ /// PrintExpr - Prints out the expr template arguments, highlighting argument /// differences. - void PrintExpr(const Expr *FromExpr, const Expr *ToExpr, bool FromDefault, + void PrintExpr(Expr const *FromExpr, Expr const *ToExpr, bool FromDefault, bool ToDefault, bool Same) { assert((FromExpr || ToExpr) && - "Only one template argument may be missing."); + "Only one template argument may be missing."); if (Same) { PrintExpr(FromExpr); } else if (!PrintTree) { @@ -1705,7 +1680,7 @@ } /// PrintExpr - Actual formatting and printing of expressions. - void PrintExpr(const Expr *E) { + void PrintExpr(Expr const *E) { if (E) { E->printPretty(OS, nullptr, Policy); return; @@ -1749,7 +1724,7 @@ /// PrintAPSInt - Handles printing of integral arguments, highlighting /// argument differences. - void PrintAPSInt(const llvm::APSInt &FromInt, const llvm::APSInt &ToInt, + void PrintAPSInt(llvm::APSInt const &FromInt, llvm::APSInt const &ToInt, bool IsValidFromInt, bool IsValidToInt, QualType FromIntType, QualType ToIntType, Expr *FromExpr, Expr *ToExpr, bool FromDefault, bool ToDefault, bool Same) { @@ -1782,7 +1757,7 @@ /// PrintAPSInt - If valid, print the APSInt. If the expression is /// gives more information, print it too. - void PrintAPSInt(const llvm::APSInt &Val, Expr *E, bool Valid, + void PrintAPSInt(llvm::APSInt const &Val, Expr *E, bool Valid, QualType IntType, bool PrintType) { Bold(); if (Valid) { @@ -1817,11 +1792,13 @@ /// HasExtraInfo - Returns true if E is not an integer literal, the /// negation of an integer literal, or a boolean literal. bool HasExtraInfo(Expr *E) { - if (!E) return false; + if (!E) + return false; E = E->IgnoreImpCasts(); - if (isa(E)) return false; + if (isa(E)) + return false; if (UnaryOperator *UO = dyn_cast(E)) if (UO->getOpcode() == UO_Minus) @@ -1901,7 +1878,7 @@ /// APSInt to print a mixed difference. void PrintValueDeclAndInteger(ValueDecl *VD, bool NeedAddressOf, bool IsNullPtr, Expr *VDExpr, bool DefaultDecl, - const llvm::APSInt &Val, QualType IntType, + llvm::APSInt const &Val, QualType IntType, Expr *IntExpr, bool DefaultInt) { if (!PrintTree) { OS << (DefaultDecl ? "(default) " : ""); @@ -1921,7 +1898,7 @@ /// PrintIntegerAndValueDecl - Uses the print functions for APSInt and /// ValueDecl to print a mixed difference. - void PrintIntegerAndValueDecl(const llvm::APSInt &Val, QualType IntType, + void PrintIntegerAndValueDecl(llvm::APSInt const &Val, QualType IntType, Expr *IntExpr, bool DefaultInt, ValueDecl *VD, bool NeedAddressOf, bool IsNullPtr, Expr *VDExpr, bool DefaultDecl) { @@ -1946,7 +1923,8 @@ for (unsigned i = 0; i < Indent; ++i) OS << " "; } - if (NumElideArgs == 0) return; + if (NumElideArgs == 0) + return; if (NumElideArgs == 1) OS << "[...]"; else @@ -1961,13 +1939,13 @@ // Both types have same qualifiers if (FromQual == ToQual) { - PrintQualifier(FromQual, /*ApplyBold*/false); + PrintQualifier(FromQual, /*ApplyBold*/ false); return; } // Find common qualifiers and strip them from FromQual and ToQual. - Qualifiers CommonQual = Qualifiers::removeCommonQualifiers(FromQual, - ToQual); + Qualifiers CommonQual = + Qualifiers::removeCommonQualifiers(FromQual, ToQual); // The qualifiers are printed before the template name. // Inline printing: @@ -1986,8 +1964,8 @@ OS << "(no qualifiers) "; Unbold(); } else { - PrintQualifier(CommonQual, /*ApplyBold*/false); - PrintQualifier(FromQual, /*ApplyBold*/true); + PrintQualifier(CommonQual, /*ApplyBold*/ false); + PrintQualifier(FromQual, /*ApplyBold*/ true); } OS << "!= "; if (CommonQual.empty() && ToQual.empty()) { @@ -1995,51 +1973,48 @@ OS << "(no qualifiers)"; Unbold(); } else { - PrintQualifier(CommonQual, /*ApplyBold*/false, - /*appendSpaceIfNonEmpty*/!ToQual.empty()); - PrintQualifier(ToQual, /*ApplyBold*/true, - /*appendSpaceIfNonEmpty*/false); + PrintQualifier(CommonQual, /*ApplyBold*/ false, + /*appendSpaceIfNonEmpty*/ !ToQual.empty()); + PrintQualifier(ToQual, /*ApplyBold*/ true, + /*appendSpaceIfNonEmpty*/ false); } OS << "] "; } else { - PrintQualifier(CommonQual, /*ApplyBold*/false); - PrintQualifier(FromQual, /*ApplyBold*/true); + PrintQualifier(CommonQual, /*ApplyBold*/ false); + PrintQualifier(FromQual, /*ApplyBold*/ true); } } void PrintQualifier(Qualifiers Q, bool ApplyBold, bool AppendSpaceIfNonEmpty = true) { - if (Q.empty()) return; - if (ApplyBold) Bold(); + if (Q.empty()) + return; + if (ApplyBold) + Bold(); Q.print(OS, Policy, AppendSpaceIfNonEmpty); - if (ApplyBold) Unbold(); + if (ApplyBold) + Unbold(); } public: - TemplateDiff(raw_ostream &OS, ASTContext &Context, QualType FromType, QualType ToType, bool PrintTree, bool PrintFromType, bool ElideType, bool ShowColor) - : Context(Context), - Policy(Context.getLangOpts()), - ElideType(ElideType), - PrintTree(PrintTree), - ShowColor(ShowColor), - // When printing a single type, the FromType is the one printed. - FromTemplateType(PrintFromType ? FromType : ToType), - ToTemplateType(PrintFromType ? ToType : FromType), - OS(OS), - IsBold(false) { - } + : Context(Context), Policy(Context.getLangOpts()), ElideType(ElideType), + PrintTree(PrintTree), ShowColor(ShowColor), + // When printing a single type, the FromType is the one printed. + FromTemplateType(PrintFromType ? FromType : ToType), + ToTemplateType(PrintFromType ? ToType : FromType), OS(OS), + IsBold(false) {} /// DiffTemplate - Start the template type diffing. void DiffTemplate() { Qualifiers FromQual = FromTemplateType.getQualifiers(), ToQual = ToTemplateType.getQualifiers(); - const TemplateSpecializationType *FromOrigTST = + TemplateSpecializationType const *FromOrigTST = GetTemplateSpecializationType(Context, FromTemplateType); - const TemplateSpecializationType *ToOrigTST = + TemplateSpecializationType const *ToOrigTST = GetTemplateSpecializationType(Context, ToTemplateType); // Only checking templates. @@ -2076,7 +2051,7 @@ return true; } }; // end class TemplateDiff -} // end anonymous namespace +} // end anonymous namespace /// FormatTemplateTypeDiff - A helper static function to start the template /// diff and return the properly formatted string. Returns true if the diff Index: clang/lib/AST/ASTDumper.cpp =================================================================== --- clang/lib/AST/ASTDumper.cpp +++ clang/lib/AST/ASTDumper.cpp @@ -22,7 +22,7 @@ using namespace clang; using namespace clang::comments; -void ASTDumper::dumpLookups(const DeclContext *DC, bool DumpDecls) { +void ASTDumper::dumpLookups(DeclContext const *DC, bool DumpDecls) { NodeDumper.AddChild([=] { OS << "StoredDeclsMap "; NodeDumper.dumpBareDeclRef(cast(DC)); @@ -82,11 +82,11 @@ } template -void ASTDumper::dumpTemplateDeclSpecialization(const SpecializationDecl *D, +void ASTDumper::dumpTemplateDeclSpecialization(SpecializationDecl const *D, bool DumpExplicitInst, bool DumpRefOnly) { bool DumpedAny = false; - for (const auto *RedeclWithBadType : D->redecls()) { + for (auto const *RedeclWithBadType : D->redecls()) { // FIXME: The redecls() range sometimes has elements of a less-specific // type. (In particular, ClassTemplateSpecializationDecl::redecls() gives // us TagDecls, and should give CXXRecordDecls). @@ -124,30 +124,30 @@ } template -void ASTDumper::dumpTemplateDecl(const TemplateDecl *D, bool DumpExplicitInst) { +void ASTDumper::dumpTemplateDecl(TemplateDecl const *D, bool DumpExplicitInst) { dumpTemplateParameters(D->getTemplateParameters()); Visit(D->getTemplatedDecl()); if (GetTraversalKind() == TK_AsIs) { - for (const auto *Child : D->specializations()) + for (auto const *Child : D->specializations()) dumpTemplateDeclSpecialization(Child, DumpExplicitInst, !D->isCanonicalDecl()); } } -void ASTDumper::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) { +void ASTDumper::VisitFunctionTemplateDecl(FunctionTemplateDecl const *D) { // FIXME: We don't add a declaration of a function template specialization // to its context when it's explicitly instantiated, so dump explicit // instantiations when we dump the template itself. dumpTemplateDecl(D, true); } -void ASTDumper::VisitClassTemplateDecl(const ClassTemplateDecl *D) { +void ASTDumper::VisitClassTemplateDecl(ClassTemplateDecl const *D) { dumpTemplateDecl(D, false); } -void ASTDumper::VisitVarTemplateDecl(const VarTemplateDecl *D) { +void ASTDumper::VisitVarTemplateDecl(VarTemplateDecl const *D) { dumpTemplateDecl(D, false); } @@ -155,7 +155,7 @@ // Type method implementations //===----------------------------------------------------------------------===// -void QualType::dump(const char *msg) const { +void QualType::dump(char const *msg) const { if (msg) llvm::errs() << msg << ": "; dump(); @@ -167,7 +167,7 @@ } LLVM_DUMP_METHOD void QualType::dump(llvm::raw_ostream &OS, - const ASTContext &Context) const { + ASTContext const &Context) const { ASTDumper Dumper(OS, Context, Context.getDiagnostics().getShowColors()); Dumper.Visit(*this); } @@ -175,7 +175,7 @@ LLVM_DUMP_METHOD void Type::dump() const { QualType(this, 0).dump(); } LLVM_DUMP_METHOD void Type::dump(llvm::raw_ostream &OS, - const ASTContext &Context) const { + ASTContext const &Context) const { QualType(this, 0).dump(OS, Context); } @@ -188,7 +188,7 @@ LLVM_DUMP_METHOD void Decl::dump(raw_ostream &OS, bool Deserialize, ASTDumpOutputFormat Format) const { ASTContext &Ctx = getASTContext(); - const SourceManager &SM = Ctx.getSourceManager(); + SourceManager const &SM = Ctx.getSourceManager(); if (ADOF_JSON == Format) { JSONDumper P(OS, SM, Ctx, Ctx.getPrintingPolicy(), @@ -203,7 +203,7 @@ } LLVM_DUMP_METHOD void Decl::dumpColor() const { - const ASTContext &Ctx = getASTContext(); + ASTContext const &Ctx = getASTContext(); ASTDumper P(llvm::errs(), Ctx, /*ShowColors=*/true); P.Visit(this); } @@ -212,13 +212,12 @@ dumpLookups(llvm::errs()); } -LLVM_DUMP_METHOD void DeclContext::dumpLookups(raw_ostream &OS, - bool DumpDecls, +LLVM_DUMP_METHOD void DeclContext::dumpLookups(raw_ostream &OS, bool DumpDecls, bool Deserialize) const { - const DeclContext *DC = this; + DeclContext const *DC = this; while (!DC->isTranslationUnit()) DC = DC->getParent(); - const ASTContext &Ctx = cast(DC)->getASTContext(); + ASTContext const &Ctx = cast(DC)->getASTContext(); ASTDumper P(OS, Ctx, Ctx.getDiagnostics().getShowColors()); P.setDeserialize(Deserialize); P.dumpLookups(this, DumpDecls); @@ -234,7 +233,7 @@ } LLVM_DUMP_METHOD void Stmt::dump(raw_ostream &OS, - const ASTContext &Context) const { + ASTContext const &Context) const { ASTDumper P(OS, Context, Context.getDiagnostics().getShowColors()); P.Visit(this); } @@ -249,7 +248,7 @@ //===----------------------------------------------------------------------===// LLVM_DUMP_METHOD void Comment::dump() const { - const auto *FC = dyn_cast(this); + auto const *FC = dyn_cast(this); if (!FC) return; ASTDumper Dumper(llvm::errs(), /*ShowColors=*/false); @@ -257,8 +256,8 @@ } LLVM_DUMP_METHOD void Comment::dump(raw_ostream &OS, - const ASTContext &Context) const { - const auto *FC = dyn_cast(this); + ASTContext const &Context) const { + auto const *FC = dyn_cast(this); if (!FC) return; ASTDumper Dumper(OS, Context, Context.getDiagnostics().getShowColors()); @@ -266,7 +265,7 @@ } LLVM_DUMP_METHOD void Comment::dumpColor() const { - const auto *FC = dyn_cast(this); + auto const *FC = dyn_cast(this); if (!FC) return; ASTDumper Dumper(llvm::errs(), /*ShowColors=*/true); @@ -283,7 +282,7 @@ } LLVM_DUMP_METHOD void APValue::dump(raw_ostream &OS, - const ASTContext &Context) const { + ASTContext const &Context) const { ASTDumper Dumper(llvm::errs(), Context, Context.getDiagnostics().getShowColors()); Dumper.Visit(*this, /*Ty=*/Context.getPointerType(Context.CharTy)); Index: clang/lib/AST/ASTImporter.cpp =================================================================== --- clang/lib/AST/ASTImporter.cpp +++ clang/lib/AST/ASTImporter.cpp @@ -12,9 +12,9 @@ //===----------------------------------------------------------------------===// #include "clang/AST/ASTImporter.h" -#include "clang/AST/ASTImporterSharedState.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" +#include "clang/AST/ASTImporterSharedState.h" #include "clang/AST/ASTStructuralEquivalence.h" #include "clang/AST/Attr.h" #include "clang/AST/Decl.h" @@ -58,8 +58,8 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" -#include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" @@ -73,646 +73,636 @@ namespace clang { - using llvm::make_error; - using llvm::Error; - using llvm::Expected; - using ExpectedType = llvm::Expected; - using ExpectedStmt = llvm::Expected; - using ExpectedExpr = llvm::Expected; - using ExpectedDecl = llvm::Expected; - using ExpectedSLoc = llvm::Expected; - using ExpectedName = llvm::Expected; - - std::string ImportError::toString() const { - // FIXME: Improve error texts. - switch (Error) { - case NameConflict: - return "NameConflict"; - case UnsupportedConstruct: - return "UnsupportedConstruct"; - case Unknown: - return "Unknown error"; - } - llvm_unreachable("Invalid error code."); - return "Invalid error code."; - } +using llvm::Error; +using llvm::Expected; +using llvm::make_error; +using ExpectedType = llvm::Expected; +using ExpectedStmt = llvm::Expected; +using ExpectedExpr = llvm::Expected; +using ExpectedDecl = llvm::Expected; +using ExpectedSLoc = llvm::Expected; +using ExpectedName = llvm::Expected; - void ImportError::log(raw_ostream &OS) const { - OS << toString(); +std::string ImportError::toString() const { + // FIXME: Improve error texts. + switch (Error) { + case NameConflict: + return "NameConflict"; + case UnsupportedConstruct: + return "UnsupportedConstruct"; + case Unknown: + return "Unknown error"; } + llvm_unreachable("Invalid error code."); + return "Invalid error code."; +} - std::error_code ImportError::convertToErrorCode() const { - llvm_unreachable("Function not implemented."); - } +void ImportError::log(raw_ostream &OS) const { OS << toString(); } - char ImportError::ID; +std::error_code ImportError::convertToErrorCode() const { + llvm_unreachable("Function not implemented."); +} - template - SmallVector - getCanonicalForwardRedeclChain(Redeclarable* D) { - SmallVector Redecls; - for (auto *R : D->getFirstDecl()->redecls()) { - if (R != D->getFirstDecl()) - Redecls.push_back(R); - } - Redecls.push_back(D->getFirstDecl()); - std::reverse(Redecls.begin(), Redecls.end()); - return Redecls; - } +char ImportError::ID; - SmallVector getCanonicalForwardRedeclChain(Decl* D) { - if (auto *FD = dyn_cast(D)) - return getCanonicalForwardRedeclChain(FD); - if (auto *VD = dyn_cast(D)) - return getCanonicalForwardRedeclChain(VD); - if (auto *TD = dyn_cast(D)) - return getCanonicalForwardRedeclChain(TD); - llvm_unreachable("Bad declaration kind"); +template +SmallVector getCanonicalForwardRedeclChain(Redeclarable *D) { + SmallVector Redecls; + for (auto *R : D->getFirstDecl()->redecls()) { + if (R != D->getFirstDecl()) + Redecls.push_back(R); + } + Redecls.push_back(D->getFirstDecl()); + std::reverse(Redecls.begin(), Redecls.end()); + return Redecls; +} + +SmallVector getCanonicalForwardRedeclChain(Decl *D) { + if (auto *FD = dyn_cast(D)) + return getCanonicalForwardRedeclChain(FD); + if (auto *VD = dyn_cast(D)) + return getCanonicalForwardRedeclChain(VD); + if (auto *TD = dyn_cast(D)) + return getCanonicalForwardRedeclChain(TD); + llvm_unreachable("Bad declaration kind"); +} + +void updateFlags(Decl const *From, Decl *To) { + // Check if some flags or attrs are new in 'From' and copy into 'To'. + // FIXME: Other flags or attrs? + if (From->isUsed(false) && !To->isUsed(false)) + To->setIsUsed(); +} + +class ASTNodeImporter : public TypeVisitor, + public DeclVisitor, + public StmtVisitor { + ASTImporter &Importer; + + // Use this instead of Importer.importInto . + template + LLVM_NODISCARD Error importInto(ImportT &To, ImportT const &From) { + return Importer.importInto(To, From); + } + + // Use this to import pointers of specific type. + template + LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) { + auto ToOrErr = Importer.Import(From); + if (ToOrErr) + To = cast_or_null(*ToOrErr); + return ToOrErr.takeError(); } - void updateFlags(const Decl *From, Decl *To) { - // Check if some flags or attrs are new in 'From' and copy into 'To'. - // FIXME: Other flags or attrs? - if (From->isUsed(false) && !To->isUsed(false)) - To->setIsUsed(); + // Call the import function of ASTImporter for a baseclass of type `T` and + // cast the return value to `T`. + template Expected import(T *From) { + auto ToOrErr = Importer.Import(From); + if (!ToOrErr) + return ToOrErr.takeError(); + return cast_or_null(*ToOrErr); } - class ASTNodeImporter : public TypeVisitor, - public DeclVisitor, - public StmtVisitor { - ASTImporter &Importer; + template Expected import(const T *From) { + return import(const_cast(From)); + } - // Use this instead of Importer.importInto . - template - LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) { - return Importer.importInto(To, From); - } + // Call the import function of ASTImporter for type `T`. + template Expected import(const T &From) { + return Importer.Import(From); + } - // Use this to import pointers of specific type. - template - LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) { - auto ToOrErr = Importer.Import(From); - if (ToOrErr) - To = cast_or_null(*ToOrErr); - return ToOrErr.takeError(); - } + // Import an Optional by importing the contained T, if any. + template Expected> import(Optional From) { + if (!From) + return Optional(); + return import(*From); + } - // Call the import function of ASTImporter for a baseclass of type `T` and - // cast the return value to `T`. - template - Expected import(T *From) { - auto ToOrErr = Importer.Import(From); - if (!ToOrErr) - return ToOrErr.takeError(); - return cast_or_null(*ToOrErr); + // Helper for chaining together multiple imports. If an error is detected, + // subsequent imports will return default constructed nodes, so that failure + // can be detected with a single conditional branch after a sequence of + // imports. + template T importChecked(Error &Err, const T &From) { + // Don't attempt to import nodes if we hit an error earlier. + if (Err) + return T{}; + Expected MaybeVal = import(From); + if (!MaybeVal) { + Err = MaybeVal.takeError(); + return T{}; } + return *MaybeVal; + } - template - Expected import(const T *From) { - return import(const_cast(From)); - } + ExplicitSpecifier importExplicitSpecifier(Error &Err, + ExplicitSpecifier ESpec); - // Call the import function of ASTImporter for type `T`. - template - Expected import(const T &From) { - return Importer.Import(From); + // Wrapper for an overload set. + template struct CallOverloadedCreateFun { + template decltype(auto) operator()(Args &&...args) { + return ToDeclT::Create(std::forward(args)...); } + }; - // Import an Optional by importing the contained T, if any. - template - Expected> import(Optional From) { - if (!From) - return Optional(); - return import(*From); + // Always use these functions to create a Decl during import. There are + // certain tasks which must be done after the Decl was created, e.g. we + // must immediately register that as an imported Decl. The parameter `ToD` + // will be set to the newly created Decl or if had been imported before + // then to the already imported Decl. Returns a bool value set to true if + // the `FromD` had been imported before. + template + LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, + Args &&...args) { + // There may be several overloads of ToDeclT::Create. We must make sure + // to call the one which would be chosen by the arguments, thus we use a + // wrapper for the overload set. + CallOverloadedCreateFun OC; + return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, + std::forward(args)...); + } + // Use this overload if a special Type is needed to be created. E.g if we + // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl` + // then: + // TypedefNameDecl *ToTypedef; + // GetImportedOrCreateDecl(ToTypedef, FromD, ...); + template + LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, + Args &&...args) { + CallOverloadedCreateFun OC; + return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, + std::forward(args)...); + } + // Use this version if a special create function must be + // used, e.g. CXXRecordDecl::CreateLambda . + template + LLVM_NODISCARD bool + GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun, + FromDeclT *FromD, Args &&...args) { + if (Importer.getImportDeclErrorIfAny(FromD)) { + ToD = nullptr; + return true; // Already imported but with error. } + ToD = cast_or_null(Importer.GetAlreadyImportedOrNull(FromD)); + if (ToD) + return true; // Already imported. + ToD = CreateFun(std::forward(args)...); + // Keep track of imported Decls. + Importer.RegisterImportedDecl(FromD, ToD); + InitializeImportedDecl(FromD, ToD); + return false; // A new Decl is created. + } + + void InitializeImportedDecl(Decl *FromD, Decl *ToD) { + ToD->IdentifierNamespace = FromD->IdentifierNamespace; + if (FromD->isUsed()) + ToD->setIsUsed(); + if (FromD->isImplicit()) + ToD->setImplicit(); + } + + // Check if we have found an existing definition. Returns with that + // definition if yes, otherwise returns null. + Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) { + FunctionDecl const *Definition = nullptr; + if (D->doesThisDeclarationHaveABody() && FoundFunction->hasBody(Definition)) + return Importer.MapImported(D, const_cast(Definition)); + return nullptr; + } - // Helper for chaining together multiple imports. If an error is detected, - // subsequent imports will return default constructed nodes, so that failure - // can be detected with a single conditional branch after a sequence of - // imports. - template T importChecked(Error &Err, const T &From) { - // Don't attempt to import nodes if we hit an error earlier. - if (Err) - return T{}; - Expected MaybeVal = import(From); - if (!MaybeVal) { - Err = MaybeVal.takeError(); - return T{}; - } - return *MaybeVal; + void addDeclToContexts(Decl *FromD, Decl *ToD) { + if (Importer.isMinimalImport()) { + // In minimal import case the decl must be added even if it is not + // contained in original context, for LLDB compatibility. + // FIXME: Check if a better solution is possible. + if (!FromD->getDescribedTemplate() && + FromD->getFriendObjectKind() == Decl::FOK_None) + ToD->getLexicalDeclContext()->addDeclInternal(ToD); + return; } - ExplicitSpecifier importExplicitSpecifier(Error &Err, - ExplicitSpecifier ESpec); + DeclContext *FromDC = FromD->getDeclContext(); + DeclContext *FromLexicalDC = FromD->getLexicalDeclContext(); + DeclContext *ToDC = ToD->getDeclContext(); + DeclContext *ToLexicalDC = ToD->getLexicalDeclContext(); - // Wrapper for an overload set. - template struct CallOverloadedCreateFun { - template decltype(auto) operator()(Args &&... args) { - return ToDeclT::Create(std::forward(args)...); - } - }; - - // Always use these functions to create a Decl during import. There are - // certain tasks which must be done after the Decl was created, e.g. we - // must immediately register that as an imported Decl. The parameter `ToD` - // will be set to the newly created Decl or if had been imported before - // then to the already imported Decl. Returns a bool value set to true if - // the `FromD` had been imported before. - template - LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, - Args &&... args) { - // There may be several overloads of ToDeclT::Create. We must make sure - // to call the one which would be chosen by the arguments, thus we use a - // wrapper for the overload set. - CallOverloadedCreateFun OC; - return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, - std::forward(args)...); - } - // Use this overload if a special Type is needed to be created. E.g if we - // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl` - // then: - // TypedefNameDecl *ToTypedef; - // GetImportedOrCreateDecl(ToTypedef, FromD, ...); - template - LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, - Args &&... args) { - CallOverloadedCreateFun OC; - return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, - std::forward(args)...); + bool Visible = false; + if (FromDC->containsDeclAndLoad(FromD)) { + ToDC->addDeclInternal(ToD); + Visible = true; } - // Use this version if a special create function must be - // used, e.g. CXXRecordDecl::CreateLambda . - template - LLVM_NODISCARD bool - GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun, - FromDeclT *FromD, Args &&... args) { - if (Importer.getImportDeclErrorIfAny(FromD)) { - ToD = nullptr; - return true; // Already imported but with error. - } - ToD = cast_or_null(Importer.GetAlreadyImportedOrNull(FromD)); - if (ToD) - return true; // Already imported. - ToD = CreateFun(std::forward(args)...); - // Keep track of imported Decls. - Importer.RegisterImportedDecl(FromD, ToD); - InitializeImportedDecl(FromD, ToD); - return false; // A new Decl is created. - } - - void InitializeImportedDecl(Decl *FromD, Decl *ToD) { - ToD->IdentifierNamespace = FromD->IdentifierNamespace; - if (FromD->isUsed()) - ToD->setIsUsed(); - if (FromD->isImplicit()) - ToD->setImplicit(); + if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) { + ToLexicalDC->addDeclInternal(ToD); + Visible = true; } - // Check if we have found an existing definition. Returns with that - // definition if yes, otherwise returns null. - Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) { - const FunctionDecl *Definition = nullptr; - if (D->doesThisDeclarationHaveABody() && - FoundFunction->hasBody(Definition)) - return Importer.MapImported(D, const_cast(Definition)); - return nullptr; - } - - void addDeclToContexts(Decl *FromD, Decl *ToD) { - if (Importer.isMinimalImport()) { - // In minimal import case the decl must be added even if it is not - // contained in original context, for LLDB compatibility. - // FIXME: Check if a better solution is possible. - if (!FromD->getDescribedTemplate() && - FromD->getFriendObjectKind() == Decl::FOK_None) - ToD->getLexicalDeclContext()->addDeclInternal(ToD); - return; - } - - DeclContext *FromDC = FromD->getDeclContext(); - DeclContext *FromLexicalDC = FromD->getLexicalDeclContext(); - DeclContext *ToDC = ToD->getDeclContext(); - DeclContext *ToLexicalDC = ToD->getLexicalDeclContext(); - - bool Visible = false; - if (FromDC->containsDeclAndLoad(FromD)) { - ToDC->addDeclInternal(ToD); - Visible = true; - } - if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) { - ToLexicalDC->addDeclInternal(ToD); - Visible = true; - } - - // If the Decl was added to any context, it was made already visible. - // Otherwise it is still possible that it should be visible. - if (!Visible) { - if (auto *FromNamed = dyn_cast(FromD)) { - auto *ToNamed = cast(ToD); - DeclContextLookupResult FromLookup = - FromDC->lookup(FromNamed->getDeclName()); - for (NamedDecl *ND : FromLookup) - if (ND == FromNamed) { - ToDC->makeDeclVisibleInContext(ToNamed); - break; - } - } + // If the Decl was added to any context, it was made already visible. + // Otherwise it is still possible that it should be visible. + if (!Visible) { + if (auto *FromNamed = dyn_cast(FromD)) { + auto *ToNamed = cast(ToD); + DeclContextLookupResult FromLookup = + FromDC->lookup(FromNamed->getDeclName()); + for (NamedDecl *ND : FromLookup) + if (ND == FromNamed) { + ToDC->makeDeclVisibleInContext(ToNamed); + break; + } } } + } - void updateLookupTableForTemplateParameters(TemplateParameterList &Params, - DeclContext *OldDC) { - ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable(); - if (!LT) - return; - - for (NamedDecl *TP : Params) - LT->update(TP, OldDC); - } - - void updateLookupTableForTemplateParameters(TemplateParameterList &Params) { - updateLookupTableForTemplateParameters( - Params, Importer.getToContext().getTranslationUnitDecl()); - } - - public: - explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {} - - using TypeVisitor::Visit; - using DeclVisitor::Visit; - using StmtVisitor::Visit; - - // Importing types - ExpectedType VisitType(const Type *T); - ExpectedType VisitAtomicType(const AtomicType *T); - ExpectedType VisitBuiltinType(const BuiltinType *T); - ExpectedType VisitDecayedType(const DecayedType *T); - ExpectedType VisitComplexType(const ComplexType *T); - ExpectedType VisitPointerType(const PointerType *T); - ExpectedType VisitBlockPointerType(const BlockPointerType *T); - ExpectedType VisitLValueReferenceType(const LValueReferenceType *T); - ExpectedType VisitRValueReferenceType(const RValueReferenceType *T); - ExpectedType VisitMemberPointerType(const MemberPointerType *T); - ExpectedType VisitConstantArrayType(const ConstantArrayType *T); - ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T); - ExpectedType VisitVariableArrayType(const VariableArrayType *T); - ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T); - // FIXME: DependentSizedExtVectorType - ExpectedType VisitVectorType(const VectorType *T); - ExpectedType VisitExtVectorType(const ExtVectorType *T); - ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T); - ExpectedType VisitFunctionProtoType(const FunctionProtoType *T); - ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T); - ExpectedType VisitParenType(const ParenType *T); - ExpectedType VisitTypedefType(const TypedefType *T); - ExpectedType VisitTypeOfExprType(const TypeOfExprType *T); - // FIXME: DependentTypeOfExprType - ExpectedType VisitTypeOfType(const TypeOfType *T); - ExpectedType VisitDecltypeType(const DecltypeType *T); - ExpectedType VisitUnaryTransformType(const UnaryTransformType *T); - ExpectedType VisitAutoType(const AutoType *T); - ExpectedType VisitDeducedTemplateSpecializationType( - const DeducedTemplateSpecializationType *T); - ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T); - // FIXME: DependentDecltypeType - ExpectedType VisitRecordType(const RecordType *T); - ExpectedType VisitEnumType(const EnumType *T); - ExpectedType VisitAttributedType(const AttributedType *T); - ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T); - ExpectedType VisitSubstTemplateTypeParmType( - const SubstTemplateTypeParmType *T); - ExpectedType - VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T); - ExpectedType VisitTemplateSpecializationType( - const TemplateSpecializationType *T); - ExpectedType VisitElaboratedType(const ElaboratedType *T); - ExpectedType VisitDependentNameType(const DependentNameType *T); - ExpectedType VisitPackExpansionType(const PackExpansionType *T); - ExpectedType VisitDependentTemplateSpecializationType( - const DependentTemplateSpecializationType *T); - ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T); - ExpectedType VisitObjCObjectType(const ObjCObjectType *T); - ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T); - - // Importing declarations - Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD, - SourceLocation &Loc); - Error ImportDeclParts( - NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, - DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc); - Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr); - Error ImportDeclarationNameLoc( - const DeclarationNameInfo &From, DeclarationNameInfo &To); - Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false); - Error ImportDeclContext( - Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC); - Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To); - - Expected ImportCastPath(CastExpr *E); - Expected ImportAPValue(const APValue &FromValue); - - using Designator = DesignatedInitExpr::Designator; - - /// What we should import from the definition. - enum ImportDefinitionKind { - /// Import the default subset of the definition, which might be - /// nothing (if minimal import is set) or might be everything (if minimal - /// import is not set). - IDK_Default, - /// Import everything. - IDK_Everything, - /// Import only the bare bones needed to establish a valid - /// DeclContext. - IDK_Basic - }; - - bool shouldForceImportDeclContext(ImportDefinitionKind IDK) { - return IDK == IDK_Everything || - (IDK == IDK_Default && !Importer.isMinimalImport()); - } + void updateLookupTableForTemplateParameters(TemplateParameterList &Params, + DeclContext *OldDC) { + ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable(); + if (!LT) + return; + + for (NamedDecl *TP : Params) + LT->update(TP, OldDC); + } + + void updateLookupTableForTemplateParameters(TemplateParameterList &Params) { + updateLookupTableForTemplateParameters( + Params, Importer.getToContext().getTranslationUnitDecl()); + } + +public: + explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {} + + using TypeVisitor::Visit; + using DeclVisitor::Visit; + using StmtVisitor::Visit; + + // Importing types + ExpectedType VisitType(Type const *T); + ExpectedType VisitAtomicType(AtomicType const *T); + ExpectedType VisitBuiltinType(BuiltinType const *T); + ExpectedType VisitDecayedType(DecayedType const *T); + ExpectedType VisitComplexType(ComplexType const *T); + ExpectedType VisitPointerType(PointerType const *T); + ExpectedType VisitBlockPointerType(BlockPointerType const *T); + ExpectedType VisitLValueReferenceType(LValueReferenceType const *T); + ExpectedType VisitRValueReferenceType(RValueReferenceType const *T); + ExpectedType VisitMemberPointerType(MemberPointerType const *T); + ExpectedType VisitConstantArrayType(ConstantArrayType const *T); + ExpectedType VisitIncompleteArrayType(IncompleteArrayType const *T); + ExpectedType VisitVariableArrayType(VariableArrayType const *T); + ExpectedType VisitDependentSizedArrayType(DependentSizedArrayType const *T); + // FIXME: DependentSizedExtVectorType + ExpectedType VisitVectorType(VectorType const *T); + ExpectedType VisitExtVectorType(ExtVectorType const *T); + ExpectedType VisitFunctionNoProtoType(FunctionNoProtoType const *T); + ExpectedType VisitFunctionProtoType(FunctionProtoType const *T); + ExpectedType VisitUnresolvedUsingType(UnresolvedUsingType const *T); + ExpectedType VisitParenType(ParenType const *T); + ExpectedType VisitTypedefType(TypedefType const *T); + ExpectedType VisitTypeOfExprType(TypeOfExprType const *T); + // FIXME: DependentTypeOfExprType + ExpectedType VisitTypeOfType(TypeOfType const *T); + ExpectedType VisitDecltypeType(DecltypeType const *T); + ExpectedType VisitUnaryTransformType(UnaryTransformType const *T); + ExpectedType VisitAutoType(AutoType const *T); + ExpectedType VisitDeducedTemplateSpecializationType( + DeducedTemplateSpecializationType const *T); + ExpectedType VisitInjectedClassNameType(InjectedClassNameType const *T); + // FIXME: DependentDecltypeType + ExpectedType VisitRecordType(RecordType const *T); + ExpectedType VisitEnumType(EnumType const *T); + ExpectedType VisitAttributedType(AttributedType const *T); + ExpectedType VisitTemplateTypeParmType(TemplateTypeParmType const *T); + ExpectedType + VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType const *T); + ExpectedType + VisitSubstTemplateTypeParmPackType(SubstTemplateTypeParmPackType const *T); + ExpectedType + VisitTemplateSpecializationType(TemplateSpecializationType const *T); + ExpectedType VisitElaboratedType(ElaboratedType const *T); + ExpectedType VisitDependentNameType(DependentNameType const *T); + ExpectedType VisitPackExpansionType(PackExpansionType const *T); + ExpectedType VisitDependentTemplateSpecializationType( + DependentTemplateSpecializationType const *T); + ExpectedType VisitObjCInterfaceType(ObjCInterfaceType const *T); + ExpectedType VisitObjCObjectType(ObjCObjectType const *T); + ExpectedType VisitObjCObjectPointerType(ObjCObjectPointerType const *T); + + // Importing declarations + Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD, + SourceLocation &Loc); + Error ImportDeclParts(NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, + DeclarationName &Name, NamedDecl *&ToD, + SourceLocation &Loc); + Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr); + Error ImportDeclarationNameLoc(DeclarationNameInfo const &From, + DeclarationNameInfo &To); + Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false); + Error ImportDeclContext(Decl *From, DeclContext *&ToDC, + DeclContext *&ToLexicalDC); + Error ImportImplicitMethods(CXXRecordDecl const *From, CXXRecordDecl *To); + + Expected ImportCastPath(CastExpr *E); + Expected ImportAPValue(APValue const &FromValue); + + using Designator = DesignatedInitExpr::Designator; + + /// What we should import from the definition. + enum ImportDefinitionKind { + /// Import the default subset of the definition, which might be + /// nothing (if minimal import is set) or might be everything (if minimal + /// import is not set). + IDK_Default, + /// Import everything. + IDK_Everything, + /// Import only the bare bones needed to establish a valid + /// DeclContext. + IDK_Basic + }; - Error ImportInitializer(VarDecl *From, VarDecl *To); - Error ImportDefinition( - RecordDecl *From, RecordDecl *To, - ImportDefinitionKind Kind = IDK_Default); - Error ImportDefinition( - EnumDecl *From, EnumDecl *To, - ImportDefinitionKind Kind = IDK_Default); - Error ImportDefinition( - ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, - ImportDefinitionKind Kind = IDK_Default); - Error ImportDefinition( - ObjCProtocolDecl *From, ObjCProtocolDecl *To, - ImportDefinitionKind Kind = IDK_Default); - Error ImportTemplateArguments( - const TemplateArgument *FromArgs, unsigned NumFromArgs, - SmallVectorImpl &ToArgs); - Expected - ImportTemplateArgument(const TemplateArgument &From); - - template - Error ImportTemplateArgumentListInfo( - const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo); - - template - Error ImportTemplateArgumentListInfo( - SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, - const InContainerTy &Container, TemplateArgumentListInfo &Result); - - using TemplateArgsTy = SmallVector; - using FunctionTemplateAndArgsTy = - std::tuple; - Expected - ImportFunctionTemplateWithTemplateArgsFromSpecialization( - FunctionDecl *FromFD); - Error ImportTemplateParameterLists(const DeclaratorDecl *FromD, - DeclaratorDecl *ToD); - - Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); - - Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD); - - Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam, - ParmVarDecl *ToParam); - - template - bool hasSameVisibilityContextAndLinkage(T *Found, T *From); - - bool IsStructuralMatch(Decl *From, Decl *To, bool Complain); - bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, - bool Complain = true); - bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar, - bool Complain = true); - bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord); - bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC); - bool IsStructuralMatch(FunctionTemplateDecl *From, - FunctionTemplateDecl *To); - bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To); - bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To); - bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To); - ExpectedDecl VisitDecl(Decl *D); - ExpectedDecl VisitImportDecl(ImportDecl *D); - ExpectedDecl VisitEmptyDecl(EmptyDecl *D); - ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D); - ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D); - ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D); - ExpectedDecl VisitBindingDecl(BindingDecl *D); - ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D); - ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D); - ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias); - ExpectedDecl VisitTypedefDecl(TypedefDecl *D); - ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D); - ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); - ExpectedDecl VisitLabelDecl(LabelDecl *D); - ExpectedDecl VisitEnumDecl(EnumDecl *D); - ExpectedDecl VisitRecordDecl(RecordDecl *D); - ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D); - ExpectedDecl VisitFunctionDecl(FunctionDecl *D); - ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D); - ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D); - ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D); - ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D); - ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D); - ExpectedDecl VisitFieldDecl(FieldDecl *D); - ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D); - ExpectedDecl VisitFriendDecl(FriendDecl *D); - ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D); - ExpectedDecl VisitVarDecl(VarDecl *D); - ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D); - ExpectedDecl VisitParmVarDecl(ParmVarDecl *D); - ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D); - ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); - ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D); - ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D); - ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D); - ExpectedDecl VisitUsingDecl(UsingDecl *D); - ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D); - ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D); - ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI); - ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D); - ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); - ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); - ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D); - ExpectedDecl - VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D); - - Expected - ImportObjCTypeParamList(ObjCTypeParamList *list); - - ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); - ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); - ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D); - ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D); - ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); - ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); - ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); - ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); - ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D); - ExpectedDecl VisitClassTemplateSpecializationDecl( - ClassTemplateSpecializationDecl *D); - ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D); - ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D); - ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D); - - // Importing statements - ExpectedStmt VisitStmt(Stmt *S); - ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S); - ExpectedStmt VisitDeclStmt(DeclStmt *S); - ExpectedStmt VisitNullStmt(NullStmt *S); - ExpectedStmt VisitCompoundStmt(CompoundStmt *S); - ExpectedStmt VisitCaseStmt(CaseStmt *S); - ExpectedStmt VisitDefaultStmt(DefaultStmt *S); - ExpectedStmt VisitLabelStmt(LabelStmt *S); - ExpectedStmt VisitAttributedStmt(AttributedStmt *S); - ExpectedStmt VisitIfStmt(IfStmt *S); - ExpectedStmt VisitSwitchStmt(SwitchStmt *S); - ExpectedStmt VisitWhileStmt(WhileStmt *S); - ExpectedStmt VisitDoStmt(DoStmt *S); - ExpectedStmt VisitForStmt(ForStmt *S); - ExpectedStmt VisitGotoStmt(GotoStmt *S); - ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S); - ExpectedStmt VisitContinueStmt(ContinueStmt *S); - ExpectedStmt VisitBreakStmt(BreakStmt *S); - ExpectedStmt VisitReturnStmt(ReturnStmt *S); - // FIXME: MSAsmStmt - // FIXME: SEHExceptStmt - // FIXME: SEHFinallyStmt - // FIXME: SEHTryStmt - // FIXME: SEHLeaveStmt - // FIXME: CapturedStmt - ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S); - ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S); - ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S); - // FIXME: MSDependentExistsStmt - ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); - ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); - ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S); - ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S); - ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); - ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); - ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); - - // Importing expressions - ExpectedStmt VisitExpr(Expr *E); - ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E); - ExpectedStmt VisitVAArgExpr(VAArgExpr *E); - ExpectedStmt VisitChooseExpr(ChooseExpr *E); - ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E); - ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E); - ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E); - ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E); - ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); - ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E); - ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E); - ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E); - ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E); - ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E); - ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E); - ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E); - ExpectedStmt VisitStringLiteral(StringLiteral *E); - ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E); - ExpectedStmt VisitAtomicExpr(AtomicExpr *E); - ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E); - ExpectedStmt VisitConstantExpr(ConstantExpr *E); - ExpectedStmt VisitParenExpr(ParenExpr *E); - ExpectedStmt VisitParenListExpr(ParenListExpr *E); - ExpectedStmt VisitStmtExpr(StmtExpr *E); - ExpectedStmt VisitUnaryOperator(UnaryOperator *E); - ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); - ExpectedStmt VisitBinaryOperator(BinaryOperator *E); - ExpectedStmt VisitConditionalOperator(ConditionalOperator *E); - ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E); - ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E); - ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E); - ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E); - ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E); - ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E); - ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E); - ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E); - ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE); - ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E); - ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E); - ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E); - ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); - ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); - ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); - ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); - ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E); - ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E); - ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E); - ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E); - ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E); - ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E); - ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); - ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); - ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); - ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E); - ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E); - ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E); - ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E); - ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E); - ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); - ExpectedStmt VisitMemberExpr(MemberExpr *E); - ExpectedStmt VisitCallExpr(CallExpr *E); - ExpectedStmt VisitLambdaExpr(LambdaExpr *LE); - ExpectedStmt VisitInitListExpr(InitListExpr *E); - ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E); - ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E); - ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E); - ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E); - ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E); - ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E); - ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E); - ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E); - ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E); - ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E); - - template - Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) { - using ItemT = std::remove_reference_t; - for (; Ibegin != Iend; ++Ibegin, ++Obegin) { - Expected ToOrErr = import(*Ibegin); - if (!ToOrErr) - return ToOrErr.takeError(); - *Obegin = *ToOrErr; - } - return Error::success(); + bool shouldForceImportDeclContext(ImportDefinitionKind IDK) { + return IDK == IDK_Everything || + (IDK == IDK_Default && !Importer.isMinimalImport()); + } + + Error ImportInitializer(VarDecl *From, VarDecl *To); + Error ImportDefinition(RecordDecl *From, RecordDecl *To, + ImportDefinitionKind Kind = IDK_Default); + Error ImportDefinition(EnumDecl *From, EnumDecl *To, + ImportDefinitionKind Kind = IDK_Default); + Error ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, + ImportDefinitionKind Kind = IDK_Default); + Error ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To, + ImportDefinitionKind Kind = IDK_Default); + Error ImportTemplateArguments(TemplateArgument const *FromArgs, + unsigned NumFromArgs, + SmallVectorImpl &ToArgs); + Expected + ImportTemplateArgument(TemplateArgument const &From); + + template + Error ImportTemplateArgumentListInfo(InContainerTy const &Container, + TemplateArgumentListInfo &ToTAInfo); + + template + Error ImportTemplateArgumentListInfo(SourceLocation FromLAngleLoc, + SourceLocation FromRAngleLoc, + InContainerTy const &Container, + TemplateArgumentListInfo &Result); + + using TemplateArgsTy = SmallVector; + using FunctionTemplateAndArgsTy = + std::tuple; + Expected + ImportFunctionTemplateWithTemplateArgsFromSpecialization( + FunctionDecl *FromFD); + Error ImportTemplateParameterLists(DeclaratorDecl const *FromD, + DeclaratorDecl *ToD); + + Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); + + Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD); + + Error ImportDefaultArgOfParmVarDecl(ParmVarDecl const *FromParam, + ParmVarDecl *ToParam); + + template + bool hasSameVisibilityContextAndLinkage(T *Found, T *From); + + bool IsStructuralMatch(Decl *From, Decl *To, bool Complain); + bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, + bool Complain = true); + bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar, + bool Complain = true); + bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord); + bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC); + bool IsStructuralMatch(FunctionTemplateDecl *From, FunctionTemplateDecl *To); + bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To); + bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To); + bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To); + ExpectedDecl VisitDecl(Decl *D); + ExpectedDecl VisitImportDecl(ImportDecl *D); + ExpectedDecl VisitEmptyDecl(EmptyDecl *D); + ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D); + ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D); + ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D); + ExpectedDecl VisitBindingDecl(BindingDecl *D); + ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D); + ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D); + ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias); + ExpectedDecl VisitTypedefDecl(TypedefDecl *D); + ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D); + ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); + ExpectedDecl VisitLabelDecl(LabelDecl *D); + ExpectedDecl VisitEnumDecl(EnumDecl *D); + ExpectedDecl VisitRecordDecl(RecordDecl *D); + ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D); + ExpectedDecl VisitFunctionDecl(FunctionDecl *D); + ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D); + ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D); + ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D); + ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D); + ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D); + ExpectedDecl VisitFieldDecl(FieldDecl *D); + ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D); + ExpectedDecl VisitFriendDecl(FriendDecl *D); + ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D); + ExpectedDecl VisitVarDecl(VarDecl *D); + ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D); + ExpectedDecl VisitParmVarDecl(ParmVarDecl *D); + ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D); + ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); + ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D); + ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D); + ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D); + ExpectedDecl VisitUsingDecl(UsingDecl *D); + ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D); + ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D); + ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI); + ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D); + ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); + ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); + ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D); + ExpectedDecl + VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D); + + Expected + ImportObjCTypeParamList(ObjCTypeParamList *list); + + ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); + ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); + ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D); + ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D); + ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); + ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); + ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); + ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); + ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D); + ExpectedDecl + VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D); + ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D); + ExpectedDecl + VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D); + ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D); + + // Importing statements + ExpectedStmt VisitStmt(Stmt *S); + ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S); + ExpectedStmt VisitDeclStmt(DeclStmt *S); + ExpectedStmt VisitNullStmt(NullStmt *S); + ExpectedStmt VisitCompoundStmt(CompoundStmt *S); + ExpectedStmt VisitCaseStmt(CaseStmt *S); + ExpectedStmt VisitDefaultStmt(DefaultStmt *S); + ExpectedStmt VisitLabelStmt(LabelStmt *S); + ExpectedStmt VisitAttributedStmt(AttributedStmt *S); + ExpectedStmt VisitIfStmt(IfStmt *S); + ExpectedStmt VisitSwitchStmt(SwitchStmt *S); + ExpectedStmt VisitWhileStmt(WhileStmt *S); + ExpectedStmt VisitDoStmt(DoStmt *S); + ExpectedStmt VisitForStmt(ForStmt *S); + ExpectedStmt VisitGotoStmt(GotoStmt *S); + ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S); + ExpectedStmt VisitContinueStmt(ContinueStmt *S); + ExpectedStmt VisitBreakStmt(BreakStmt *S); + ExpectedStmt VisitReturnStmt(ReturnStmt *S); + // FIXME: MSAsmStmt + // FIXME: SEHExceptStmt + // FIXME: SEHFinallyStmt + // FIXME: SEHTryStmt + // FIXME: SEHLeaveStmt + // FIXME: CapturedStmt + ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S); + ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S); + ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S); + // FIXME: MSDependentExistsStmt + ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); + ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); + ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S); + ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S); + ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); + ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); + ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); + + // Importing expressions + ExpectedStmt VisitExpr(Expr *E); + ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E); + ExpectedStmt VisitVAArgExpr(VAArgExpr *E); + ExpectedStmt VisitChooseExpr(ChooseExpr *E); + ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E); + ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E); + ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E); + ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E); + ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); + ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E); + ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E); + ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E); + ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E); + ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E); + ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E); + ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E); + ExpectedStmt VisitStringLiteral(StringLiteral *E); + ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E); + ExpectedStmt VisitAtomicExpr(AtomicExpr *E); + ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E); + ExpectedStmt VisitConstantExpr(ConstantExpr *E); + ExpectedStmt VisitParenExpr(ParenExpr *E); + ExpectedStmt VisitParenListExpr(ParenListExpr *E); + ExpectedStmt VisitStmtExpr(StmtExpr *E); + ExpectedStmt VisitUnaryOperator(UnaryOperator *E); + ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); + ExpectedStmt VisitBinaryOperator(BinaryOperator *E); + ExpectedStmt VisitConditionalOperator(ConditionalOperator *E); + ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E); + ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E); + ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E); + ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E); + ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E); + ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E); + ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E); + ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E); + ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE); + ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E); + ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E); + ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E); + ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); + ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); + ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); + ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); + ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E); + ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E); + ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E); + ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E); + ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E); + ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E); + ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); + ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); + ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); + ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E); + ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E); + ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E); + ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E); + ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E); + ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); + ExpectedStmt VisitMemberExpr(MemberExpr *E); + ExpectedStmt VisitCallExpr(CallExpr *E); + ExpectedStmt VisitLambdaExpr(LambdaExpr *LE); + ExpectedStmt VisitInitListExpr(InitListExpr *E); + ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E); + ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E); + ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E); + ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E); + ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E); + ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E); + ExpectedStmt + VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E); + ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E); + ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E); + ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E); + + template + Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) { + using ItemT = std::remove_reference_t; + for (; Ibegin != Iend; ++Ibegin, ++Obegin) { + Expected ToOrErr = import(*Ibegin); + if (!ToOrErr) + return ToOrErr.takeError(); + *Obegin = *ToOrErr; } + return Error::success(); + } - // Import every item from a container structure into an output container. - // If error occurs, stops at first error and returns the error. - // The output container should have space for all needed elements (it is not - // expanded, new items are put into from the beginning). - template - Error ImportContainerChecked( - const InContainerTy &InContainer, OutContainerTy &OutContainer) { - return ImportArrayChecked( - InContainer.begin(), InContainer.end(), OutContainer.begin()); - } + // Import every item from a container structure into an output container. + // If error occurs, stops at first error and returns the error. + // The output container should have space for all needed elements (it is not + // expanded, new items are put into from the beginning). + template + Error ImportContainerChecked(InContainerTy const &InContainer, + OutContainerTy &OutContainer) { + return ImportArrayChecked(InContainer.begin(), InContainer.end(), + OutContainer.begin()); + } - template - Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) { - return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin); - } + template + Error ImportArrayChecked(InContainerTy const &InContainer, OIter Obegin) { + return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin); + } - Error ImportOverriddenMethods(CXXMethodDecl *ToMethod, - CXXMethodDecl *FromMethod); + Error ImportOverriddenMethods(CXXMethodDecl *ToMethod, + CXXMethodDecl *FromMethod); - Expected FindFunctionTemplateSpecialization( - FunctionDecl *FromFD); + Expected + FindFunctionTemplateSpecialization(FunctionDecl *FromFD); - // Returns true if the given function has a placeholder return type and - // that type is declared inside the body of the function. - // E.g. auto f() { struct X{}; return X(); } - bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D); - }; + // Returns true if the given function has a placeholder return type and + // that type is declared inside the body of the function. + // E.g. auto f() { struct X{}; return X(); } + bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D); +}; template Error ASTNodeImporter::ImportTemplateArgumentListInfo( SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, - const InContainerTy &Container, TemplateArgumentListInfo &Result) { + InContainerTy const &Container, TemplateArgumentListInfo &Result) { auto ToLAngleLocOrErr = import(FromLAngleLoc); if (!ToLAngleLocOrErr) return ToLAngleLocOrErr.takeError(); @@ -729,25 +719,24 @@ template <> Error ASTNodeImporter::ImportTemplateArgumentListInfo( - const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) { + TemplateArgumentListInfo const &From, TemplateArgumentListInfo &Result) { return ImportTemplateArgumentListInfo( From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result); } template <> Error ASTNodeImporter::ImportTemplateArgumentListInfo< - ASTTemplateArgumentListInfo>( - const ASTTemplateArgumentListInfo &From, - TemplateArgumentListInfo &Result) { - return ImportTemplateArgumentListInfo( - From.LAngleLoc, From.RAngleLoc, From.arguments(), Result); + ASTTemplateArgumentListInfo>(ASTTemplateArgumentListInfo const &From, + TemplateArgumentListInfo &Result) { + return ImportTemplateArgumentListInfo(From.LAngleLoc, From.RAngleLoc, + From.arguments(), Result); } Expected ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( FunctionDecl *FromFD) { assert(FromFD->getTemplatedKind() == - FunctionDecl::TK_FunctionTemplateSpecialization); + FunctionDecl::TK_FunctionTemplateSpecialization); FunctionTemplateAndArgsTy Result; @@ -758,7 +747,7 @@ // Import template arguments. auto TemplArgs = FTSInfo->TemplateArguments->asArray(); if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), - std::get<1>(Result))) + std::get<1>(Result))) return std::move(Err); return Result; @@ -786,17 +775,13 @@ return ToRAngleLocOrErr.takeError(); return TemplateParameterList::Create( - Importer.getToContext(), - *ToTemplateLocOrErr, - *ToLAngleLocOrErr, - To, - *ToRAngleLocOrErr, - *ToRequiresClause); + Importer.getToContext(), *ToTemplateLocOrErr, *ToLAngleLocOrErr, To, + *ToRAngleLocOrErr, *ToRequiresClause); } template <> Expected -ASTNodeImporter::import(const TemplateArgument &From) { +ASTNodeImporter::import(TemplateArgument const &From) { switch (From.getKind()) { case TemplateArgument::Null: return TemplateArgument(); @@ -829,7 +814,7 @@ ExpectedType ToTypeOrErr = import(From.getNullPtrType()); if (!ToTypeOrErr) return ToTypeOrErr.takeError(); - return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true); + return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ true); } case TemplateArgument::Template: { @@ -846,8 +831,7 @@ if (!ToTemplateOrErr) return ToTemplateOrErr.takeError(); - return TemplateArgument( - *ToTemplateOrErr, From.getNumTemplateExpansions()); + return TemplateArgument(*ToTemplateOrErr, From.getNumTemplateExpansions()); } case TemplateArgument::Expression: @@ -859,8 +843,8 @@ case TemplateArgument::Pack: { SmallVector ToPack; ToPack.reserve(From.pack_size()); - if (Error Err = ImportTemplateArguments( - From.pack_begin(), From.pack_size(), ToPack)) + if (Error Err = ImportTemplateArguments(From.pack_begin(), From.pack_size(), + ToPack)) return std::move(Err); return TemplateArgument( @@ -873,7 +857,7 @@ template <> Expected -ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) { +ASTNodeImporter::import(TemplateArgumentLoc const &TALoc) { Expected ArgOrErr = import(TALoc.getArgument()); if (!ArgOrErr) return ArgOrErr.takeError(); @@ -900,8 +884,7 @@ auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc()); if (!ToTemplateNameLocOrErr) return ToTemplateNameLocOrErr.takeError(); - auto ToTemplateEllipsisLocOrErr = - import(FromInfo.getTemplateEllipsisLoc()); + auto ToTemplateEllipsisLocOrErr = import(FromInfo.getTemplateEllipsisLoc()); if (!ToTemplateEllipsisLocOrErr) return ToTemplateEllipsisLocOrErr.takeError(); ToInfo = TemplateArgumentLocInfo( @@ -913,7 +896,7 @@ } template <> -Expected ASTNodeImporter::import(const DeclGroupRef &DG) { +Expected ASTNodeImporter::import(DeclGroupRef const &DG) { if (DG.isNull()) return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0); size_t NumDecls = DG.end() - DG.begin(); @@ -925,14 +908,13 @@ else return ToDOrErr.takeError(); } - return DeclGroupRef::Create(Importer.getToContext(), - ToDecls.begin(), + return DeclGroupRef::Create(Importer.getToContext(), ToDecls.begin(), NumDecls); } template <> Expected -ASTNodeImporter::import(const Designator &D) { +ASTNodeImporter::import(Designator const &D) { if (D.isFieldDesignator()) { IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName()); @@ -956,21 +938,20 @@ return ToRBracketLocOrErr.takeError(); if (D.isArrayDesignator()) - return Designator(D.getFirstExprIndex(), - *ToLBracketLocOrErr, *ToRBracketLocOrErr); + return Designator(D.getFirstExprIndex(), *ToLBracketLocOrErr, + *ToRBracketLocOrErr); ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc()); if (!ToEllipsisLocOrErr) return ToEllipsisLocOrErr.takeError(); assert(D.isArrayRangeDesignator()); - return Designator( - D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr, - *ToRBracketLocOrErr); + return Designator(D.getFirstExprIndex(), *ToLBracketLocOrErr, + *ToEllipsisLocOrErr, *ToRBracketLocOrErr); } template <> -Expected ASTNodeImporter::import(const LambdaCapture &From) { +Expected ASTNodeImporter::import(LambdaCapture const &From) { VarDecl *Var = nullptr; if (From.capturesVariable()) { if (auto VarOrErr = import(From.getCapturedVar())) @@ -988,9 +969,8 @@ if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc())) return std::move(Err); - return LambdaCapture( - *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var, - EllipsisLoc); + return LambdaCapture(*LocationOrErr, From.isImplicit(), From.getCaptureKind(), + Var, EllipsisLoc); } template @@ -1010,8 +990,8 @@ } template <> -bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found, - TypedefNameDecl *From) { +bool ASTNodeImporter::hasSameVisibilityContextAndLinkage( + TypedefNameDecl *Found, TypedefNameDecl *From) { if (Found->getLinkageInternal() != From->getLinkageInternal()) return false; @@ -1028,13 +1008,13 @@ using namespace clang; -ExpectedType ASTNodeImporter::VisitType(const Type *T) { +ExpectedType ASTNodeImporter::VisitType(Type const *T) { Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node) - << T->getTypeClassName(); + << T->getTypeClassName(); return make_error(ImportError::UnsupportedConstruct); } -ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){ +ExpectedType ASTNodeImporter::VisitAtomicType(AtomicType const *T) { ExpectedType UnderlyingTypeOrErr = import(T->getValueType()); if (!UnderlyingTypeOrErr) return UnderlyingTypeOrErr.takeError(); @@ -1042,22 +1022,22 @@ return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr); } -ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) { +ExpectedType ASTNodeImporter::VisitBuiltinType(BuiltinType const *T) { switch (T->getKind()) { -#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ - case BuiltinType::Id: \ +#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ + case BuiltinType::Id: \ return Importer.getToContext().SingletonId; #include "clang/Basic/OpenCLImageTypes.def" -#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ - case BuiltinType::Id: \ +#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ + case BuiltinType::Id: \ return Importer.getToContext().Id##Ty; #include "clang/Basic/OpenCLExtensionTypes.def" -#define SVE_TYPE(Name, Id, SingletonId) \ - case BuiltinType::Id: \ +#define SVE_TYPE(Name, Id, SingletonId) \ + case BuiltinType::Id: \ return Importer.getToContext().SingletonId; #include "clang/Basic/AArch64SVEACLETypes.def" -#define PPC_VECTOR_TYPE(Name, Id, Size) \ - case BuiltinType::Id: \ +#define PPC_VECTOR_TYPE(Name, Id, Size) \ + case BuiltinType::Id: \ return Importer.getToContext().Id##Ty; #include "clang/Basic/PPCTypes.def" #define RVV_TYPE(Name, Id, SingletonId) \ @@ -1065,15 +1045,16 @@ return Importer.getToContext().SingletonId; #include "clang/Basic/RISCVVTypes.def" #define SHARED_SINGLETON_TYPE(Expansion) -#define BUILTIN_TYPE(Id, SingletonId) \ - case BuiltinType::Id: return Importer.getToContext().SingletonId; +#define BUILTIN_TYPE(Id, SingletonId) \ + case BuiltinType::Id: \ + return Importer.getToContext().SingletonId; #include "clang/AST/BuiltinTypes.def" - // FIXME: for Char16, Char32, and NullPtr, make sure that the "to" - // context supports C++. + // FIXME: for Char16, Char32, and NullPtr, make sure that the "to" + // context supports C++. - // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to" - // context supports ObjC. + // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to" + // context supports ObjC. case BuiltinType::Char_U: // The context we're importing from has an unsigned 'char'. If we're @@ -1103,7 +1084,7 @@ llvm_unreachable("Invalid BuiltinType Kind!"); } -ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) { +ExpectedType ASTNodeImporter::VisitDecayedType(DecayedType const *T) { ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType()); if (!ToOriginalTypeOrErr) return ToOriginalTypeOrErr.takeError(); @@ -1111,7 +1092,7 @@ return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr); } -ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) { +ExpectedType ASTNodeImporter::VisitComplexType(ComplexType const *T) { ExpectedType ToElementTypeOrErr = import(T->getElementType()); if (!ToElementTypeOrErr) return ToElementTypeOrErr.takeError(); @@ -1119,7 +1100,7 @@ return Importer.getToContext().getComplexType(*ToElementTypeOrErr); } -ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) { +ExpectedType ASTNodeImporter::VisitPointerType(PointerType const *T) { ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); if (!ToPointeeTypeOrErr) return ToPointeeTypeOrErr.takeError(); @@ -1127,7 +1108,7 @@ return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr); } -ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) { +ExpectedType ASTNodeImporter::VisitBlockPointerType(BlockPointerType const *T) { // FIXME: Check for blocks support in "to" context. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); if (!ToPointeeTypeOrErr) @@ -1137,7 +1118,7 @@ } ExpectedType -ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) { +ASTNodeImporter::VisitLValueReferenceType(LValueReferenceType const *T) { // FIXME: Check for C++ support in "to" context. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); if (!ToPointeeTypeOrErr) @@ -1147,7 +1128,7 @@ } ExpectedType -ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) { +ASTNodeImporter::VisitRValueReferenceType(RValueReferenceType const *T) { // FIXME: Check for C++0x support in "to" context. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); if (!ToPointeeTypeOrErr) @@ -1157,7 +1138,7 @@ } ExpectedType -ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { +ASTNodeImporter::VisitMemberPointerType(MemberPointerType const *T) { // FIXME: Check for C++ support in "to" context. ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); if (!ToPointeeTypeOrErr) @@ -1172,7 +1153,7 @@ } ExpectedType -ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) { +ASTNodeImporter::VisitConstantArrayType(ConstantArrayType const *T) { Error Err = Error::success(); auto ToElementType = importChecked(Err, T->getElementType()); auto ToSizeExpr = importChecked(Err, T->getSizeExpr()); @@ -1185,18 +1166,18 @@ } ExpectedType -ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) { +ASTNodeImporter::VisitIncompleteArrayType(IncompleteArrayType const *T) { ExpectedType ToElementTypeOrErr = import(T->getElementType()); if (!ToElementTypeOrErr) return ToElementTypeOrErr.takeError(); - return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr, - T->getSizeModifier(), - T->getIndexTypeCVRQualifiers()); + return Importer.getToContext().getIncompleteArrayType( + *ToElementTypeOrErr, T->getSizeModifier(), + T->getIndexTypeCVRQualifiers()); } ExpectedType -ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) { +ASTNodeImporter::VisitVariableArrayType(VariableArrayType const *T) { Error Err = Error::success(); QualType ToElementType = importChecked(Err, T->getElementType()); Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr()); @@ -1209,7 +1190,7 @@ } ExpectedType ASTNodeImporter::VisitDependentSizedArrayType( - const DependentSizedArrayType *T) { + DependentSizedArrayType const *T) { Error Err = Error::success(); QualType ToElementType = importChecked(Err, T->getElementType()); Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr()); @@ -1224,17 +1205,16 @@ T->getIndexTypeCVRQualifiers(), ToBracketsRange); } -ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) { +ExpectedType ASTNodeImporter::VisitVectorType(VectorType const *T) { ExpectedType ToElementTypeOrErr = import(T->getElementType()); if (!ToElementTypeOrErr) return ToElementTypeOrErr.takeError(); - return Importer.getToContext().getVectorType(*ToElementTypeOrErr, - T->getNumElements(), - T->getVectorKind()); + return Importer.getToContext().getVectorType( + *ToElementTypeOrErr, T->getNumElements(), T->getVectorKind()); } -ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) { +ExpectedType ASTNodeImporter::VisitExtVectorType(ExtVectorType const *T) { ExpectedType ToElementTypeOrErr = import(T->getElementType()); if (!ToElementTypeOrErr) return ToElementTypeOrErr.takeError(); @@ -1244,7 +1224,7 @@ } ExpectedType -ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { +ASTNodeImporter::VisitFunctionNoProtoType(FunctionNoProtoType const *T) { // FIXME: What happens if we're importing a function without a prototype // into C++? Should we make it variadic? ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); @@ -1256,14 +1236,14 @@ } ExpectedType -ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { +ASTNodeImporter::VisitFunctionProtoType(FunctionProtoType const *T) { ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); if (!ToReturnTypeOrErr) return ToReturnTypeOrErr.takeError(); // Import argument types SmallVector ArgTypes; - for (const auto &A : T->param_types()) { + for (auto const &A : T->param_types()) { ExpectedType TyOrErr = import(A); if (!TyOrErr) return TyOrErr.takeError(); @@ -1272,7 +1252,7 @@ // Import exception types SmallVector ExceptionTypes; - for (const auto &E : T->exceptions()) { + for (auto const &E : T->exceptions()) { ExpectedType TyOrErr = import(E); if (!TyOrErr) return TyOrErr.takeError(); @@ -1299,12 +1279,12 @@ if (Err) return std::move(Err); - return Importer.getToContext().getFunctionType( - *ToReturnTypeOrErr, ArgTypes, ToEPI); + return Importer.getToContext().getFunctionType(*ToReturnTypeOrErr, ArgTypes, + ToEPI); } -ExpectedType ASTNodeImporter::VisitUnresolvedUsingType( - const UnresolvedUsingType *T) { +ExpectedType +ASTNodeImporter::VisitUnresolvedUsingType(UnresolvedUsingType const *T) { Error Err = Error::success(); auto ToD = importChecked(Err, T->getDecl()); auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl()); @@ -1315,7 +1295,7 @@ ToD, cast_or_null(ToPrevD)); } -ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) { +ExpectedType ASTNodeImporter::VisitParenType(ParenType const *T) { ExpectedType ToInnerTypeOrErr = import(T->getInnerType()); if (!ToInnerTypeOrErr) return ToInnerTypeOrErr.takeError(); @@ -1323,7 +1303,7 @@ return Importer.getToContext().getParenType(*ToInnerTypeOrErr); } -ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { +ExpectedType ASTNodeImporter::VisitTypedefType(TypedefType const *T) { Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) return ToDeclOrErr.takeError(); @@ -1331,7 +1311,7 @@ return Importer.getToContext().getTypeDeclType(*ToDeclOrErr); } -ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { +ExpectedType ASTNodeImporter::VisitTypeOfExprType(TypeOfExprType const *T) { ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); if (!ToExprOrErr) return ToExprOrErr.takeError(); @@ -1339,7 +1319,7 @@ return Importer.getToContext().getTypeOfExprType(*ToExprOrErr); } -ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) { +ExpectedType ASTNodeImporter::VisitTypeOfType(TypeOfType const *T) { ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); if (!ToUnderlyingTypeOrErr) return ToUnderlyingTypeOrErr.takeError(); @@ -1347,7 +1327,7 @@ return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr); } -ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) { +ExpectedType ASTNodeImporter::VisitDecltypeType(DecltypeType const *T) { // FIXME: Make sure that the "to" context supports C++0x! ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); if (!ToExprOrErr) @@ -1357,12 +1337,12 @@ if (!ToUnderlyingTypeOrErr) return ToUnderlyingTypeOrErr.takeError(); - return Importer.getToContext().getDecltypeType( - *ToExprOrErr, *ToUnderlyingTypeOrErr); + return Importer.getToContext().getDecltypeType(*ToExprOrErr, + *ToUnderlyingTypeOrErr); } ExpectedType -ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) { +ASTNodeImporter::VisitUnaryTransformType(UnaryTransformType const *T) { ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); if (!ToBaseTypeOrErr) return ToBaseTypeOrErr.takeError(); @@ -1375,7 +1355,7 @@ *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind()); } -ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) { +ExpectedType ASTNodeImporter::VisitAutoType(AutoType const *T) { // FIXME: Make sure that the "to" context supports C++11! ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType()); if (!ToDeducedTypeOrErr) @@ -1387,19 +1367,18 @@ SmallVector ToTemplateArgs; ArrayRef FromTemplateArgs = T->getTypeConstraintArguments(); - if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(), - FromTemplateArgs.size(), - ToTemplateArgs)) + if (Error Err = ImportTemplateArguments( + FromTemplateArgs.data(), FromTemplateArgs.size(), ToTemplateArgs)) return std::move(Err); return Importer.getToContext().getAutoType( - *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false, + *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/ false, /*IsPack=*/false, cast_or_null(*ToTypeConstraintConcept), ToTemplateArgs); } ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType( - const DeducedTemplateSpecializationType *T) { + DeducedTemplateSpecializationType const *T) { // FIXME: Make sure that the "to" context supports C++17! Expected ToTemplateNameOrErr = import(T->getTemplateName()); if (!ToTemplateNameOrErr) @@ -1412,8 +1391,8 @@ *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType()); } -ExpectedType ASTNodeImporter::VisitInjectedClassNameType( - const InjectedClassNameType *T) { +ExpectedType +ASTNodeImporter::VisitInjectedClassNameType(InjectedClassNameType const *T) { Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) return ToDeclOrErr.takeError(); @@ -1425,16 +1404,14 @@ // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading // See comments in InjectedClassNameType definition for details // return Importer.getToContext().getInjectedClassNameType(D, InjType); - enum { - TypeAlignmentInBits = 4, - TypeAlignment = 1 << TypeAlignmentInBits - }; + enum { TypeAlignmentInBits = 4, TypeAlignment = 1 << TypeAlignmentInBits }; return QualType(new (Importer.getToContext(), TypeAlignment) - InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0); + InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), + 0); } -ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) { +ExpectedType ASTNodeImporter::VisitRecordType(RecordType const *T) { Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) return ToDeclOrErr.takeError(); @@ -1442,7 +1419,7 @@ return Importer.getToContext().getTagDeclType(*ToDeclOrErr); } -ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) { +ExpectedType ASTNodeImporter::VisitEnumType(EnumType const *T) { Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) return ToDeclOrErr.takeError(); @@ -1450,7 +1427,7 @@ return Importer.getToContext().getTagDeclType(*ToDeclOrErr); } -ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) { +ExpectedType ASTNodeImporter::VisitAttributedType(AttributedType const *T) { ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType()); if (!ToModifiedTypeOrErr) return ToModifiedTypeOrErr.takeError(); @@ -1458,12 +1435,12 @@ if (!ToEquivalentTypeOrErr) return ToEquivalentTypeOrErr.takeError(); - return Importer.getToContext().getAttributedType(T->getAttrKind(), - *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr); + return Importer.getToContext().getAttributedType( + T->getAttrKind(), *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr); } -ExpectedType ASTNodeImporter::VisitTemplateTypeParmType( - const TemplateTypeParmType *T) { +ExpectedType +ASTNodeImporter::VisitTemplateTypeParmType(TemplateTypeParmType const *T) { Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) return ToDeclOrErr.takeError(); @@ -1473,11 +1450,11 @@ } ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType( - const SubstTemplateTypeParmType *T) { + SubstTemplateTypeParmType const *T) { ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0)); if (!ReplacedOrErr) return ReplacedOrErr.takeError(); - const TemplateTypeParmType *Replaced = + TemplateTypeParmType const *Replaced = cast((*ReplacedOrErr).getTypePtr()); ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType()); @@ -1485,15 +1462,15 @@ return ToReplacementTypeOrErr.takeError(); return Importer.getToContext().getSubstTemplateTypeParmType( - Replaced, (*ToReplacementTypeOrErr).getCanonicalType()); + Replaced, (*ToReplacementTypeOrErr).getCanonicalType()); } ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType( - const SubstTemplateTypeParmPackType *T) { + SubstTemplateTypeParmPackType const *T) { ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0)); if (!ReplacedOrErr) return ReplacedOrErr.takeError(); - const TemplateTypeParmType *Replaced = + TemplateTypeParmType const *Replaced = cast(ReplacedOrErr->getTypePtr()); Expected ToArgumentPack = import(T->getArgumentPack()); @@ -1505,31 +1482,30 @@ } ExpectedType ASTNodeImporter::VisitTemplateSpecializationType( - const TemplateSpecializationType *T) { + TemplateSpecializationType const *T) { auto ToTemplateOrErr = import(T->getTemplateName()); if (!ToTemplateOrErr) return ToTemplateOrErr.takeError(); SmallVector ToTemplateArgs; - if (Error Err = ImportTemplateArguments( - T->getArgs(), T->getNumArgs(), ToTemplateArgs)) + if (Error Err = ImportTemplateArguments(T->getArgs(), T->getNumArgs(), + ToTemplateArgs)) return std::move(Err); QualType ToCanonType; if (!QualType(T, 0).isCanonical()) { - QualType FromCanonType - = Importer.getFromContext().getCanonicalType(QualType(T, 0)); + QualType FromCanonType = + Importer.getFromContext().getCanonicalType(QualType(T, 0)); if (ExpectedType TyOrErr = import(FromCanonType)) ToCanonType = *TyOrErr; else return TyOrErr.takeError(); } - return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr, - ToTemplateArgs, - ToCanonType); + return Importer.getToContext().getTemplateSpecializationType( + *ToTemplateOrErr, ToTemplateArgs, ToCanonType); } -ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) { +ExpectedType ASTNodeImporter::VisitElaboratedType(ElaboratedType const *T) { // Note: the qualifier in an ElaboratedType is optional. auto ToQualifierOrErr = import(T->getQualifier()); if (!ToQualifierOrErr) @@ -1543,14 +1519,13 @@ if (!ToOwnedTagDeclOrErr) return ToOwnedTagDeclOrErr.takeError(); - return Importer.getToContext().getElaboratedType(T->getKeyword(), - *ToQualifierOrErr, - *ToNamedTypeOrErr, - *ToOwnedTagDeclOrErr); + return Importer.getToContext().getElaboratedType( + T->getKeyword(), *ToQualifierOrErr, *ToNamedTypeOrErr, + *ToOwnedTagDeclOrErr); } ExpectedType -ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) { +ASTNodeImporter::VisitPackExpansionType(PackExpansionType const *T) { ExpectedType ToPatternOrErr = import(T->getPattern()); if (!ToPatternOrErr) return ToPatternOrErr.takeError(); @@ -1561,7 +1536,7 @@ } ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType( - const DependentTemplateSpecializationType *T) { + DependentTemplateSpecializationType const *T) { auto ToQualifierOrErr = import(T->getQualifier()); if (!ToQualifierOrErr) return ToQualifierOrErr.takeError(); @@ -1570,8 +1545,8 @@ SmallVector ToPack; ToPack.reserve(T->getNumArgs()); - if (Error Err = ImportTemplateArguments( - T->getArgs(), T->getNumArgs(), ToPack)) + if (Error Err = + ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToPack)) return std::move(Err); return Importer.getToContext().getDependentTemplateSpecializationType( @@ -1579,7 +1554,7 @@ } ExpectedType -ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) { +ASTNodeImporter::VisitDependentNameType(DependentNameType const *T) { auto ToQualifierOrErr = import(T->getQualifier()); if (!ToQualifierOrErr) return ToQualifierOrErr.takeError(); @@ -1594,13 +1569,12 @@ return TyOrErr.takeError(); } - return Importer.getToContext().getDependentNameType(T->getKeyword(), - *ToQualifierOrErr, - Name, Canon); + return Importer.getToContext().getDependentNameType( + T->getKeyword(), *ToQualifierOrErr, Name, Canon); } ExpectedType -ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { +ASTNodeImporter::VisitObjCInterfaceType(ObjCInterfaceType const *T) { Expected ToDeclOrErr = import(T->getDecl()); if (!ToDeclOrErr) return ToDeclOrErr.takeError(); @@ -1608,7 +1582,7 @@ return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr); } -ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) { +ExpectedType ASTNodeImporter::VisitObjCObjectType(ObjCObjectType const *T) { ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); if (!ToBaseTypeOrErr) return ToBaseTypeOrErr.takeError(); @@ -1627,16 +1601,14 @@ Protocols.push_back(*ProtocolOrErr); else return ProtocolOrErr.takeError(); - } - return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs, - Protocols, - T->isKindOfTypeAsWritten()); + return Importer.getToContext().getObjCObjectType( + *ToBaseTypeOrErr, TypeArgs, Protocols, T->isKindOfTypeAsWritten()); } ExpectedType -ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { +ASTNodeImporter::VisitObjCObjectPointerType(ObjCObjectPointerType const *T) { ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); if (!ToPointeeTypeOrErr) return ToPointeeTypeOrErr.takeError(); @@ -1647,9 +1619,10 @@ //---------------------------------------------------------------------------- // Import Declarations //---------------------------------------------------------------------------- -Error ASTNodeImporter::ImportDeclParts( - NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, - DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) { +Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, + DeclContext *&LexicalDC, + DeclarationName &Name, NamedDecl *&ToD, + SourceLocation &Loc) { // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop. // example: int struct_in_proto(struct data_t{int a;int b;} *d); // FIXME: We could support these constructs by importing a different type of @@ -1660,14 +1633,14 @@ FunctionDecl *FunDecl; if (isa(D) && (FunDecl = dyn_cast(OrigDC)) && FunDecl->hasBody()) { - auto getLeafPointeeType = [](const Type *T) { + auto getLeafPointeeType = [](Type const *T) { while (T->isPointerType() || T->isArrayType()) { T = T->getPointeeOrArrayElementType(); } return T; }; - for (const ParmVarDecl *P : FunDecl->parameters()) { - const Type *LeafT = + for (ParmVarDecl const *P : FunDecl->parameters()) { + Type const *LeafT = getLeafPointeeType(P->getType().getCanonicalType().getTypePtr()); auto *RT = dyn_cast(LeafT); if (RT && RT->getDecl() == D) { @@ -1749,9 +1722,8 @@ return Error::success(); } -Error -ASTNodeImporter::ImportDeclarationNameLoc( - const DeclarationNameInfo &From, DeclarationNameInfo& To) { +Error ASTNodeImporter::ImportDeclarationNameLoc(DeclarationNameInfo const &From, + DeclarationNameInfo &To) { // NOTE: To.Name and To.Loc are already imported. // We only have to import To.LocInfo. switch (To.getName().getNameKind()) { @@ -1790,8 +1762,8 @@ llvm_unreachable("Unknown name kind."); } -Error -ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { +Error ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, + bool ForceImport) { if (Importer.isMinimalImport() && !ForceImport) { auto ToDCOrErr = Importer.ImportContext(FromDC); return ToDCOrErr.takeError(); @@ -1826,15 +1798,19 @@ // If we have a field that is an ArrayType we need to check if the array // element is a RecordDecl and if so we need to import the defintion. if (FieldFrom->getType()->isArrayType()) { - // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us. - FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl(); - ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl(); + // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for + // us. + FromRecordDecl = FieldFrom->getType() + ->getBaseElementTypeUnsafe() + ->getAsRecordDecl(); + ToRecordDecl = + FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl(); } if (!FromRecordDecl || !ToRecordDecl) { - const RecordType *RecordFrom = + RecordType const *RecordFrom = FieldFrom->getType()->getAs(); - const RecordType *RecordTo = FieldTo->getType()->getAs(); + RecordType const *RecordTo = FieldTo->getType()->getAs(); if (RecordFrom && RecordTo) { FromRecordDecl = RecordFrom->getDecl(); @@ -1848,7 +1824,7 @@ Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl); if (Err && AccumulateChildErrors) - ChildErrors = joinErrors(std::move(ChildErrors), std::move(Err)); + ChildErrors = joinErrors(std::move(ChildErrors), std::move(Err)); else consumeError(std::move(Err)); } @@ -1886,7 +1862,7 @@ // interface in LLDB is implemented by the means of the ASTImporter. However, // calling an import at this point would result in an uncontrolled import, we // must avoid that. - const auto *FromRD = dyn_cast(FromDC); + auto const *FromRD = dyn_cast(FromDC); if (!FromRD) return ChildErrors; @@ -1919,16 +1895,16 @@ return ChildErrors; } -Error ASTNodeImporter::ImportDeclContext( - Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) { +Error ASTNodeImporter::ImportDeclContext(Decl *FromD, DeclContext *&ToDC, + DeclContext *&ToLexicalDC) { auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext()); if (!ToDCOrErr) return ToDCOrErr.takeError(); ToDC = *ToDCOrErr; if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) { - auto ToLexicalDCOrErr = Importer.ImportContext( - FromD->getLexicalDeclContext()); + auto ToLexicalDCOrErr = + Importer.ImportContext(FromD->getLexicalDeclContext()); if (!ToLexicalDCOrErr) return ToLexicalDCOrErr.takeError(); ToLexicalDC = *ToLexicalDCOrErr; @@ -1938,10 +1914,10 @@ return Error::success(); } -Error ASTNodeImporter::ImportImplicitMethods( - const CXXRecordDecl *From, CXXRecordDecl *To) { +Error ASTNodeImporter::ImportImplicitMethods(CXXRecordDecl const *From, + CXXRecordDecl *To) { assert(From->isCompleteDefinition() && To->getDefinition() == To && - "Import implicit methods to or from non-definition"); + "Import implicit methods to or from non-definition"); for (CXXMethodDecl *FromM : From->methods()) if (FromM->isImplicit()) { @@ -1964,8 +1940,8 @@ return Error::success(); } -Error ASTNodeImporter::ImportDefinition( - RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) { +Error ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, + ImportDefinitionKind Kind) { auto DefinitionCompleter = [To]() { // There are cases in LLDB when we first import a class without its // members. The class will have DefinitionData, but no members. Then, @@ -1988,7 +1964,7 @@ auto *FromCXXRD = cast(From); SmallVector ToCaptures; ToCaptures.reserve(FromCXXRD->capture_size()); - for (const auto &FromCapture : FromCXXRD->captures()) { + for (auto const &FromCapture : FromCXXRD->captures()) { if (auto ToCaptureOrErr = import(FromCapture)) ToCaptures.push_back(*ToCaptureOrErr); else @@ -2026,15 +2002,14 @@ struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data(); struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data(); - #define FIELD(Name, Width, Merge) \ - ToData.Name = FromData.Name; - #include "clang/AST/CXXRecordDeclDefinitionBits.def" +#define FIELD(Name, Width, Merge) ToData.Name = FromData.Name; +#include "clang/AST/CXXRecordDeclDefinitionBits.def" // Copy over the data stored in RecordDeclBits ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions()); SmallVector Bases; - for (const auto &Base1 : FromCXX->bases()) { + for (auto const &Base1 : FromCXX->bases()) { ExpectedType TyOrErr = import(Base1.getType()); if (!TyOrErr) return TyOrErr.takeError(); @@ -2049,7 +2024,7 @@ // Ensure that we have a definition for the base. if (Error Err = - ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl())) + ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl())) return Err; auto RangeOrErr = import(Base1.getSourceRange()); @@ -2060,14 +2035,9 @@ if (!TSIOrErr) return TSIOrErr.takeError(); - Bases.push_back( - new (Importer.getToContext()) CXXBaseSpecifier( - *RangeOrErr, - Base1.isVirtual(), - Base1.isBaseOfClass(), - Base1.getAccessSpecifierAsWritten(), - *TSIOrErr, - EllipsisLoc)); + Bases.push_back(new (Importer.getToContext()) CXXBaseSpecifier( + *RangeOrErr, Base1.isVirtual(), Base1.isBaseOfClass(), + Base1.getAccessSpecifierAsWritten(), *TSIOrErr, EllipsisLoc)); } if (!Bases.empty()) ToCXX->setBases(Bases.data(), Bases.size()); @@ -2104,8 +2074,8 @@ return Error::success(); } -Error ASTNodeImporter::ImportDefinition( - EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) { +Error ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, + ImportDefinitionKind Kind) { if (To->getDefinition() || To->isBeingDefined()) { if (Kind == IDK_Everything) return ImportDeclContext(From, /*ForceImport=*/true); @@ -2139,7 +2109,7 @@ } Error ASTNodeImporter::ImportTemplateArguments( - const TemplateArgument *FromArgs, unsigned NumFromArgs, + TemplateArgument const *FromArgs, unsigned NumFromArgs, SmallVectorImpl &ToArgs) { for (unsigned I = 0; I != NumFromArgs; ++I) { if (auto ToOrErr = import(FromArgs[I])) @@ -2153,14 +2123,14 @@ // FIXME: Do not forget to remove this and use only 'import'. Expected -ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { +ASTNodeImporter::ImportTemplateArgument(TemplateArgument const &From) { return import(From); } template Error ASTNodeImporter::ImportTemplateArgumentListInfo( - const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) { - for (const auto &FromLoc : Container) { + InContainerTy const &Container, TemplateArgumentListInfo &ToTAInfo) { + for (auto const &FromLoc : Container) { if (auto ToLocOrErr = import(FromLoc)) ToTAInfo.addArgument(*ToLocOrErr); else @@ -2170,7 +2140,7 @@ } static StructuralEquivalenceKind -getStructuralEquivalenceKind(const ASTImporter &Importer) { +getStructuralEquivalenceKind(ASTImporter const &Importer) { return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal : StructuralEquivalenceKind::Default; } @@ -2194,11 +2164,10 @@ ToRecord = ToOriginRecord; } - StructuralEquivalenceContext Ctx(Importer.getFromContext(), - ToRecord->getASTContext(), - Importer.getNonEquivalentDecls(), - getStructuralEquivalenceKind(Importer), - false, Complain); + StructuralEquivalenceContext Ctx( + Importer.getFromContext(), ToRecord->getASTContext(), + Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), + false, Complain); return Ctx.IsEquivalent(FromRecord, ToRecord); } @@ -2216,7 +2185,7 @@ // something we're trying to import while completing ToEnum. if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum)) if (auto *ToOriginEnum = dyn_cast(ToOrigin)) - ToEnum = ToOriginEnum; + ToEnum = ToOriginEnum; StructuralEquivalenceContext Ctx( Importer.getFromContext(), Importer.getToContext(), @@ -2243,35 +2212,32 @@ bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC) { - const llvm::APSInt &FromVal = FromEC->getInitVal(); - const llvm::APSInt &ToVal = ToEC->getInitVal(); + llvm::APSInt const &FromVal = FromEC->getInitVal(); + llvm::APSInt const &ToVal = ToEC->getInitVal(); return FromVal.isSigned() == ToVal.isSigned() && - FromVal.getBitWidth() == ToVal.getBitWidth() && - FromVal == ToVal; + FromVal.getBitWidth() == ToVal.getBitWidth() && FromVal == ToVal; } bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To) { - StructuralEquivalenceContext Ctx(Importer.getFromContext(), - Importer.getToContext(), - Importer.getNonEquivalentDecls(), - getStructuralEquivalenceKind(Importer)); + StructuralEquivalenceContext Ctx( + Importer.getFromContext(), Importer.getToContext(), + Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer)); return Ctx.IsEquivalent(From, To); } bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To) { - StructuralEquivalenceContext Ctx(Importer.getFromContext(), - Importer.getToContext(), - Importer.getNonEquivalentDecls(), - getStructuralEquivalenceKind(Importer)); + StructuralEquivalenceContext Ctx( + Importer.getFromContext(), Importer.getToContext(), + Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer)); return Ctx.IsEquivalent(From, To); } ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) { Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) - << D->getDeclKindName(); + << D->getDeclKindName(); return make_error(ImportError::UnsupportedConstruct); } @@ -2302,8 +2268,7 @@ } ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { - TranslationUnitDecl *ToD = - Importer.getToContext().getTranslationUnitDecl(); + TranslationUnitDecl *ToD = Importer.getToContext().getTranslationUnitDecl(); Importer.MapImported(D, ToD); @@ -2382,9 +2347,9 @@ return std::move(Err); StaticAssertDecl *ToD; - if (GetImportedOrCreateDecl( - ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage, - ToRParenLoc, D->isFailed())) + if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, ToLocation, + ToAssertExpr, ToMessage, ToRParenLoc, + D->isFailed())) return ToD; ToD->setLexicalDeclContext(LexicalDC); @@ -2449,10 +2414,10 @@ // Create the "to" namespace, if needed. NamespaceDecl *ToNamespace = MergeWithNamespace; if (!ToNamespace) { - if (GetImportedOrCreateDecl( - ToNamespace, D, Importer.getToContext(), DC, D->isInline(), - *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), - /*PrevDecl=*/nullptr)) + if (GetImportedOrCreateDecl(ToNamespace, D, Importer.getToContext(), DC, + D->isInline(), *BeginLocOrErr, Loc, + Name.getAsIdentifierInfo(), + /*PrevDecl=*/nullptr)) return ToNamespace; ToNamespace->setRBraceLoc(*RBraceLocOrErr); ToNamespace->setLexicalDeclContext(LexicalDC); @@ -2500,9 +2465,9 @@ IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier()); NamespaceAliasDecl *ToD; - if (GetImportedOrCreateDecl( - ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc, - ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace)) + if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, + ToNamespaceLoc, ToAliasLoc, ToIdentifier, + ToQualifierLoc, ToTargetNameLoc, ToNamespace)) return ToD; ToD->setLexicalDeclContext(LexicalDC); @@ -2511,8 +2476,8 @@ return ToD; } -ExpectedDecl -ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) { +ExpectedDecl ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, + bool IsAlias) { // Import the major distinguishing characteristics of this typedef. DeclarationName Name; SourceLocation Loc; @@ -2585,12 +2550,12 @@ TypedefNameDecl *ToTypedef; if (IsAlias) { if (GetImportedOrCreateDecl( - ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, - Name.getAsIdentifierInfo(), ToTypeSourceInfo)) + ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, + Name.getAsIdentifierInfo(), ToTypeSourceInfo)) return ToTypedef; } else if (GetImportedOrCreateDecl( - ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, - Name.getAsIdentifierInfo(), ToTypeSourceInfo)) + ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, + Name.getAsIdentifierInfo(), ToTypeSourceInfo)) return ToTypedef; // Import the DeclContext and set it to the Typedef. @@ -2703,7 +2668,6 @@ if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo())) return ToLabel; - } Expected ToStmtOrErr = import(D->getStmt()); @@ -2731,8 +2695,8 @@ unsigned IDNS = Decl::IDNS_Tag; DeclarationName SearchName = Name; if (!SearchName && D->getTypedefNameForAnonDecl()) { - if (Error Err = importInto( - SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) + if (Error Err = importInto(SearchName, + D->getTypedefNameForAnonDecl()->getDeclName())) return std::move(Err); IDNS = Decl::IDNS_Ordinary; } else if (Importer.getToContext().getLangOpts().CPlusPlus) @@ -2742,14 +2706,13 @@ EnumDecl *PrevDecl = nullptr; if (!DC->isFunctionOrMethod() && SearchName) { SmallVector ConflictingDecls; - auto FoundDecls = - Importer.findDeclsInToCtx(DC, SearchName); + auto FoundDecls = Importer.findDeclsInToCtx(DC, SearchName); for (auto *FoundDecl : FoundDecls) { if (!FoundDecl->isInIdentifierNamespace(IDNS)) continue; if (auto *Typedef = dyn_cast(FoundDecl)) { - if (const auto *Tag = Typedef->getUnderlyingType()->getAs()) + if (auto const *Tag = Typedef->getUnderlyingType()->getAs()) FoundDecl = Tag->getDecl(); } @@ -2788,10 +2751,10 @@ // Create the enum declaration. EnumDecl *D2; - if (GetImportedOrCreateDecl( - D2, D, Importer.getToContext(), DC, ToBeginLoc, - Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(), - D->isScopedUsingClassTag(), D->isFixed())) + if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, ToBeginLoc, + Loc, Name.getAsIdentifierInfo(), PrevDecl, + D->isScoped(), D->isScopedUsingClassTag(), + D->isFixed())) return D2; D2->setQualifierInfo(ToQualifierLoc); @@ -2845,8 +2808,8 @@ unsigned IDNS = Decl::IDNS_Tag; DeclarationName SearchName = Name; if (!SearchName && D->getTypedefNameForAnonDecl()) { - if (Error Err = importInto( - SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) + if (Error Err = importInto(SearchName, + D->getTypedefNameForAnonDecl()->getDeclName())) return std::move(Err); IDNS = Decl::IDNS_Ordinary; } else if (Importer.getToContext().getLangOpts().CPlusPlus) @@ -2856,8 +2819,7 @@ RecordDecl *PrevDecl = nullptr; if (!DC->isFunctionOrMethod() && !D->isLambda()) { SmallVector ConflictingDecls; - auto FoundDecls = - Importer.findDeclsInToCtx(DC, SearchName); + auto FoundDecls = Importer.findDeclsInToCtx(DC, SearchName); if (!FoundDecls.empty()) { // We're going to have to compare D against potentially conflicting Decls, // so complete it. @@ -2871,7 +2833,7 @@ Decl *Found = FoundDecl; if (auto *Typedef = dyn_cast(Found)) { - if (const auto *Tag = Typedef->getUnderlyingType()->getAs()) + if (auto const *Tag = Typedef->getUnderlyingType()->getAs()) Found = Tag->getDecl(); } @@ -2898,7 +2860,7 @@ // FIXME: Structural equivalence check should check for same // user-defined methods. Importer.MapImported(D, FoundDef); - if (const auto *DCXX = dyn_cast(D)) { + if (auto const *DCXX = dyn_cast(D)) { auto *FoundCXX = dyn_cast(FoundDef); assert(FoundCXX && "Record type mismatch"); @@ -2914,7 +2876,7 @@ } ConflictingDecls.push_back(FoundDecl); } // kind is RecordDecl - } // for + } // for if (!ConflictingDecls.empty() && SearchName) { ExpectedName NameOrErr = Importer.HandleNameConflict( @@ -2951,17 +2913,17 @@ DCXX->hasKnownLambdaInternalLinkage()); D2CXX->setDeviceLambdaManglingNumber( DCXX->getDeviceLambdaManglingNumber()); - } else if (DCXX->isInjectedClassName()) { + } else if (DCXX->isInjectedClassName()) { // We have to be careful to do a similar dance to the one in // Sema::ActOnStartCXXMemberDeclarations - const bool DelayTypeCreation = true; + bool const DelayTypeCreation = true; if (GetImportedOrCreateDecl( D2CXX, D, Importer.getToContext(), D->getTagKind(), DC, *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), cast_or_null(PrevDecl), DelayTypeCreation)) return D2CXX; - Importer.getToContext().getTypeDeclType( - D2CXX, dyn_cast(DC)); + Importer.getToContext().getTypeDeclType(D2CXX, + dyn_cast(DC)); } else { if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(), D->getTagKind(), DC, *BeginLocOrErr, Loc, @@ -2975,8 +2937,7 @@ D2->setLexicalDeclContext(LexicalDC); addDeclToContexts(D, D2); - if (ClassTemplateDecl *FromDescribed = - DCXX->getDescribedClassTemplate()) { + if (ClassTemplateDecl *FromDescribed = DCXX->getDescribedClassTemplate()) { ClassTemplateDecl *ToDescribed; if (Error Err = importInto(ToDescribed, FromDescribed)) return std::move(Err); @@ -2997,8 +2958,7 @@ } } // Create an injected type for the whole redecl chain. - SmallVector Redecls = - getCanonicalForwardRedeclChain(D2CXX); + SmallVector Redecls = getCanonicalForwardRedeclChain(D2CXX); for (auto *R : Redecls) { auto *RI = cast(R); RI->setTypeForDecl(nullptr); @@ -3016,26 +2976,25 @@ } } else if (MemberSpecializationInfo *MemberInfo = DCXX->getMemberSpecializationInfo()) { - TemplateSpecializationKind SK = - MemberInfo->getTemplateSpecializationKind(); - CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass(); + TemplateSpecializationKind SK = + MemberInfo->getTemplateSpecializationKind(); + CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass(); - if (Expected ToInstOrErr = import(FromInst)) - D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK); - else - return ToInstOrErr.takeError(); + if (Expected ToInstOrErr = import(FromInst)) + D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK); + else + return ToInstOrErr.takeError(); - if (ExpectedSLoc POIOrErr = - import(MemberInfo->getPointOfInstantiation())) - D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation( + if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation())) + D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation( *POIOrErr); - else - return POIOrErr.takeError(); + else + return POIOrErr.takeError(); } } else { - if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), - D->getTagKind(), DC, *BeginLocOrErr, Loc, + if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), D->getTagKind(), + DC, *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), PrevDecl)) return D2; D2->setLexicalDeclContext(LexicalDC); @@ -3119,7 +3078,7 @@ return ToEnumerator; } -Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD, +Error ASTNodeImporter::ImportTemplateParameterLists(DeclaratorDecl const *FromD, DeclaratorDecl *ToD) { unsigned int Num = FromD->getNumTemplateParameterLists(); if (Num == 0) @@ -3135,8 +3094,8 @@ return Error::success(); } -Error ASTNodeImporter::ImportTemplateInformation( - FunctionDecl *FromFD, FunctionDecl *ToFD) { +Error ASTNodeImporter::ImportTemplateInformation(FunctionDecl *FromFD, + FunctionDecl *ToFD) { switch (FromFD->getTemplatedKind()) { case FunctionDecl::TK_NonTemplate: case FunctionDecl::TK_FunctionTemplate: @@ -3146,13 +3105,13 @@ TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind(); if (Expected InstFDOrErr = - import(FromFD->getInstantiatedFromMemberFunction())) + import(FromFD->getInstantiatedFromMemberFunction())) ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK); else return InstFDOrErr.takeError(); if (ExpectedSLoc POIOrErr = import( - FromFD->getMemberSpecializationInfo()->getPointOfInstantiation())) + FromFD->getMemberSpecializationInfo()->getPointOfInstantiation())) ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr); else return POIOrErr.takeError(); @@ -3167,14 +3126,14 @@ return FunctionAndArgsOrErr.takeError(); TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy( - Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr)); + Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr)); auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); TemplateArgumentListInfo ToTAInfo; - const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten; + auto const *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten; if (FromTAArgsAsWritten) - if (Error Err = ImportTemplateArgumentListInfo( - *FromTAArgsAsWritten, ToTAInfo)) + if (Error Err = + ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ToTAInfo)) return Err; ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation()); @@ -3197,7 +3156,7 @@ unsigned NumTemplates = FromInfo->getNumTemplates(); for (unsigned I = 0; I < NumTemplates; I++) { if (Expected ToFTDOrErr = - import(FromInfo->getTemplate(I))) + import(FromInfo->getTemplate(I))) TemplDecls.addDecl(*ToFTDOrErr); else return ToFTDOrErr.takeError(); @@ -3206,10 +3165,10 @@ // Import TemplateArgumentListInfo. TemplateArgumentListInfo ToTAInfo; if (Error Err = ImportTemplateArgumentListInfo( - FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(), - llvm::makeArrayRef( - FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()), - ToTAInfo)) + FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(), + llvm::makeArrayRef(FromInfo->getTemplateArgs(), + FromInfo->getNumTemplateArgs()), + ToTAInfo)) return Err; ToFD->setDependentTemplateSpecialization(Importer.getToContext(), @@ -3248,8 +3207,8 @@ // Returns true if the given D has a DeclContext up to the TranslationUnitDecl // which is equal to the given DC. -static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) { - const DeclContext *DCi = D->getDeclContext(); +static bool isAncestorDeclContextOf(DeclContext const *DC, Decl const *D) { + DeclContext const *DCi = D->getDeclContext(); while (DCi != D->getTranslationUnitDecl()) { if (DCi == DC) return true; @@ -3260,11 +3219,11 @@ bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) { QualType FromTy = D->getType(); - const FunctionProtoType *FromFPT = FromTy->getAs(); + FunctionProtoType const *FromFPT = FromTy->getAs(); assert(FromFPT && "Must be called on FunctionProtoType"); if (AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType()) { QualType DeducedT = AutoT->getDeducedType(); - if (const RecordType *RecordT = + if (RecordType const *RecordT = DeducedT.isNull() ? nullptr : dyn_cast(DeducedT)) { RecordDecl *RD = RecordT->getDecl(); assert(RD); @@ -3274,7 +3233,7 @@ } } } - if (const TypedefType *TypedefT = + if (TypedefType const *TypedefT = dyn_cast(FromFPT->getReturnType())) { TypedefNameDecl *TD = TypedefT->getDecl(); assert(TD); @@ -3423,7 +3382,7 @@ // FunctionDecl with a simplified function type and update it only after the // relevant AST nodes are already imported. bool UsedDifferentProtoType = false; - if (const auto *FromFPT = FromTy->getAs()) { + if (auto const *FromFPT = FromTy->getAs()) { QualType FromReturnTy = FromFPT->getReturnType(); // Functions with auto return type may define a struct inside their body // and the return type could refer to that struct. @@ -3547,8 +3506,8 @@ // Connect the redecl chain. if (FoundByLookup) { - auto *Recent = const_cast( - FoundByLookup->getMostRecentDecl()); + auto *Recent = + const_cast(FoundByLookup->getMostRecentDecl()); ToFunction->setPreviousDecl(Recent); // FIXME Probably we should merge exception specifications. E.g. In the // "To" context the existing function may have exception specification with @@ -3581,7 +3540,7 @@ // params it refers to. if (TInfo) { if (auto ProtoLoc = - TInfo->getTypeLoc().IgnoreParens().getAs()) { + TInfo->getTypeLoc().IgnoreParens().getAs()) { for (unsigned I = 0, N = Parameters.size(); I != N; ++I) ProtoLoc.setParam(I, Parameters[I]); } @@ -3599,8 +3558,8 @@ if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) { SmallVector CtorInitializers(NumInitializers); // Import first, then allocate memory and copy if there was no error. - if (Error Err = ImportContainerChecked( - FromConstructor->inits(), CtorInitializers)) + if (Error Err = ImportContainerChecked(FromConstructor->inits(), + CtorInitializers)) return std::move(Err); auto **Memory = new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers]; @@ -3686,9 +3645,8 @@ for (auto *FoundDecl : FoundDecls) { if (FieldDecl *FoundField = dyn_cast(FoundDecl)) { // For anonymous fields, match up by index. - if (!Name && - ASTImporter::getFieldIndex(D) != - ASTImporter::getFieldIndex(FoundField)) + if (!Name && ASTImporter::getFieldIndex(D) != + ASTImporter::getFieldIndex(FoundField)) continue; if (Importer.IsStructurallyEquivalent(D->getType(), @@ -3718,9 +3676,9 @@ // FIXME: Why is this case not handled with calling HandleNameConflict? Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) - << Name << D->getType() << FoundField->getType(); + << Name << D->getType() << FoundField->getType(); Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) - << FoundField->getType(); + << FoundField->getType(); return make_error(ImportError::NameConflict); } @@ -3734,7 +3692,7 @@ auto ToInitializer = importChecked(Err, D->getInClassInitializer()); if (Err) return std::move(Err); - const Type *ToCapturedVLAType = nullptr; + Type const *ToCapturedVLAType = nullptr; if (Error Err = Importer.importInto( ToCapturedVLAType, cast_or_null(D->getCapturedVLAType()))) return std::move(Err); @@ -3773,27 +3731,25 @@ for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { if (auto *FoundField = dyn_cast(FoundDecls[I])) { // For anonymous indirect fields, match up by index. - if (!Name && - ASTImporter::getFieldIndex(D) != - ASTImporter::getFieldIndex(FoundField)) + if (!Name && ASTImporter::getFieldIndex(D) != + ASTImporter::getFieldIndex(FoundField)) continue; - if (Importer.IsStructurallyEquivalent(D->getType(), - FoundField->getType(), + if (Importer.IsStructurallyEquivalent(D->getType(), FoundField->getType(), !Name.isEmpty())) { Importer.MapImported(D, FoundField); return FoundField; } // If there are more anonymous fields to check, continue. - if (!Name && I < N-1) + if (!Name && I < N - 1) continue; // FIXME: Why is this case not handled with calling HandleNameConflict? Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) - << Name << D->getType() << FoundField->getType(); + << Name << D->getType() << FoundField->getType(); Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) - << FoundField->getType(); + << FoundField->getType(); return make_error(ImportError::NameConflict); } @@ -3805,7 +3761,7 @@ return TypeOrErr.takeError(); auto **NamedChain = - new (Importer.getToContext()) NamedDecl*[D->getChainingSize()]; + new (Importer.getToContext()) NamedDecl *[D->getChainingSize()]; unsigned i = 0; for (auto *PI : D->chain()) @@ -3837,15 +3793,15 @@ template static FriendCountAndPosition getFriendCountAndPosition( - const FriendDecl *FD, - llvm::function_ref GetCanTypeOrDecl) { + FriendDecl const *FD, + llvm::function_ref GetCanTypeOrDecl) { unsigned int FriendCount = 0; llvm::Optional FriendPosition; - const auto *RD = cast(FD->getLexicalDeclContext()); + auto const *RD = cast(FD->getLexicalDeclContext()); T TypeOrDecl = GetCanTypeOrDecl(FD); - for (const FriendDecl *FoundFriend : RD->friends()) { + for (FriendDecl const *FoundFriend : RD->friends()) { if (FoundFriend == FD) { FriendPosition = FriendCount; ++FriendCount; @@ -3860,15 +3816,15 @@ return {FriendCount, *FriendPosition}; } -static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) { +static FriendCountAndPosition getFriendCountAndPosition(FriendDecl const *FD) { if (FD->getFriendType()) - return getFriendCountAndPosition(FD, [](const FriendDecl *F) { + return getFriendCountAndPosition(FD, [](FriendDecl const *F) { if (TypeSourceInfo *TSI = F->getFriendType()) return TSI->getType().getCanonicalType(); llvm_unreachable("Wrong friend object type."); }); else - return getFriendCountAndPosition(FD, [](const FriendDecl *F) { + return getFriendCountAndPosition(FD, [](FriendDecl const *F) { if (Decl *D = F->getFriendDecl()) return D->getCanonicalDecl(); llvm_unreachable("Wrong friend object type."); @@ -3884,7 +3840,7 @@ // Determine whether we've already imported this decl. // FriendDecl is not a NamedDecl so we cannot use lookup. // We try to maintain order and count of redundant friend declarations. - const auto *RD = cast(DC); + auto const *RD = cast(DC); FriendDecl *ImportedFriend = RD->getFirstFriend(); SmallVector ImportedEquivalentFriends; @@ -3950,8 +3906,7 @@ FriendDecl *FrD; if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC, - *LocationOrErr, ToFU, - *FriendLocOrErr, ToTPLists)) + *LocationOrErr, ToFU, *FriendLocOrErr, ToTPLists)) return FrD; FrD->setAccess(D->getAccess()); @@ -3982,9 +3937,9 @@ } Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent) - << Name << D->getType() << FoundIvar->getType(); + << Name << D->getType() << FoundIvar->getType(); Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here) - << FoundIvar->getType(); + << FoundIvar->getType(); return make_error(ImportError::NameConflict); } @@ -3999,11 +3954,11 @@ return std::move(Err); ObjCIvarDecl *ToIvar; - if (GetImportedOrCreateDecl( - ToIvar, D, Importer.getToContext(), cast(DC), - ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), - ToType, ToTypeSourceInfo, - D->getAccessControl(),ToBitWidth, D->getSynthesize())) + if (GetImportedOrCreateDecl(ToIvar, D, Importer.getToContext(), + cast(DC), ToInnerLocStart, Loc, + Name.getAsIdentifierInfo(), ToType, + ToTypeSourceInfo, D->getAccessControl(), + ToBitWidth, D->getSynthesize())) return ToIvar; ToIvar->setLexicalDeclContext(LexicalDC); @@ -4013,7 +3968,7 @@ ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) { - SmallVector Redecls = getCanonicalForwardRedeclChain(D); + SmallVector Redecls = getCanonicalForwardRedeclChain(D); auto RedeclIt = Redecls.begin(); // Import the first part of the decl chain. I.e. import all previous // declarations starting from the canonical decl. @@ -4061,19 +4016,19 @@ // The VarDecl in the "From" context has an initializer, but in the // "To" context we already have an initializer. - const VarDecl *FoundDInit = nullptr; + VarDecl const *FoundDInit = nullptr; if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit)) // FIXME Diagnose ODR error if the two initializers are different? - return Importer.MapImported(D, const_cast(FoundDInit)); + return Importer.MapImported(D, const_cast(FoundDInit)); FoundByLookup = FoundVar; break; } - const ArrayType *FoundArray - = Importer.getToContext().getAsArrayType(FoundVar->getType()); - const ArrayType *TArray - = Importer.getToContext().getAsArrayType(D->getType()); + ArrayType const *FoundArray = + Importer.getToContext().getAsArrayType(FoundVar->getType()); + ArrayType const *TArray = + Importer.getToContext().getAsArrayType(D->getType()); if (FoundArray && TArray) { if (isa(FoundArray) && isa(TArray)) { @@ -4093,9 +4048,9 @@ } Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent) - << Name << D->getType() << FoundVar->getType(); + << Name << D->getType() << FoundVar->getType(); Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here) - << FoundVar->getType(); + << FoundVar->getType(); ConflictingDecls.push_back(FoundDecl); } } @@ -4196,7 +4151,7 @@ } Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl( - const ParmVarDecl *FromParam, ParmVarDecl *ToParam) { + ParmVarDecl const *FromParam, ParmVarDecl *ToParam) { ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg()); ToParam->setKNRPromoted(FromParam->isKNRPromoted()); @@ -4276,12 +4231,13 @@ // Check return types. if (!Importer.IsStructurallyEquivalent(D->getReturnType(), FoundMethod->getReturnType())) { - Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent) + Importer.ToDiag(Loc, + diag::warn_odr_objc_method_result_type_inconsistent) << D->isInstanceMethod() << Name << D->getReturnType() << FoundMethod->getReturnType(); Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) - << D->isInstanceMethod() << Name; + << D->isInstanceMethod() << Name; return make_error(ImportError::NameConflict); } @@ -4289,27 +4245,28 @@ // Check the number of parameters. if (D->param_size() != FoundMethod->param_size()) { Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent) - << D->isInstanceMethod() << Name - << D->param_size() << FoundMethod->param_size(); + << D->isInstanceMethod() << Name << D->param_size() + << FoundMethod->param_size(); Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) - << D->isInstanceMethod() << Name; + << D->isInstanceMethod() << Name; return make_error(ImportError::NameConflict); } // Check parameter types. for (ObjCMethodDecl::param_iterator P = D->param_begin(), - PEnd = D->param_end(), FoundP = FoundMethod->param_begin(); + PEnd = D->param_end(), + FoundP = FoundMethod->param_begin(); P != PEnd; ++P, ++FoundP) { if (!Importer.IsStructurallyEquivalent((*P)->getType(), (*FoundP)->getType())) { Importer.FromDiag((*P)->getLocation(), diag::warn_odr_objc_method_param_type_inconsistent) - << D->isInstanceMethod() << Name - << (*P)->getType() << (*FoundP)->getType(); + << D->isInstanceMethod() << Name << (*P)->getType() + << (*FoundP)->getType(); Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here) - << (*FoundP)->getType(); + << (*FoundP)->getType(); return make_error(ImportError::NameConflict); } @@ -4319,10 +4276,10 @@ // Check the number of parameters. if (D->isVariadic() != FoundMethod->isVariadic()) { Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent) - << D->isInstanceMethod() << Name; + << D->isInstanceMethod() << Name; Importer.ToDiag(FoundMethod->getLocation(), diag::note_odr_objc_method_here) - << D->isInstanceMethod() << Name; + << D->isInstanceMethod() << Name; return make_error(ImportError::NameConflict); } @@ -4408,11 +4365,10 @@ return std::move(Err); ObjCTypeParamDecl *Result; - if (GetImportedOrCreateDecl( - Result, D, Importer.getToContext(), DC, D->getVariance(), - ToVarianceLoc, D->getIndex(), - ToLocation, Name.getAsIdentifierInfo(), - ToColonLoc, ToTypeSourceInfo)) + if (GetImportedOrCreateDecl(Result, D, Importer.getToContext(), DC, + D->getVariance(), ToVarianceLoc, D->getIndex(), + ToLocation, Name.getAsIdentifierInfo(), + ToColonLoc, ToTypeSourceInfo)) return Result; Result->setLexicalDeclContext(LexicalDC); @@ -4435,8 +4391,8 @@ return std::move(Err); // Determine if we've already encountered this category. - ObjCCategoryDecl *MergeWithCategory - = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo()); + ObjCCategoryDecl *MergeWithCategory = + ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo()); ObjCCategoryDecl *ToCategory = MergeWithCategory; if (!ToCategory) { @@ -4448,13 +4404,10 @@ if (Err) return std::move(Err); - if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC, - ToAtStartLoc, Loc, - ToCategoryNameLoc, - Name.getAsIdentifierInfo(), ToInterface, - /*TypeParamList=*/nullptr, - ToIvarLBraceLoc, - ToIvarRBraceLoc)) + if (GetImportedOrCreateDecl( + ToCategory, D, Importer.getToContext(), DC, ToAtStartLoc, Loc, + ToCategoryNameLoc, Name.getAsIdentifierInfo(), ToInterface, + /*TypeParamList=*/nullptr, ToIvarLBraceLoc, ToIvarRBraceLoc)) return ToCategory; ToCategory->setLexicalDeclContext(LexicalDC); @@ -4469,12 +4422,11 @@ // Import protocols SmallVector Protocols; SmallVector ProtocolLocs; - ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc - = D->protocol_loc_begin(); + ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc = + D->protocol_loc_begin(); for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(), - FromProtoEnd = D->protocol_end(); - FromProto != FromProtoEnd; - ++FromProto, ++FromProtoLoc) { + FromProtoEnd = D->protocol_end(); + FromProto != FromProtoEnd; ++FromProto, ++FromProtoLoc) { if (Expected ToProtoOrErr = import(*FromProto)) Protocols.push_back(*ToProtoOrErr); else @@ -4501,7 +4453,7 @@ // If we have an implementation, import it as well. if (D->getImplementation()) { if (Expected ToImplOrErr = - import(D->getImplementation())) + import(D->getImplementation())) ToCategory->setImplementation(*ToImplOrErr); else return ToImplOrErr.takeError(); @@ -4510,8 +4462,9 @@ return ToCategory; } -Error ASTNodeImporter::ImportDefinition( - ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) { +Error ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, + ObjCProtocolDecl *To, + ImportDefinitionKind Kind) { if (To->getDefinition()) { if (shouldForceImportDeclContext(Kind)) if (Error Err = ImportDeclContext(From)) @@ -4528,9 +4481,8 @@ ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc = From->protocol_loc_begin(); for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(), - FromProtoEnd = From->protocol_end(); - FromProto != FromProtoEnd; - ++FromProto, ++FromProtoLoc) { + FromProtoEnd = From->protocol_end(); + FromProto != FromProtoEnd; ++FromProto, ++FromProtoLoc) { if (Expected ToProtoOrErr = import(*FromProto)) Protocols.push_back(*ToProtoOrErr); else @@ -4540,12 +4492,11 @@ ProtocolLocs.push_back(*ToProtoLocOrErr); else return ToProtoLocOrErr.takeError(); - } // FIXME: If we're merging, make sure that the protocol list is the same. - To->setProtocolList(Protocols.data(), Protocols.size(), - ProtocolLocs.data(), Importer.getToContext()); + To->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), + Importer.getToContext()); if (shouldForceImportDeclContext(Kind)) { // Import all of the members of this protocol. @@ -4628,8 +4579,8 @@ LinkageSpecDecl *ToLinkageSpec; if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC, - *ExternLocOrErr, *LangLocOrErr, - D->getLanguage(), HasBraces)) + *ExternLocOrErr, *LangLocOrErr, D->getLanguage(), + HasBraces)) return ToLinkageSpec; if (HasBraces) { @@ -4689,10 +4640,10 @@ LexicalDC->addDeclInternal(ToUsing); if (NamedDecl *FromPattern = - Importer.getFromContext().getInstantiatedFromUsingDecl(D)) { + Importer.getFromContext().getInstantiatedFromUsingDecl(D)) { if (Expected ToPatternOrErr = import(FromPattern)) - Importer.getToContext().setInstantiatedFromUsingDecl( - ToUsing, *ToPatternOrErr); + Importer.getToContext().setInstantiatedFromUsingDecl(ToUsing, + *ToPatternOrErr); else return ToPatternOrErr.takeError(); } @@ -4764,7 +4715,7 @@ ToShadow->setAccess(D->getAccess()); if (UsingShadowDecl *FromPattern = - Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) { + Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) { if (Expected ToPatternOrErr = import(FromPattern)) Importer.getToContext().setInstantiatedFromUsingShadowDecl( ToShadow, *ToPatternOrErr); @@ -4805,10 +4756,8 @@ UsingDirectiveDecl *ToUsingDir; if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC, - ToUsingLoc, - ToNamespaceKeyLocation, - ToQualifierLoc, - ToIdentLocation, + ToUsingLoc, ToNamespaceKeyLocation, + ToQualifierLoc, ToIdentLocation, ToNominatedNamespace, *ToComAncestorOrErr)) return ToUsingDir; @@ -4818,8 +4767,8 @@ return ToUsingDir; } -ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl( - UnresolvedUsingValueDecl *D) { +ExpectedDecl +ASTNodeImporter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { DeclContext *DC, *LexicalDC; DeclarationName Name; SourceLocation Loc; @@ -4875,8 +4824,8 @@ UnresolvedUsingTypenameDecl *ToUsing; if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, - ToUsingLoc, ToTypenameLoc, - ToQualifierLoc, Loc, Name, ToEllipsisLoc)) + ToUsingLoc, ToTypenameLoc, ToQualifierLoc, Loc, + Name, ToEllipsisLoc)) return ToUsing; ToUsing->setAccess(D->getAccess()); @@ -4887,7 +4836,7 @@ } ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { - Decl* ToD = nullptr; + Decl *ToD = nullptr; switch (D->getBuiltinTemplateKind()) { case BuiltinTemplateKind::BTK__make_integer_seq: ToD = Importer.getToContext().getMakeIntegerSeqDecl(); @@ -4901,8 +4850,9 @@ return ToD; } -Error ASTNodeImporter::ImportDefinition( - ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) { +Error ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, + ObjCInterfaceDecl *To, + ImportDefinitionKind Kind) { if (To->getDefinition()) { // Check consistency of superclass. ObjCInterfaceDecl *FromSuper = From->getSuperClass(); @@ -4918,17 +4868,17 @@ (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) { Importer.ToDiag(To->getLocation(), diag::warn_odr_objc_superclass_inconsistent) - << To->getDeclName(); + << To->getDeclName(); if (ToSuper) Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass) - << To->getSuperClass()->getDeclName(); + << To->getSuperClass()->getDeclName(); else Importer.ToDiag(To->getLocation(), diag::note_odr_objc_missing_superclass); if (From->getSuperClass()) Importer.FromDiag(From->getSuperClassLoc(), diag::note_odr_objc_superclass) - << From->getSuperClass()->getDeclName(); + << From->getSuperClass()->getDeclName(); else Importer.FromDiag(From->getLocation(), diag::note_odr_objc_missing_superclass); @@ -4958,9 +4908,8 @@ From->protocol_loc_begin(); for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(), - FromProtoEnd = From->protocol_end(); - FromProto != FromProtoEnd; - ++FromProto, ++FromProtoLoc) { + FromProtoEnd = From->protocol_end(); + FromProto != FromProtoEnd; ++FromProto, ++FromProtoLoc) { if (Expected ToProtoOrErr = import(*FromProto)) Protocols.push_back(*ToProtoOrErr); else @@ -4970,12 +4919,11 @@ ProtocolLocs.push_back(*ToProtoLocOrErr); else return ToProtoLocOrErr.takeError(); - } // FIXME: If we're merging, make sure that the protocol list is the same. - To->setProtocolList(Protocols.data(), Protocols.size(), - ProtocolLocs.data(), Importer.getToContext()); + To->setProtocolList(Protocols.data(), Protocols.size(), ProtocolLocs.data(), + Importer.getToContext()); // Import categories. When the categories themselves are imported, they'll // hook themselves into this interface. @@ -4988,7 +4936,7 @@ // If we have an @implementation, import it as well. if (From->getImplementation()) { if (Expected ToImplOrErr = - import(From->getImplementation())) + import(From->getImplementation())) To->setImplementation(*ToImplOrErr); else return ToImplOrErr.takeError(); @@ -5022,10 +4970,8 @@ if (!RAngleLocOrErr) return RAngleLocOrErr.takeError(); - return ObjCTypeParamList::create(Importer.getToContext(), - *LAngleLocOrErr, - toTypeParams, - *RAngleLocOrErr); + return ObjCTypeParamList::create(Importer.getToContext(), *LAngleLocOrErr, + toTypeParams, *RAngleLocOrErr); } ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { @@ -5068,11 +5014,11 @@ if (!AtBeginLocOrErr) return AtBeginLocOrErr.takeError(); - if (GetImportedOrCreateDecl( - ToIface, D, Importer.getToContext(), DC, - *AtBeginLocOrErr, Name.getAsIdentifierInfo(), - /*TypeParamList=*/nullptr, - /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl())) + if (GetImportedOrCreateDecl(ToIface, D, Importer.getToContext(), DC, + *AtBeginLocOrErr, Name.getAsIdentifierInfo(), + /*TypeParamList=*/nullptr, + /*PrevDecl=*/nullptr, Loc, + D->isImplicitInterfaceDecl())) return ToIface; ToIface->setLexicalDeclContext(LexicalDC); LexicalDC->addDeclInternal(ToIface); @@ -5081,7 +5027,7 @@ // Import the type parameter list after MapImported, to avoid // loops when bringing in their DeclContext. if (auto ToPListOrErr = - ImportObjCTypeParamList(D->getTypeParamListAsWritten())) + ImportObjCTypeParamList(D->getTypeParamListAsWritten())) ToIface->setTypeParamList(*ToPListOrErr); else return ToPListOrErr.takeError(); @@ -5112,10 +5058,10 @@ if (Err) return std::move(Err); - if (GetImportedOrCreateDecl( - ToImpl, D, Importer.getToContext(), DC, - Importer.Import(D->getIdentifier()), Category->getClassInterface(), - ToLocation, ToAtStartLoc, ToCategoryNameLoc)) + if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC, + Importer.Import(D->getIdentifier()), + Category->getClassInterface(), ToLocation, + ToAtStartLoc, ToCategoryNameLoc)) return ToImpl; ToImpl->setLexicalDeclContext(LexicalDC); @@ -5159,13 +5105,9 @@ if (Err) return std::move(Err); - if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(), - DC, Iface, Super, - ToLocation, - ToAtStartLoc, - ToSuperClassLoc, - ToIvarLBraceLoc, - ToIvarRBraceLoc)) + if (GetImportedOrCreateDecl( + Impl, D, Importer.getToContext(), DC, Iface, Super, ToLocation, + ToAtStartLoc, ToSuperClassLoc, ToIvarLBraceLoc, ToIvarRBraceLoc)) return Impl; Impl->setLexicalDeclContext(LexicalDC); @@ -5184,20 +5126,18 @@ Impl->getSuperClass()))) { Importer.ToDiag(Impl->getLocation(), diag::warn_odr_objc_superclass_inconsistent) - << Iface->getDeclName(); + << Iface->getDeclName(); // FIXME: It would be nice to have the location of the superclass // below. if (Impl->getSuperClass()) - Importer.ToDiag(Impl->getLocation(), - diag::note_odr_objc_superclass) - << Impl->getSuperClass()->getDeclName(); + Importer.ToDiag(Impl->getLocation(), diag::note_odr_objc_superclass) + << Impl->getSuperClass()->getDeclName(); else Importer.ToDiag(Impl->getLocation(), diag::note_odr_objc_missing_superclass); if (D->getSuperClass()) - Importer.FromDiag(D->getLocation(), - diag::note_odr_objc_superclass) - << D->getSuperClass()->getDeclName(); + Importer.FromDiag(D->getLocation(), diag::note_odr_objc_superclass) + << D->getSuperClass()->getDeclName(); else Importer.FromDiag(D->getLocation(), diag::note_odr_objc_missing_superclass); @@ -5237,9 +5177,9 @@ if (!Importer.IsStructurallyEquivalent(D->getType(), FoundProp->getType())) { Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent) - << Name << D->getType() << FoundProp->getType(); + << Name << D->getType() << FoundProp->getType(); Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here) - << FoundProp->getType(); + << FoundProp->getType(); return make_error(ImportError::NameConflict); } @@ -5262,11 +5202,10 @@ // Create the new property. ObjCPropertyDecl *ToProperty; - if (GetImportedOrCreateDecl( - ToProperty, D, Importer.getToContext(), DC, Loc, - Name.getAsIdentifierInfo(), ToAtLoc, - ToLParenLoc, ToType, - ToTypeSourceInfo, D->getPropertyImplementation())) + if (GetImportedOrCreateDecl(ToProperty, D, Importer.getToContext(), DC, Loc, + Name.getAsIdentifierInfo(), ToAtLoc, ToLParenLoc, + ToType, ToTypeSourceInfo, + D->getPropertyImplementation())) return ToProperty; auto ToGetterName = importChecked(Err, D->getGetterName()); @@ -5284,7 +5223,7 @@ ToProperty->setPropertyAttributes(D->getPropertyAttributes()); ToProperty->setPropertyAttributesAsWritten( - D->getPropertyAttributesAsWritten()); + D->getPropertyAttributesAsWritten()); ToProperty->setGetterName(ToGetterName, ToGetterNameLoc); ToProperty->setSetterName(ToSetterName, ToSetterNameLoc); ToProperty->setGetterMethodDecl(ToGetterMethodDecl); @@ -5310,9 +5249,8 @@ if (Error Err = importInto(Ivar, D->getPropertyIvarDecl())) return std::move(Err); - ObjCPropertyImplDecl *ToImpl - = InImpl->FindPropertyImplDecl(Property->getIdentifier(), - Property->getQueryKind()); + ObjCPropertyImplDecl *ToImpl = InImpl->FindPropertyImplDecl( + Property->getIdentifier(), Property->getQueryKind()); if (!ToImpl) { Error Err = Error::success(); @@ -5324,8 +5262,7 @@ return std::move(Err); if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC, - ToBeginLoc, - ToLocation, Property, + ToBeginLoc, ToLocation, Property, D->getPropertyImplementation(), Ivar, ToPropertyIvarDeclLoc)) return ToImpl; @@ -5338,13 +5275,13 @@ if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) { Importer.ToDiag(ToImpl->getLocation(), diag::warn_odr_objc_property_impl_kind_inconsistent) - << Property->getDeclName() - << (ToImpl->getPropertyImplementation() - == ObjCPropertyImplDecl::Dynamic); + << Property->getDeclName() + << (ToImpl->getPropertyImplementation() == + ObjCPropertyImplDecl::Dynamic); Importer.FromDiag(D->getLocation(), diag::note_odr_objc_property_impl_kind) - << D->getPropertyDecl()->getDeclName() - << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); + << D->getPropertyDecl()->getDeclName() + << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); return make_error(ImportError::NameConflict); } @@ -5354,12 +5291,12 @@ Ivar != ToImpl->getPropertyIvarDecl()) { Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), diag::warn_odr_objc_synthesize_ivar_inconsistent) - << Property->getDeclName() - << ToImpl->getPropertyIvarDecl()->getDeclName() - << Ivar->getDeclName(); + << Property->getDeclName() + << ToImpl->getPropertyIvarDecl()->getDeclName() + << Ivar->getDeclName(); Importer.FromDiag(D->getPropertyIvarDeclLoc(), diag::note_odr_objc_synthesize_ivar_here) - << D->getPropertyIvarDecl()->getDeclName(); + << D->getPropertyIvarDecl()->getDeclName(); return make_error(ImportError::NameConflict); } @@ -5387,16 +5324,15 @@ TemplateTypeParmDecl *ToD = nullptr; if (GetImportedOrCreateDecl( - ToD, D, Importer.getToContext(), - Importer.getToContext().getTranslationUnitDecl(), - *BeginLocOrErr, *LocationOrErr, - D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()), - D->wasDeclaredWithTypename(), D->isParameterPack(), - D->hasTypeConstraint())) + ToD, D, Importer.getToContext(), + Importer.getToContext().getTranslationUnitDecl(), *BeginLocOrErr, + *LocationOrErr, D->getDepth(), D->getIndex(), + Importer.Import(D->getIdentifier()), D->wasDeclaredWithTypename(), + D->isParameterPack(), D->hasTypeConstraint())) return ToD; // Import the type-constraint - if (const TypeConstraint *TC = D->getTypeConstraint()) { + if (TypeConstraint const *TC = D->getTypeConstraint()) { Error Err = Error::success(); auto ToNNS = importChecked(Err, TC->getNestedNameSpecifierLoc()); @@ -5409,18 +5345,19 @@ return std::move(Err); TemplateArgumentListInfo ToTAInfo; - const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten(); + auto const *ASTTemplateArgs = TC->getTemplateArgsAsWritten(); if (ASTTemplateArgs) - if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, - ToTAInfo)) + if (Error Err = + ImportTemplateArgumentListInfo(*ASTTemplateArgs, ToTAInfo)) return std::move(Err); ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc), - ToFoundDecl, ToNamedConcept, - ASTTemplateArgs ? - ASTTemplateArgumentListInfo::Create(Importer.getToContext(), - ToTAInfo) : nullptr, - ToIDC); + ToFoundDecl, ToNamedConcept, + ASTTemplateArgs + ? ASTTemplateArgumentListInfo::Create( + Importer.getToContext(), ToTAInfo) + : nullptr, + ToIDC); } if (D->hasDefaultArgument()) { @@ -5625,7 +5562,7 @@ } ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl( - ClassTemplateSpecializationDecl *D) { + ClassTemplateSpecializationDecl *D) { ClassTemplateDecl *ClassTemplate; if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate())) return std::move(Err); @@ -5637,15 +5574,16 @@ // Import template arguments. SmallVector TemplateArgs; - if (Error Err = ImportTemplateArguments( - D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) + if (Error Err = + ImportTemplateArguments(D->getTemplateArgs().data(), + D->getTemplateArgs().size(), TemplateArgs)) return std::move(Err); // Try to find an existing specialization with these template arguments and // template parameter list. void *InsertPos = nullptr; ClassTemplateSpecializationDecl *PrevDecl = nullptr; ClassTemplatePartialSpecializationDecl *PartialSpec = - dyn_cast(D); + dyn_cast(D); // Import template parameters. TemplateParameterList *ToTPList = nullptr; @@ -5655,9 +5593,8 @@ if (!ToTPListOrErr) return ToTPListOrErr.takeError(); ToTPList = *ToTPListOrErr; - PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs, - *ToTPListOrErr, - InsertPos); + PrevDecl = ClassTemplate->findPartialSpecialization( + TemplateArgs, *ToTPListOrErr, InsertPos); } else PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos); @@ -5708,19 +5645,19 @@ if (PartialSpec) { // Import TemplateArgumentListInfo. TemplateArgumentListInfo ToTAInfo; - const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten(); + auto const &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten(); if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo)) return std::move(Err); QualType CanonInjType; - if (Error Err = importInto( - CanonInjType, PartialSpec->getInjectedSpecializationType())) + if (Error Err = importInto(CanonInjType, + PartialSpec->getInjectedSpecializationType())) return std::move(Err); CanonInjType = CanonInjType.getCanonicalType(); if (GetImportedOrCreateDecl( - D2, D, Importer.getToContext(), D->getTagKind(), DC, - *BeginLocOrErr, *IdLocOrErr, ToTPList, ClassTemplate, + D2, D, Importer.getToContext(), D->getTagKind(), DC, *BeginLocOrErr, + *IdLocOrErr, ToTPList, ClassTemplate, llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()), ToTAInfo, CanonInjType, cast_or_null(PrevDecl))) @@ -5736,10 +5673,9 @@ updateLookupTableForTemplateParameters(*ToTPList); } else { // Not a partial specialization. - if (GetImportedOrCreateDecl( - D2, D, Importer.getToContext(), D->getTagKind(), DC, - *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs, - PrevDecl)) + if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), D->getTagKind(), + DC, *BeginLocOrErr, *IdLocOrErr, ClassTemplate, + TemplateArgs, PrevDecl)) return D2; // Update InsertPos, because preceding import calls may have invalidated @@ -5940,14 +5876,15 @@ // Import template arguments. SmallVector TemplateArgs; - if (Error Err = ImportTemplateArguments( - D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) + if (Error Err = + ImportTemplateArguments(D->getTemplateArgs().data(), + D->getTemplateArgs().size(), TemplateArgs)) return std::move(Err); // Try to find an existing specialization with these template arguments. void *InsertPos = nullptr; - VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization( - TemplateArgs, InsertPos); + VarTemplateSpecializationDecl *D2 = + VarTemplate->findSpecialization(TemplateArgs, InsertPos); if (D2) { // We already have a variable template specialization with these template // arguments. @@ -5974,8 +5911,8 @@ return TInfoOrErr.takeError(); TemplateArgumentListInfo ToTAInfo; - if (Error Err = ImportTemplateArgumentListInfo( - D->getTemplateArgsInfo(), ToTAInfo)) + if (Error Err = + ImportTemplateArgumentListInfo(D->getTemplateArgsInfo(), ToTAInfo)) return std::move(Err); using PartVarSpecDecl = VarTemplatePartialSpecializationDecl; @@ -5983,10 +5920,10 @@ if (auto *FromPartial = dyn_cast(D)) { // Import TemplateArgumentListInfo TemplateArgumentListInfo ArgInfos; - const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten(); + auto const *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten(); // NOTE: FromTAArgsAsWritten and template parameter list are non-null. - if (Error Err = ImportTemplateArgumentListInfo( - *FromTAArgsAsWritten, ArgInfos)) + if (Error Err = + ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ArgInfos)) return std::move(Err); auto ToTPListOrErr = import(FromPartial->getTemplateParameters()); @@ -6000,8 +5937,8 @@ D->getStorageClass(), TemplateArgs, ArgInfos)) return ToPartial; - if (Expected ToInstOrErr = import( - FromPartial->getInstantiatedFromMember())) + if (Expected ToInstOrErr = + import(FromPartial->getInstantiatedFromMember())) ToPartial->setInstantiatedFromMember(*ToInstOrErr); else return ToInstOrErr.takeError(); @@ -6015,10 +5952,9 @@ // to adopt template parameters. // updateLookupTableForTemplateParameters(**ToTPListOrErr); } else { // Full specialization - if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, - *BeginLocOrErr, *IdLocOrErr, VarTemplate, - T, *TInfoOrErr, - D->getStorageClass(), TemplateArgs)) + if (GetImportedOrCreateDecl( + D2, D, Importer.getToContext(), DC, *BeginLocOrErr, *IdLocOrErr, + VarTemplate, T, *TInfoOrErr, D->getStorageClass(), TemplateArgs)) return D2; } @@ -6070,7 +6006,7 @@ if (ToD) return ToD; - const FunctionTemplateDecl *FoundByLookup = nullptr; + FunctionTemplateDecl const *FoundByLookup = nullptr; // Try to find a function in our own ("to") context with the same name, same // type, and in the same context as the function we're importing. @@ -6162,7 +6098,6 @@ return make_error(ImportError::UnsupportedConstruct); } - ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) { if (Importer.returnWithErrorInTest()) return make_error(ImportError::UnsupportedConstruct); @@ -6187,7 +6122,6 @@ Clobbers.push_back(*ClobberOrErr); else return ClobberOrErr.takeError(); - } SmallVector Constraints; @@ -6229,20 +6163,10 @@ return RParenLocOrErr.takeError(); return new (Importer.getToContext()) GCCAsmStmt( - Importer.getToContext(), - *AsmLocOrErr, - S->isSimple(), - S->isVolatile(), - S->getNumOutputs(), - S->getNumInputs(), - Names.data(), - Constraints.data(), - Exprs.data(), - *AsmStrOrErr, - S->getNumClobbers(), - Clobbers.data(), - S->getNumLabels(), - *RParenLocOrErr); + Importer.getToContext(), *AsmLocOrErr, S->isSimple(), S->isVolatile(), + S->getNumOutputs(), S->getNumInputs(), Names.data(), Constraints.data(), + Exprs.data(), *AsmStrOrErr, S->getNumClobbers(), Clobbers.data(), + S->getNumLabels(), *RParenLocOrErr); } ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) { @@ -6260,8 +6184,8 @@ ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc()); if (!ToSemiLocOrErr) return ToSemiLocOrErr.takeError(); - return new (Importer.getToContext()) NullStmt( - *ToSemiLocOrErr, S->hasLeadingEmptyMacro()); + return new (Importer.getToContext()) + NullStmt(*ToSemiLocOrErr, S->hasLeadingEmptyMacro()); } ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) { @@ -6278,9 +6202,8 @@ if (!ToRBracLocOrErr) return ToRBracLocOrErr.takeError(); - return CompoundStmt::Create( - Importer.getToContext(), ToStmts, - *ToLBracLocOrErr, *ToRBracLocOrErr); + return CompoundStmt::Create(Importer.getToContext(), ToStmts, + *ToLBracLocOrErr, *ToRBracLocOrErr); } ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) { @@ -6311,8 +6234,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) DefaultStmt( - ToDefaultLoc, ToColonLoc, ToSubStmt); + return new (Importer.getToContext()) + DefaultStmt(ToDefaultLoc, ToColonLoc, ToSubStmt); } ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) { @@ -6324,24 +6247,24 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) LabelStmt( - ToIdentLoc, ToLabelDecl, ToSubStmt); + return new (Importer.getToContext()) + LabelStmt(ToIdentLoc, ToLabelDecl, ToSubStmt); } ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) { ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc()); if (!ToAttrLocOrErr) return ToAttrLocOrErr.takeError(); - ArrayRef FromAttrs(S->getAttrs()); - SmallVector ToAttrs(FromAttrs.size()); + ArrayRef FromAttrs(S->getAttrs()); + SmallVector ToAttrs(FromAttrs.size()); if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs)) return std::move(Err); ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); if (!ToSubStmtOrErr) return ToSubStmtOrErr.takeError(); - return AttributedStmt::Create( - Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr); + return AttributedStmt::Create(Importer.getToContext(), *ToAttrLocOrErr, + ToAttrs, *ToSubStmtOrErr); } ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) { @@ -6427,8 +6350,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) DoStmt( - ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc); + return new (Importer.getToContext()) + DoStmt(ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc); } ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) { @@ -6445,10 +6368,9 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) ForStmt( - Importer.getToContext(), - ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc, - ToRParenLoc); + return new (Importer.getToContext()) + ForStmt(Importer.getToContext(), ToInit, ToCond, ToConditionVariable, + ToInc, ToBody, ToForLoc, ToLParenLoc, ToRParenLoc); } ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) { @@ -6460,8 +6382,7 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) GotoStmt( - ToLabel, ToGotoLoc, ToLabelLoc); + return new (Importer.getToContext()) GotoStmt(ToLabel, ToGotoLoc, ToLabelLoc); } ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) { @@ -6473,8 +6394,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) IndirectGotoStmt( - ToGotoLoc, ToStarLoc, ToTarget); + return new (Importer.getToContext()) + IndirectGotoStmt(ToGotoLoc, ToStarLoc, ToTarget); } ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) { @@ -6513,8 +6434,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) CXXCatchStmt ( - ToCatchLoc, ToExceptionDecl, ToHandlerBlock); + return new (Importer.getToContext()) + CXXCatchStmt(ToCatchLoc, ToExceptionDecl, ToHandlerBlock); } ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) { @@ -6535,8 +6456,8 @@ return ToHandlerOrErr.takeError(); } - return CXXTryStmt::Create( - Importer.getToContext(), *ToTryLocOrErr,*ToTryBlockOrErr, ToHandlers); + return CXXTryStmt::Create(Importer.getToContext(), *ToTryLocOrErr, + *ToTryBlockOrErr, ToHandlers); } ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) { @@ -6573,11 +6494,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement, - ToCollection, - ToBody, - ToForLoc, - ToRParenLoc); + return new (Importer.getToContext()) ObjCForCollectionStmt( + ToElement, ToCollection, ToBody, ToForLoc, ToRParenLoc); } ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { @@ -6590,8 +6508,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) ObjCAtCatchStmt ( - ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody); + return new (Importer.getToContext()) + ObjCAtCatchStmt(ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody); } ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) { @@ -6601,8 +6519,8 @@ ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody()); if (!ToAtFinallyStmtOrErr) return ToAtFinallyStmtOrErr.takeError(); - return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr, - *ToAtFinallyStmtOrErr); + return new (Importer.getToContext()) + ObjCAtFinallyStmt(*ToAtFinallyLocOrErr, *ToAtFinallyStmtOrErr); } ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { @@ -6623,8 +6541,7 @@ return ToCatchStmtOrErr.takeError(); } - return ObjCAtTryStmt::Create(Importer.getToContext(), - ToAtTryLoc, ToTryBody, + return ObjCAtTryStmt::Create(Importer.getToContext(), ToAtTryLoc, ToTryBody, ToCatchStmts.begin(), ToCatchStmts.size(), ToFinallyStmt); } @@ -6639,8 +6556,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) ObjCAtSynchronizedStmt( - ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody); + return new (Importer.getToContext()) + ObjCAtSynchronizedStmt(ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody); } ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { @@ -6650,20 +6567,20 @@ ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr()); if (!ToThrowExprOrErr) return ToThrowExprOrErr.takeError(); - return new (Importer.getToContext()) ObjCAtThrowStmt( - *ToThrowLocOrErr, *ToThrowExprOrErr); + return new (Importer.getToContext()) + ObjCAtThrowStmt(*ToThrowLocOrErr, *ToThrowExprOrErr); } -ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt( - ObjCAutoreleasePoolStmt *S) { +ExpectedStmt +ASTNodeImporter::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) { ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc()); if (!ToAtLocOrErr) return ToAtLocOrErr.takeError(); ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); if (!ToSubStmtOrErr) return ToSubStmtOrErr.takeError(); - return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr, - *ToSubStmtOrErr); + return new (Importer.getToContext()) + ObjCAutoreleasePoolStmt(*ToAtLocOrErr, *ToSubStmtOrErr); } //---------------------------------------------------------------------------- @@ -6701,9 +6618,9 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) VAArgExpr( - ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType, - E->isMicrosoftABI()); + return new (Importer.getToContext()) + VAArgExpr(ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType, + E->isMicrosoftABI()); } ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) { @@ -6752,17 +6669,17 @@ if (Err) return std::move(Err); - ArrayRef FromAssocTypes(E->getAssocTypeSourceInfos()); + ArrayRef FromAssocTypes(E->getAssocTypeSourceInfos()); SmallVector ToAssocTypes(FromAssocTypes.size()); if (Error Err = ImportContainerChecked(FromAssocTypes, ToAssocTypes)) return std::move(Err); - ArrayRef FromAssocExprs(E->getAssocExprs()); + ArrayRef FromAssocExprs(E->getAssocExprs()); SmallVector ToAssocExprs(FromAssocExprs.size()); if (Error Err = ImportContainerChecked(FromAssocExprs, ToAssocExprs)) return std::move(Err); - const ASTContext &ToCtx = Importer.getToContext(); + ASTContext const &ToCtx = Importer.getToContext(); if (E->isResultDependent()) { return GenericSelectionExpr::Create( ToCtx, ToGenericLoc, ToControllingExpr, @@ -6827,7 +6744,8 @@ return ToE; } -ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { +ExpectedStmt +ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { ExpectedType TypeOrErr = import(E->getType()); if (!TypeOrErr) return TypeOrErr.takeError(); @@ -6857,10 +6775,9 @@ if (Error Err = ImportContainerChecked(E->designators(), ToDesignators)) return std::move(Err); - return DesignatedInitExpr::Create( - Importer.getToContext(), ToDesignators, - ToIndexExprs, *ToEqualOrColonLocOrErr, - E->usesGNUSyntax(), *ToInitOrErr); + return DesignatedInitExpr::Create(Importer.getToContext(), ToDesignators, + ToIndexExprs, *ToEqualOrColonLocOrErr, + E->usesGNUSyntax(), *ToInitOrErr); } ExpectedStmt @@ -6873,8 +6790,8 @@ if (!ToLocationOrErr) return ToLocationOrErr.takeError(); - return new (Importer.getToContext()) CXXNullPtrLiteralExpr( - *ToTypeOrErr, *ToLocationOrErr); + return new (Importer.getToContext()) + CXXNullPtrLiteralExpr(*ToTypeOrErr, *ToLocationOrErr); } ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) { @@ -6886,11 +6803,10 @@ if (!ToLocationOrErr) return ToLocationOrErr.takeError(); - return IntegerLiteral::Create( - Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr); + return IntegerLiteral::Create(Importer.getToContext(), E->getValue(), + *ToTypeOrErr, *ToLocationOrErr); } - ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) { ExpectedType ToTypeOrErr = import(E->getType()); if (!ToTypeOrErr) @@ -6900,9 +6816,8 @@ if (!ToLocationOrErr) return ToLocationOrErr.takeError(); - return FloatingLiteral::Create( - Importer.getToContext(), E->getValue(), E->isExact(), - *ToTypeOrErr, *ToLocationOrErr); + return FloatingLiteral::Create(Importer.getToContext(), E->getValue(), + E->isExact(), *ToTypeOrErr, *ToLocationOrErr); } ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) { @@ -6914,8 +6829,8 @@ if (!ToSubExprOrErr) return ToSubExprOrErr.takeError(); - return new (Importer.getToContext()) ImaginaryLiteral( - *ToSubExprOrErr, *ToTypeOrErr); + return new (Importer.getToContext()) + ImaginaryLiteral(*ToSubExprOrErr, *ToTypeOrErr); } ExpectedStmt ASTNodeImporter::VisitFixedPointLiteral(FixedPointLiteral *E) { @@ -6951,13 +6866,13 @@ return ToTypeOrErr.takeError(); SmallVector ToLocations(E->getNumConcatenated()); - if (Error Err = ImportArrayChecked( - E->tokloc_begin(), E->tokloc_end(), ToLocations.begin())) + if (Error Err = ImportArrayChecked(E->tokloc_begin(), E->tokloc_end(), + ToLocations.begin())) return std::move(Err); - return StringLiteral::Create( - Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(), - *ToTypeOrErr, ToLocations.data(), ToLocations.size()); + return StringLiteral::Create(Importer.getToContext(), E->getBytes(), + E->getKind(), E->isPascal(), *ToTypeOrErr, + ToLocations.data(), ToLocations.size()); } ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { @@ -6970,9 +6885,9 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) CompoundLiteralExpr( - ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(), - ToInitializer, E->isFileScope()); + return new (Importer.getToContext()) + CompoundLiteralExpr(ToLParenLoc, ToTypeSourceInfo, ToType, + E->getValueKind(), ToInitializer, E->isFileScope()); } ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) { @@ -6985,9 +6900,9 @@ return std::move(Err); SmallVector ToExprs(E->getNumSubExprs()); - if (Error Err = ImportArrayChecked( - E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(), - ToExprs.begin())) + if (Error Err = ImportArrayChecked(E->getSubExprs(), + E->getSubExprs() + E->getNumSubExprs(), + ToExprs.begin())) return std::move(Err); return new (Importer.getToContext()) AtomicExpr( @@ -7004,8 +6919,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) AddrLabelExpr( - ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType); + return new (Importer.getToContext()) + AddrLabelExpr(ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType); } ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) { Error Err = Error::success(); @@ -7024,8 +6939,7 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) - ParenExpr(ToLParen, ToRParen, ToSubExpr); + return new (Importer.getToContext()) ParenExpr(ToLParen, ToRParen, ToSubExpr); } ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) { @@ -7054,9 +6968,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) - StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc, - E->getTemplateDepth()); + return new (Importer.getToContext()) StmtExpr( + ToSubStmt, ToType, ToLParenLoc, ToRParenLoc, E->getTemplateDepth()); } ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) { @@ -7067,10 +6980,10 @@ if (Err) return std::move(Err); - return UnaryOperator::Create( - Importer.getToContext(), ToSubExpr, E->getOpcode(), ToType, - E->getValueKind(), E->getObjectKind(), ToOperatorLoc, E->canOverflow(), - E->getFPOptionsOverride()); + return UnaryOperator::Create(Importer.getToContext(), ToSubExpr, + E->getOpcode(), ToType, E->getValueKind(), + E->getObjectKind(), ToOperatorLoc, + E->canOverflow(), E->getFPOptionsOverride()); } ExpectedStmt @@ -7089,9 +7002,9 @@ if (!ToArgumentTypeInfoOrErr) return ToArgumentTypeInfoOrErr.takeError(); - return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( - E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc, - ToRParenLoc); + return new (Importer.getToContext()) + UnaryExprOrTypeTraitExpr(E->getKind(), *ToArgumentTypeInfoOrErr, ToType, + ToOperatorLoc, ToRParenLoc); } ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr()); @@ -7128,9 +7041,9 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) ConditionalOperator( - ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType, - E->getValueKind(), E->getObjectKind()); + return new (Importer.getToContext()) + ConditionalOperator(ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, + ToType, E->getValueKind(), E->getObjectKind()); } ExpectedStmt @@ -7148,9 +7061,8 @@ return std::move(Err); return new (Importer.getToContext()) BinaryConditionalOperator( - ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, - ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(), - E->getObjectKind()); + ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, ToQuestionLoc, + ToColonLoc, ToType, E->getValueKind(), E->getObjectKind()); } ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) { @@ -7178,9 +7090,9 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) ExpressionTraitExpr( - ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(), - ToEndLoc, ToType); + return new (Importer.getToContext()) + ExpressionTraitExpr(ToBeginLoc, E->getTrait(), ToQueriedExpression, + E->getValue(), ToEndLoc, ToType); } ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) { @@ -7204,9 +7116,9 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) ArraySubscriptExpr( - ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(), - ToRBracketLoc); + return new (Importer.getToContext()) + ArraySubscriptExpr(ToLHS, ToRHS, ToType, E->getValueKind(), + E->getObjectKind(), ToRBracketLoc); } ExpectedStmt @@ -7229,8 +7141,7 @@ ToComputationLHSType, ToComputationResultType); } -Expected -ASTNodeImporter::ImportCastPath(CastExpr *CE) { +Expected ASTNodeImporter::ImportCastPath(CastExpr *CE) { CXXCastPath Path; for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) { if (auto SpecOrErr = import(*I)) @@ -7322,7 +7233,7 @@ ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) { SmallVector ToNodes; for (int I = 0, N = E->getNumComponents(); I < N; ++I) { - const OffsetOfNode &FromNode = E->getComponent(I); + OffsetOfNode const &FromNode = E->getComponent(I); SourceLocation ToBeginLoc, ToEndLoc; @@ -7377,9 +7288,8 @@ if (Err) return std::move(Err); - return OffsetOfExpr::Create( - Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes, - ToExprs, ToRParenLoc); + return OffsetOfExpr::Create(Importer.getToContext(), ToType, ToOperatorLoc, + ToTypeSourceInfo, ToNodes, ToExprs, ToRParenLoc); } ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) { @@ -7397,8 +7307,8 @@ else ToCanThrow = E->getValue() ? CT_Can : CT_Cannot; - return new (Importer.getToContext()) CXXNoexceptExpr( - ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc); + return new (Importer.getToContext()) + CXXNoexceptExpr(ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc); } ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) { @@ -7409,8 +7319,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) CXXThrowExpr( - ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope()); + return new (Importer.getToContext()) + CXXThrowExpr(ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope()); } ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { @@ -7454,8 +7364,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) CXXScalarValueInitExpr( - ToType, ToTypeSourceInfo, ToRParenLoc); + return new (Importer.getToContext()) + CXXScalarValueInitExpr(ToType, ToTypeSourceInfo, ToRParenLoc); } ExpectedStmt @@ -7566,19 +7476,17 @@ SmallVector ToPartialArguments; if (E->isPartiallySubstituted()) { - if (Error Err = ImportTemplateArguments( - E->getPartialArguments().data(), - E->getPartialArguments().size(), - ToPartialArguments)) + if (Error Err = ImportTemplateArguments(E->getPartialArguments().data(), + E->getPartialArguments().size(), + ToPartialArguments)) return std::move(Err); } - return SizeOfPackExpr::Create( - Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc, - Length, ToPartialArguments); + return SizeOfPackExpr::Create(Importer.getToContext(), ToOperatorLoc, ToPack, + ToPackLoc, ToRParenLoc, Length, + ToPartialArguments); } - ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) { Error Err = Error::success(); auto ToOperatorNew = importChecked(Err, E->getOperatorNew()); @@ -7596,7 +7504,7 @@ SmallVector ToPlacementArgs(E->getNumPlacementArgs()); if (Error Err = - ImportContainerChecked(E->placement_arguments(), ToPlacementArgs)) + ImportContainerChecked(E->placement_arguments(), ToPlacementArgs)) return std::move(Err); return CXXNewExpr::Create( @@ -7652,9 +7560,8 @@ if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects)) return std::move(Err); - return ExprWithCleanups::Create( - Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(), - ToObjects); + return ExprWithCleanups::Create(Importer.getToContext(), *ToSubExprOrErr, + E->cleanupsHaveSideEffects(), ToObjects); } ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { @@ -7683,8 +7590,8 @@ if (!ToLocationOrErr) return ToLocationOrErr.takeError(); - return new (Importer.getToContext()) CXXThisExpr( - *ToLocationOrErr, *ToTypeOrErr, E->isImplicit()); + return new (Importer.getToContext()) + CXXThisExpr(*ToLocationOrErr, *ToTypeOrErr, E->isImplicit()); } ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { @@ -7696,8 +7603,8 @@ if (!ToLocationOrErr) return ToLocationOrErr.takeError(); - return new (Importer.getToContext()) CXXBoolLiteralExpr( - E->getValue(), *ToTypeOrErr, *ToLocationOrErr); + return new (Importer.getToContext()) + CXXBoolLiteralExpr(E->getValue(), *ToTypeOrErr, *ToLocationOrErr); } ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) { @@ -7832,14 +7739,14 @@ TemplateArgumentListInfo *ResInfo = nullptr; if (E->hasExplicitTemplateArgs()) { if (Error Err = - ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo)) + ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo)) return std::move(Err); ResInfo = &ToTAInfo; } - return DependentScopeDeclRefExpr::Create( - Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, - ToNameInfo, ResInfo); + return DependentScopeDeclRefExpr::Create(Importer.getToContext(), + ToQualifierLoc, ToTemplateKeywordLoc, + ToNameInfo, ResInfo); } ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr( @@ -7854,7 +7761,7 @@ SmallVector ToArgs(E->getNumArgs()); if (Error Err = - ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin())) + ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin())) return std::move(Err); return CXXUnresolvedConstructExpr::Create( @@ -7892,9 +7799,9 @@ if (E->hasExplicitTemplateArgs()) { TemplateArgumentListInfo ToTAInfo; - if (Error Err = ImportTemplateArgumentListInfo( - E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(), - ToTAInfo)) + if (Error Err = + ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), + E->template_arguments(), ToTAInfo)) return std::move(Err); ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc()); @@ -7972,9 +7879,9 @@ unsigned NumArgs = E->getNumArgs(); llvm::SmallVector ToArgs(NumArgs); if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) - return std::move(Err); + return std::move(Err); - if (const auto *OCE = dyn_cast(E)) { + if (auto const *OCE = dyn_cast(E)) { return CXXOperatorCallExpr::Create( Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType, OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(), @@ -8015,7 +7922,6 @@ ToEndLoc, E->containsUnexpandedParameterPack()); } - ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) { Error Err = Error::success(); auto ToLBraceLoc = importChecked(Err, E->getLBraceLoc()); @@ -8029,8 +7935,8 @@ return std::move(Err); ASTContext &ToCtx = Importer.getToContext(); - InitListExpr *To = new (ToCtx) InitListExpr( - ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc); + InitListExpr *To = + new (ToCtx) InitListExpr(ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc); To->setType(ToType); if (E->hasArrayFiller()) { @@ -8061,8 +7967,8 @@ return To; } -ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr( - CXXStdInitializerListExpr *E) { +ExpectedStmt +ASTNodeImporter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) { ExpectedType ToTypeOrErr = import(E->getType()); if (!ToTypeOrErr) return ToTypeOrErr.takeError(); @@ -8071,12 +7977,12 @@ if (!ToSubExprOrErr) return ToSubExprOrErr.takeError(); - return new (Importer.getToContext()) CXXStdInitializerListExpr( - *ToTypeOrErr, *ToSubExprOrErr); + return new (Importer.getToContext()) + CXXStdInitializerListExpr(*ToTypeOrErr, *ToSubExprOrErr); } -ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr( - CXXInheritedCtorInitExpr *E) { +ExpectedStmt +ASTNodeImporter::VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E) { Error Err = Error::success(); auto ToLocation = importChecked(Err, E->getLocation()); auto ToType = importChecked(Err, E->getType()); @@ -8084,9 +7990,9 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) CXXInheritedCtorInitExpr( - ToLocation, ToType, ToConstructor, E->constructsVBase(), - E->inheritedFromVBase()); + return new (Importer.getToContext()) + CXXInheritedCtorInitExpr(ToLocation, ToType, ToConstructor, + E->constructsVBase(), E->inheritedFromVBase()); } ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) { @@ -8097,8 +8003,8 @@ if (Err) return std::move(Err); - return new (Importer.getToContext()) ArrayInitLoopExpr( - ToType, ToCommonExpr, ToSubExpr); + return new (Importer.getToContext()) + ArrayInitLoopExpr(ToType, ToCommonExpr, ToSubExpr); } ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { @@ -8121,8 +8027,8 @@ if (!UsedContextOrErr) return UsedContextOrErr.takeError(); - return CXXDefaultInitExpr::Create( - Importer.getToContext(), *ToBeginLocOrErr, *ToFieldOrErr, *UsedContextOrErr); + return CXXDefaultInitExpr::Create(Importer.getToContext(), *ToBeginLocOrErr, + *ToFieldOrErr, *UsedContextOrErr); } ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) { @@ -8196,9 +8102,8 @@ // Value is always false. bool ToValue = (E->isValueDependent() ? false : E->getValue()); - return TypeTraitExpr::Create( - Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs, - ToEndLoc, ToValue); + return TypeTraitExpr::Create(Importer.getToContext(), ToType, ToBeginLoc, + E->getTrait(), ToArgs, ToEndLoc, ToValue); } ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) { @@ -8212,8 +8117,8 @@ if (E->isTypeOperand()) { if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo())) - return new (Importer.getToContext()) CXXTypeidExpr( - *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr); + return new (Importer.getToContext()) + CXXTypeidExpr(*ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr); else return ToTSIOrErr.takeError(); } @@ -8222,8 +8127,8 @@ if (!ToExprOperandOrErr) return ToExprOperandOrErr.takeError(); - return new (Importer.getToContext()) CXXTypeidExpr( - *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr); + return new (Importer.getToContext()) + CXXTypeidExpr(*ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr); } ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) { @@ -8250,8 +8155,8 @@ Error ImportErrors = Error::success(); for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) { if (auto ImportedOrErr = import(FromOverriddenMethod)) - ToMethod->getCanonicalDecl()->addOverriddenMethod(cast( - (*ImportedOrErr)->getCanonicalDecl())); + ToMethod->getCanonicalDecl()->addOverriddenMethod( + cast((*ImportedOrErr)->getCanonicalDecl())); else ImportErrors = joinErrors(std::move(ImportErrors), ImportedOrErr.takeError()); @@ -8280,14 +8185,14 @@ Optional ASTImporter::getFieldIndex(Decl *F) { assert(F && (isa(*F) || isa(*F)) && - "Try to get field index for non-field."); + "Try to get field index for non-field."); auto *Owner = dyn_cast(F->getDeclContext()); if (!Owner) return None; unsigned Index = 0; - for (const auto *D : Owner->decls()) { + for (auto const *D : Owner->decls()) { if (D == F) return Index; @@ -8300,8 +8205,8 @@ return None; } -ASTImporter::FoundDeclsTy -ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) { +ASTImporter::FoundDeclsTy ASTImporter::findDeclsInToCtx(DeclContext *DC, + DeclarationName Name) { // We search in the redecl context because of transparent contexts. // E.g. a simple C language enum is a transparent context: // enum E { A, B }; @@ -8359,12 +8264,12 @@ return make_error(ImportError::UnsupportedConstruct); } -Expected ASTImporter::Import(const Type *FromT) { +Expected ASTImporter::Import(Type const *FromT) { if (!FromT) return FromT; // Check whether we've already imported this type. - llvm::DenseMap::iterator Pos = + llvm::DenseMap::iterator Pos = ImportedTypes.find(FromT); if (Pos != ImportedTypes.end()) return Pos->second; @@ -8385,7 +8290,7 @@ if (FromT.isNull()) return QualType{}; - Expected ToTyOrErr = Import(FromT.getTypePtr()); + Expected ToTyOrErr = Import(FromT.getTypePtr()); if (!ToTyOrErr) return ToTyOrErr.takeError(); @@ -8408,7 +8313,7 @@ return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr); } -Expected ASTImporter::Import(const Attr *FromAttr) { +Expected ASTImporter::Import(Attr const *FromAttr) { Attr *ToAttr = nullptr; SourceRange ToRange; if (Error Err = importInto(ToRange, FromAttr->getRange())) @@ -8442,7 +8347,7 @@ break; } case attr::Format: { - const auto *From = cast(FromAttr); + auto const *From = cast(FromAttr); FormatAttr *To; IdentifierInfo *ToAttrType = Import(From->getType()); To = FormatAttr::Create(ToContext, ToAttrType, From->getFormatIdx(), @@ -8459,11 +8364,11 @@ break; } assert(ToAttr && "Attribute should be created."); - + return ToAttr; } -Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const { +Decl *ASTImporter::GetAlreadyImportedOrNull(Decl const *FromD) const { auto Pos = ImportedDecls.find(FromD); if (Pos != ImportedDecls.end()) return Pos->second; @@ -8552,7 +8457,7 @@ // Get a copy of the error object (any more simple solution for this?). ImportError ErrOut; handleAllErrors(ToDOrErr.takeError(), - [&ErrOut](const ImportError &E) { ErrOut = E; }); + [&ErrOut](ImportError const &E) { ErrOut = E; }); setImportDeclError(FromD, ErrOut); // Set the error for the mapped to Decl, which is in the "to" context. if (Pos != ImportedDecls.end()) @@ -8560,16 +8465,16 @@ // Set the error for all nodes which have been created before we // recognized the error. - for (const auto &Path : SavedImportPaths[FromD]) + for (auto const &Path : SavedImportPaths[FromD]) for (Decl *FromDi : Path) { setImportDeclError(FromDi, ErrOut); - //FIXME Should we remove these Decls from ImportedDecls? - // Set the error for the mapped to Decl, which is in the "to" context. + // FIXME Should we remove these Decls from ImportedDecls? + // Set the error for the mapped to Decl, which is in the "to" context. auto Ii = ImportedDecls.find(FromDi); if (Ii != ImportedDecls.end()) SharedState->setImportDeclError(Ii->second, ErrOut); - // FIXME Should we remove these Decls from the LookupTable, - // and from ImportedFromDecls? + // FIXME Should we remove these Decls from the LookupTable, + // and from ImportedFromDecls? } SavedImportPaths.erase(FromD); @@ -8601,7 +8506,7 @@ assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?"); if (FromD->hasAttrs()) - for (const Attr *FromAttr : FromD->getAttrs()) { + for (Attr const *FromAttr : FromD->getAttrs()) { auto ToAttrOrErr = Import(FromAttr); if (ToAttrOrErr) ToD->addAttr(*ToAttrOrErr); @@ -8644,7 +8549,7 @@ if (FromRecord->isCompleteDefinition()) if (Error Err = ASTNodeImporter(*this).ImportDefinition( - FromRecord, ToRecord, ASTNodeImporter::IDK_Basic)) + FromRecord, ToRecord, ASTNodeImporter::IDK_Basic)) return std::move(Err); } else if (auto *ToEnum = dyn_cast(ToDC)) { auto *FromEnum = cast(FromDC); @@ -8652,7 +8557,7 @@ // Do nothing. } else if (FromEnum->isCompleteDefinition()) { if (Error Err = ASTNodeImporter(*this).ImportDefinition( - FromEnum, ToEnum, ASTNodeImporter::IDK_Basic)) + FromEnum, ToEnum, ASTNodeImporter::IDK_Basic)) return std::move(Err); } else { CompleteDecl(ToEnum); @@ -8663,7 +8568,7 @@ // Do nothing. } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) { if (Error Err = ASTNodeImporter(*this).ImportDefinition( - FromDef, ToClass, ASTNodeImporter::IDK_Basic)) + FromDef, ToClass, ASTNodeImporter::IDK_Basic)) return std::move(Err); } else { CompleteDecl(ToClass); @@ -8674,7 +8579,7 @@ // Do nothing. } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) { if (Error Err = ASTNodeImporter(*this).ImportDefinition( - FromDef, ToProto, ASTNodeImporter::IDK_Basic)) + FromDef, ToProto, ASTNodeImporter::IDK_Basic)) return std::move(Err); } else { CompleteDecl(ToProto); @@ -8778,7 +8683,7 @@ Expected ASTImporter::Import(NestedNameSpecifierLoc FromNNS) { // Copied from NestedNameSpecifier mostly. - SmallVector NestedNames; + SmallVector NestedNames; NestedNameSpecifierLoc NNS = FromNNS; // Push each of the nested-name-specifiers's onto a stack for @@ -8830,7 +8735,7 @@ if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc())) return std::move(Err); TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo( - QualType(Spec->getAsType(), 0), ToTLoc); + QualType(Spec->getAsType(), 0), ToTLoc); if (Kind == NestedNameSpecifier::TypeSpecWithTemplate) // ToLocalBeginLoc is here the location of the 'template' keyword. Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(), @@ -8855,7 +8760,7 @@ ToSourceRangeOrErr->getBegin(), ToSourceRangeOrErr->getEnd()); } - } + } } return Builder.getWithLocInContext(getToContext()); @@ -8935,8 +8840,8 @@ } case TemplateName::SubstTemplateTemplateParmPack: { - SubstTemplateTemplateParmPackStorage *SubstPack - = From.getAsSubstTemplateTemplateParmPack(); + SubstTemplateTemplateParmPackStorage *SubstPack = + From.getAsSubstTemplateTemplateParmPack(); ExpectedDecl ParamOrErr = Import(SubstPack->getParameterPack()); if (!ParamOrErr) return ParamOrErr.takeError(); @@ -8987,12 +8892,12 @@ SourceManager &FromSM = FromContext.getSourceManager(); SourceManager &ToSM = ToContext.getSourceManager(); - const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID); + SrcMgr::SLocEntry const &FromSLoc = FromSM.getSLocEntry(FromID); // Map the FromID to the "to" source manager. FileID ToID; if (FromSLoc.isExpansion()) { - const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion(); + SrcMgr::ExpansionInfo const &FromEx = FromSLoc.getExpansion(); ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc()); if (!ToSpLoc) return ToSpLoc.takeError(); @@ -9012,7 +8917,7 @@ } ToID = ToSM.getFileID(MLoc); } else { - const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache(); + SrcMgr::ContentCache const *Cache = &FromSLoc.getFile().getContentCache(); if (!IsBuiltin && !Cache->BufferOverridden) { // Include location of this file. @@ -9132,7 +9037,7 @@ } Expected -ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) { +ASTImporter::Import(CXXBaseSpecifier const *BaseSpec) { auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec); if (Pos != ImportedCXXBaseSpecifiers.end()) return Pos->second; @@ -9153,7 +9058,7 @@ return Imported; } -llvm::Expected ASTImporter::Import(const APValue &FromValue) { +llvm::Expected ASTImporter::Import(APValue const &FromValue) { ASTNodeImporter Importer(*this); return Importer.ImportAPValue(FromValue); } @@ -9169,32 +9074,29 @@ if (auto *ToRecord = dyn_cast(To)) { if (!ToRecord->getDefinition()) { - return Importer.ImportDefinition( - cast(FromDC), ToRecord, - ASTNodeImporter::IDK_Everything); + return Importer.ImportDefinition(cast(FromDC), ToRecord, + ASTNodeImporter::IDK_Everything); } } if (auto *ToEnum = dyn_cast(To)) { if (!ToEnum->getDefinition()) { - return Importer.ImportDefinition( - cast(FromDC), ToEnum, ASTNodeImporter::IDK_Everything); + return Importer.ImportDefinition(cast(FromDC), ToEnum, + ASTNodeImporter::IDK_Everything); } } if (auto *ToIFace = dyn_cast(To)) { if (!ToIFace->getDefinition()) { - return Importer.ImportDefinition( - cast(FromDC), ToIFace, - ASTNodeImporter::IDK_Everything); + return Importer.ImportDefinition(cast(FromDC), ToIFace, + ASTNodeImporter::IDK_Everything); } } if (auto *ToProto = dyn_cast(To)) { if (!ToProto->getDefinition()) { - return Importer.ImportDefinition( - cast(FromDC), ToProto, - ASTNodeImporter::IDK_Everything); + return Importer.ImportDefinition(cast(FromDC), ToProto, + ASTNodeImporter::IDK_Everything); } } @@ -9251,7 +9153,7 @@ case DeclarationName::CXXOperatorName: return ToContext.DeclarationNames.getCXXOperatorName( - FromName.getCXXOverloadedOperator()); + FromName.getCXXOverloadedOperator()); case DeclarationName::CXXLiteralOperatorName: return ToContext.DeclarationNames.getCXXLiteralOperatorName( @@ -9265,7 +9167,7 @@ llvm_unreachable("Invalid DeclarationName Kind!"); } -IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) { +IdentifierInfo *ASTImporter::Import(IdentifierInfo const *FromId) { if (!FromId) return nullptr; @@ -9289,10 +9191,10 @@ } llvm::Expected -ASTNodeImporter::ImportAPValue(const APValue &FromValue) { +ASTNodeImporter::ImportAPValue(APValue const &FromValue) { APValue Result; llvm::Error Err = llvm::Error::success(); - auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) { + auto ImportLoop = [&](APValue const *From, APValue *To, unsigned Size) { for (unsigned Idx = 0; Idx < Size; Idx++) { APValue Tmp = importChecked(Err, From[Idx]); To[Idx] = Tmp; @@ -9312,28 +9214,28 @@ Result.MakeVector(); MutableArrayRef Elts = Result.setVectorUninit(FromValue.getVectorLength()); - ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts, + ImportLoop(((APValue::Vec const *)(char const *)&FromValue.Data)->Elts, Elts.data(), FromValue.getVectorLength()); break; } case APValue::Array: Result.MakeArray(FromValue.getArrayInitializedElts(), FromValue.getArraySize()); - ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts, - ((const APValue::Arr *)(const char *)&Result.Data)->Elts, + ImportLoop(((APValue::Arr const *)(char const *)&FromValue.Data)->Elts, + ((APValue::Arr const *)(char const *)&Result.Data)->Elts, FromValue.getArrayInitializedElts()); break; case APValue::Struct: Result.MakeStruct(FromValue.getStructNumBases(), FromValue.getStructNumFields()); ImportLoop( - ((const APValue::StructData *)(const char *)&FromValue.Data)->Elts, - ((const APValue::StructData *)(const char *)&Result.Data)->Elts, + ((APValue::StructData const *)(char const *)&FromValue.Data)->Elts, + ((APValue::StructData const *)(char const *)&Result.Data)->Elts, FromValue.getStructNumBases() + FromValue.getStructNumFields()); break; case APValue::Union: { Result.MakeUnion(); - const Decl *ImpFDecl = importChecked(Err, FromValue.getUnionField()); + Decl const *ImpFDecl = importChecked(Err, FromValue.getUnionField()); APValue ImpValue = importChecked(Err, FromValue.getUnionValue()); if (Err) return std::move(Err); @@ -9342,8 +9244,8 @@ } case APValue::AddrLabelDiff: { Result.MakeAddrLabelDiff(); - const Expr *ImpLHS = importChecked(Err, FromValue.getAddrLabelDiffLHS()); - const Expr *ImpRHS = importChecked(Err, FromValue.getAddrLabelDiffRHS()); + Expr const *ImpLHS = importChecked(Err, FromValue.getAddrLabelDiffLHS()); + Expr const *ImpRHS = importChecked(Err, FromValue.getAddrLabelDiffRHS()); if (Err) return std::move(Err); Result.setAddrLabelDiff(cast(ImpLHS), @@ -9351,20 +9253,20 @@ break; } case APValue::MemberPointer: { - const Decl *ImpMemPtrDecl = + Decl const *ImpMemPtrDecl = importChecked(Err, FromValue.getMemberPointerDecl()); if (Err) return std::move(Err); - MutableArrayRef ToPath = + MutableArrayRef ToPath = Result.setMemberPointerUninit( cast(ImpMemPtrDecl), FromValue.isMemberPointerToDerivedMember(), FromValue.getMemberPointerPath().size()); - llvm::ArrayRef FromPath = + llvm::ArrayRef FromPath = Result.getMemberPointerPath(); for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size(); Idx++) { - const Decl *ImpDecl = importChecked(Err, FromPath[Idx]); + Decl const *ImpDecl = importChecked(Err, FromPath[Idx]); if (Err) return std::move(Err); ToPath[Idx] = cast(ImpDecl->getCanonicalDecl()); @@ -9379,10 +9281,10 @@ "in C++20 dynamic allocation are transient so they shouldn't " "appear in the AST"); if (!FromValue.getLValueBase().is()) { - if (const auto *E = - FromValue.getLValueBase().dyn_cast()) { + if (auto const *E = + FromValue.getLValueBase().dyn_cast()) { FromElemTy = E->getType(); - const Expr *ImpExpr = importChecked(Err, E); + Expr const *ImpExpr = importChecked(Err, E); if (Err) return std::move(Err); Base = APValue::LValueBase(ImpExpr, @@ -9390,9 +9292,9 @@ FromValue.getLValueBase().getVersion()); } else { FromElemTy = - FromValue.getLValueBase().get()->getType(); - const Decl *ImpDecl = importChecked( - Err, FromValue.getLValueBase().get()); + FromValue.getLValueBase().get()->getType(); + Decl const *ImpDecl = importChecked( + Err, FromValue.getLValueBase().get()); if (Err) return std::move(Err); Base = APValue::LValueBase(cast(ImpDecl), @@ -9424,9 +9326,9 @@ FromValue.getLValuePath(); for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) { if (FromElemTy->isRecordType()) { - const Decl *FromDecl = + Decl const *FromDecl = FromPath[LoopIdx].getAsBaseOrMember().getPointer(); - const Decl *ImpDecl = importChecked(Err, FromDecl); + Decl const *ImpDecl = importChecked(Err, FromDecl); if (Err) return std::move(Err); if (auto *RD = dyn_cast(FromDecl)) @@ -9467,7 +9369,7 @@ DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) { if (LastDiagFromFrom) ToContext.getDiagnostics().notePriorDiagnosticFrom( - FromContext.getDiagnostics()); + FromContext.getDiagnostics()); LastDiagFromFrom = false; return ToContext.getDiagnostics().Report(Loc, DiagID); } @@ -9475,27 +9377,24 @@ DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) { if (!LastDiagFromFrom) FromContext.getDiagnostics().notePriorDiagnosticFrom( - ToContext.getDiagnostics()); + ToContext.getDiagnostics()); LastDiagFromFrom = true; return FromContext.getDiagnostics().Report(Loc, DiagID); } -void ASTImporter::CompleteDecl (Decl *D) { +void ASTImporter::CompleteDecl(Decl *D) { if (auto *ID = dyn_cast(D)) { if (!ID->getDefinition()) ID->startDefinition(); - } - else if (auto *PD = dyn_cast(D)) { + } else if (auto *PD = dyn_cast(D)) { if (!PD->getDefinition()) PD->startDefinition(); - } - else if (auto *TD = dyn_cast(D)) { + } else if (auto *TD = dyn_cast(D)) { if (!TD->getDefinition() && !TD->isBeingDefined()) { TD->startDefinition(); TD->setCompleteDefinition(true); } - } - else { + } else { assert(0 && "CompleteDecl called on a Decl that can't be completed"); } } @@ -9503,7 +9402,7 @@ Decl *ASTImporter::MapImported(Decl *From, Decl *To) { llvm::DenseMap::iterator Pos = ImportedDecls.find(From); assert((Pos == ImportedDecls.end() || Pos->second == To) && - "Try to import an already imported Decl"); + "Try to import an already imported Decl"); if (Pos != ImportedDecls.end()) return Pos->second; ImportedDecls[From] = To; @@ -9537,7 +9436,7 @@ bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To, bool Complain) { - llvm::DenseMap::iterator Pos = + llvm::DenseMap::iterator Pos = ImportedTypes.find(From.getTypePtr()); if (Pos != ImportedTypes.end()) { if (ExpectedType ToFromOrErr = Import(From)) { Index: clang/lib/AST/ASTImporterLookupTable.cpp =================================================================== --- clang/lib/AST/ASTImporterLookupTable.cpp +++ clang/lib/AST/ASTImporterLookupTable.cpp @@ -26,7 +26,7 @@ bool VisitTypedefNameDecl(TypedefNameDecl *D) { QualType Ty = D->getUnderlyingType(); Ty = Ty.getCanonicalType(); - if (const auto *RTy = dyn_cast(Ty)) { + if (auto const *RTy = dyn_cast(Ty)) { LT.add(RTy->getAsRecordDecl()); // iterate over the field decls, adding them for (auto *it : RTy->getAsRecordDecl()->fields()) { @@ -55,11 +55,11 @@ // However, there are non-dependent cases which does not have the // type as a child node. We have to dig up that type now. if (!Ty->isDependentType()) { - if (const auto *RTy = dyn_cast(Ty)) + if (auto const *RTy = dyn_cast(Ty)) LT.add(RTy->getAsCXXRecordDecl()); - else if (const auto *SpecTy = dyn_cast(Ty)) + else if (auto const *SpecTy = dyn_cast(Ty)) LT.add(SpecTy->getAsCXXRecordDecl()); - else if (const auto *SubstTy = + else if (auto const *SubstTy = dyn_cast(Ty)) { if (SubstTy->getAsCXXRecordDecl()) LT.add(SubstTy->getAsCXXRecordDecl()); @@ -136,7 +136,7 @@ if (DCI == LookupTable.end()) return {}; - const auto &FoundNameMap = DCI->second; + auto const &FoundNameMap = DCI->second; auto NamesI = FoundNameMap.find(Name); if (NamesI == FoundNameMap.end()) return {}; @@ -152,12 +152,12 @@ auto DCI = LookupTable.find(DC->getPrimaryContext()); if (DCI == LookupTable.end()) llvm::errs() << "empty\n"; - const auto &FoundNameMap = DCI->second; - for (const auto &Entry : FoundNameMap) { + auto const &FoundNameMap = DCI->second; + for (auto const &Entry : FoundNameMap) { DeclarationName Name = Entry.first; llvm::errs() << "==== Name: "; Name.dump(); - const DeclList& List = Entry.second; + DeclList const &List = Entry.second; for (NamedDecl *ND : List) { ND->dump(); } @@ -165,7 +165,7 @@ } void ASTImporterLookupTable::dump() const { - for (const auto &Entry : LookupTable) { + for (auto const &Entry : LookupTable) { DeclContext *DC = Entry.first; StringRef Primary = DC->getPrimaryContext() ? " primary" : ""; llvm::errs() << "== DC:" << cast(DC) << Primary << "\n"; Index: clang/lib/AST/ASTStructuralEquivalence.cpp =================================================================== --- clang/lib/AST/ASTStructuralEquivalence.cpp +++ clang/lib/AST/ASTStructuralEquivalence.cpp @@ -100,13 +100,13 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Decl *D1, Decl *D2); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, - const TemplateArgument &Arg1, - const TemplateArgument &Arg2); + TemplateArgument const &Arg1, + TemplateArgument const &Arg2); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, NestedNameSpecifier *NNS1, NestedNameSpecifier *NNS2); -static bool IsStructurallyEquivalent(const IdentifierInfo *Name1, - const IdentifierInfo *Name2); +static bool IsStructurallyEquivalent(IdentifierInfo const *Name1, + IdentifierInfo const *Name2); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const DeclarationName Name1, @@ -165,19 +165,19 @@ // and only has to compare the data that is specific to the specific statement // class. Should only be called from TraverseStmt. - bool IsStmtEquivalent(const AddrLabelExpr *E1, const AddrLabelExpr *E2) { + bool IsStmtEquivalent(AddrLabelExpr const *E1, AddrLabelExpr const *E2) { return IsStructurallyEquivalent(Context, E1->getLabel(), E2->getLabel()); } - bool IsStmtEquivalent(const AtomicExpr *E1, const AtomicExpr *E2) { + bool IsStmtEquivalent(AtomicExpr const *E1, AtomicExpr const *E2) { return E1->getOp() == E2->getOp(); } - bool IsStmtEquivalent(const BinaryOperator *E1, const BinaryOperator *E2) { + bool IsStmtEquivalent(BinaryOperator const *E1, BinaryOperator const *E2) { return E1->getOpcode() == E2->getOpcode(); } - bool IsStmtEquivalent(const CallExpr *E1, const CallExpr *E2) { + bool IsStmtEquivalent(CallExpr const *E1, CallExpr const *E2) { // FIXME: IsStructurallyEquivalent requires non-const Decls. Decl *Callee1 = const_cast(E1->getCalleeDecl()); Decl *Callee2 = const_cast(E2->getCalleeDecl()); @@ -194,16 +194,16 @@ return IsStructurallyEquivalent(Context, Callee1, Callee2); } - bool IsStmtEquivalent(const CharacterLiteral *E1, - const CharacterLiteral *E2) { + bool IsStmtEquivalent(CharacterLiteral const *E1, + CharacterLiteral const *E2) { return E1->getValue() == E2->getValue() && E1->getKind() == E2->getKind(); } - bool IsStmtEquivalent(const ChooseExpr *E1, const ChooseExpr *E2) { + bool IsStmtEquivalent(ChooseExpr const *E1, ChooseExpr const *E2) { return true; // Semantics only depend on children. } - bool IsStmtEquivalent(const CompoundStmt *E1, const CompoundStmt *E2) { + bool IsStmtEquivalent(CompoundStmt const *E1, CompoundStmt const *E2) { // Number of children is actually checked by the generic children comparison // code, but a CompoundStmt is one of the few statements where the number of // children frequently differs and the number of statements is also always @@ -212,8 +212,8 @@ return E1->size() == E2->size(); } - bool IsStmtEquivalent(const DependentScopeDeclRefExpr *DE1, - const DependentScopeDeclRefExpr *DE2) { + bool IsStmtEquivalent(DependentScopeDeclRefExpr const *DE1, + DependentScopeDeclRefExpr const *DE2) { if (!IsStructurallyEquivalent(Context, DE1->getDeclName(), DE2->getDeclName())) return false; @@ -221,21 +221,21 @@ DE2->getQualifier()); } - bool IsStmtEquivalent(const Expr *E1, const Expr *E2) { + bool IsStmtEquivalent(Expr const *E1, Expr const *E2) { return IsStructurallyEquivalent(Context, E1->getType(), E2->getType()); } - bool IsStmtEquivalent(const ExpressionTraitExpr *E1, - const ExpressionTraitExpr *E2) { + bool IsStmtEquivalent(ExpressionTraitExpr const *E1, + ExpressionTraitExpr const *E2) { return E1->getTrait() == E2->getTrait() && E1->getValue() == E2->getValue(); } - bool IsStmtEquivalent(const FloatingLiteral *E1, const FloatingLiteral *E2) { + bool IsStmtEquivalent(FloatingLiteral const *E1, FloatingLiteral const *E2) { return E1->isExact() == E2->isExact() && E1->getValue() == E2->getValue(); } - bool IsStmtEquivalent(const GenericSelectionExpr *E1, - const GenericSelectionExpr *E2) { + bool IsStmtEquivalent(GenericSelectionExpr const *E1, + GenericSelectionExpr const *E2) { for (auto Pair : zip_longest(E1->getAssocTypeSourceInfos(), E2->getAssocTypeSourceInfos())) { Optional Child1 = std::get<0>(Pair); @@ -252,54 +252,54 @@ return true; } - bool IsStmtEquivalent(const ImplicitCastExpr *CastE1, - const ImplicitCastExpr *CastE2) { + bool IsStmtEquivalent(ImplicitCastExpr const *CastE1, + ImplicitCastExpr const *CastE2) { return IsStructurallyEquivalent(Context, CastE1->getType(), CastE2->getType()); } - bool IsStmtEquivalent(const IntegerLiteral *E1, const IntegerLiteral *E2) { + bool IsStmtEquivalent(IntegerLiteral const *E1, IntegerLiteral const *E2) { return E1->getValue() == E2->getValue(); } - bool IsStmtEquivalent(const MemberExpr *E1, const MemberExpr *E2) { + bool IsStmtEquivalent(MemberExpr const *E1, MemberExpr const *E2) { return IsStructurallyEquivalent(Context, E1->getFoundDecl(), E2->getFoundDecl()); } - bool IsStmtEquivalent(const ObjCStringLiteral *E1, - const ObjCStringLiteral *E2) { + bool IsStmtEquivalent(ObjCStringLiteral const *E1, + ObjCStringLiteral const *E2) { // Just wraps a StringLiteral child. return true; } - bool IsStmtEquivalent(const Stmt *S1, const Stmt *S2) { return true; } + bool IsStmtEquivalent(Stmt const *S1, Stmt const *S2) { return true; } - bool IsStmtEquivalent(const SourceLocExpr *E1, const SourceLocExpr *E2) { + bool IsStmtEquivalent(SourceLocExpr const *E1, SourceLocExpr const *E2) { return E1->getIdentKind() == E2->getIdentKind(); } - bool IsStmtEquivalent(const StmtExpr *E1, const StmtExpr *E2) { + bool IsStmtEquivalent(StmtExpr const *E1, StmtExpr const *E2) { return E1->getTemplateDepth() == E2->getTemplateDepth(); } - bool IsStmtEquivalent(const StringLiteral *E1, const StringLiteral *E2) { + bool IsStmtEquivalent(StringLiteral const *E1, StringLiteral const *E2) { return E1->getBytes() == E2->getBytes(); } - bool IsStmtEquivalent(const SubstNonTypeTemplateParmExpr *E1, - const SubstNonTypeTemplateParmExpr *E2) { + bool IsStmtEquivalent(SubstNonTypeTemplateParmExpr const *E1, + SubstNonTypeTemplateParmExpr const *E2) { return IsStructurallyEquivalent(Context, E1->getParameter(), E2->getParameter()); } - bool IsStmtEquivalent(const SubstNonTypeTemplateParmPackExpr *E1, - const SubstNonTypeTemplateParmPackExpr *E2) { + bool IsStmtEquivalent(SubstNonTypeTemplateParmPackExpr const *E1, + SubstNonTypeTemplateParmPackExpr const *E2) { return IsStructurallyEquivalent(Context, E1->getArgumentPack(), E2->getArgumentPack()); } - bool IsStmtEquivalent(const TypeTraitExpr *E1, const TypeTraitExpr *E2) { + bool IsStmtEquivalent(TypeTraitExpr const *E1, TypeTraitExpr const *E2) { if (E1->getTrait() != E2->getTrait()) return false; @@ -317,25 +317,25 @@ return true; } - bool IsStmtEquivalent(const UnaryExprOrTypeTraitExpr *E1, - const UnaryExprOrTypeTraitExpr *E2) { + bool IsStmtEquivalent(UnaryExprOrTypeTraitExpr const *E1, + UnaryExprOrTypeTraitExpr const *E2) { if (E1->getKind() != E2->getKind()) return false; return IsStructurallyEquivalent(Context, E1->getTypeOfArgument(), E2->getTypeOfArgument()); } - bool IsStmtEquivalent(const UnaryOperator *E1, const UnaryOperator *E2) { + bool IsStmtEquivalent(UnaryOperator const *E1, UnaryOperator const *E2) { return E1->getOpcode() == E2->getOpcode(); } - bool IsStmtEquivalent(const VAArgExpr *E1, const VAArgExpr *E2) { + bool IsStmtEquivalent(VAArgExpr const *E1, VAArgExpr const *E2) { // Semantics only depend on children. return true; } /// End point of the traversal chain. - bool TraverseStmt(const Stmt *S1, const Stmt *S2) { return true; } + bool TraverseStmt(Stmt const *S1, Stmt const *S2) { return true; } // Create traversal methods that traverse the class hierarchy and return // the accumulated result of the comparison. Each TraverseStmt overload @@ -357,7 +357,7 @@ /// Determine whether two statements are equivalent. The statements have to /// be of the same kind. The children of the statements and their properties /// are not compared by this function. - bool IsEquivalent(const Stmt *S1, const Stmt *S2) { + bool IsEquivalent(Stmt const *S1, Stmt const *S2) { if (S1->getStmtClass() != S2->getStmtClass()) return false; @@ -383,7 +383,7 @@ /// Determine structural equivalence of two statements. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, - const Stmt *S1, const Stmt *S2) { + Stmt const *S1, Stmt const *S2) { if (!S1 || !S2) return S1 == S2; @@ -394,8 +394,8 @@ // Iterate over the children of both statements and also compare them. for (auto Pair : zip_longest(S1->children(), S2->children())) { - Optional Child1 = std::get<0>(Pair); - Optional Child2 = std::get<1>(Pair); + Optional Child1 = std::get<0>(Pair); + Optional Child2 = std::get<1>(Pair); // One of the statements has a different amount of children than the other, // so the statements can't be equivalent. if (!Child1 || !Child2) @@ -407,8 +407,8 @@ } /// Determine whether two identifiers are equivalent. -static bool IsStructurallyEquivalent(const IdentifierInfo *Name1, - const IdentifierInfo *Name2) { +static bool IsStructurallyEquivalent(IdentifierInfo const *Name1, + IdentifierInfo const *Name2) { if (!Name1 || !Name2) return Name1 == Name2; @@ -455,8 +455,8 @@ } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, - const TemplateName &N1, - const TemplateName &N2) { + TemplateName const &N1, + TemplateName const &N2) { TemplateDecl *TemplateDeclN1 = N1.getAsTemplateDecl(); TemplateDecl *TemplateDeclN2 = N2.getAsTemplateDecl(); if (TemplateDeclN1 && TemplateDeclN2) { @@ -514,12 +514,11 @@ P2->getParameterPack()); } - case TemplateName::Template: - case TemplateName::QualifiedTemplate: - case TemplateName::SubstTemplateTemplateParm: - // It is sufficient to check value of getAsTemplateDecl. - break; - + case TemplateName::Template: + case TemplateName::QualifiedTemplate: + case TemplateName::SubstTemplateTemplateParm: + // It is sufficient to check value of getAsTemplateDecl. + break; } return true; @@ -527,8 +526,8 @@ /// Determine whether two template arguments are equivalent. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, - const TemplateArgument &Arg1, - const TemplateArgument &Arg2) { + TemplateArgument const &Arg1, + TemplateArgument const &Arg2) { if (Arg1.getKind() != Arg2.getKind()) return false; @@ -537,18 +536,20 @@ return true; case TemplateArgument::Type: - return IsStructurallyEquivalent(Context, Arg1.getAsType(), Arg2.getAsType()); + return IsStructurallyEquivalent(Context, Arg1.getAsType(), + Arg2.getAsType()); case TemplateArgument::Integral: if (!IsStructurallyEquivalent(Context, Arg1.getIntegralType(), - Arg2.getIntegralType())) + Arg2.getIntegralType())) return false; return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral()); case TemplateArgument::Declaration: - return IsStructurallyEquivalent(Context, Arg1.getAsDecl(), Arg2.getAsDecl()); + return IsStructurallyEquivalent(Context, Arg1.getAsDecl(), + Arg2.getAsDecl()); case TemplateArgument::NullPtr: return true; // FIXME: Is this correct? @@ -584,8 +585,8 @@ /// Determine structural equivalence for the common part of array /// types. static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context, - const ArrayType *Array1, - const ArrayType *Array2) { + ArrayType const *Array1, + ArrayType const *Array2) { if (!IsStructurallyEquivalent(Context, Array1->getElementType(), Array2->getElementType())) return false; @@ -625,8 +626,8 @@ /// Check the equivalence of exception specifications. static bool IsEquivalentExceptionSpec(StructuralEquivalenceContext &Context, - const FunctionProtoType *Proto1, - const FunctionProtoType *Proto2) { + FunctionProtoType const *Proto1, + FunctionProtoType const *Proto2) { auto Spec1 = Proto1->getExceptionSpecType(); auto Spec2 = Proto2->getExceptionSpecType(); @@ -725,8 +726,8 @@ case Type::LValueReference: case Type::RValueReference: { - const auto *Ref1 = cast(T1); - const auto *Ref2 = cast(T2); + auto const *Ref1 = cast(T1); + auto const *Ref2 = cast(T2); if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue()) return false; if (Ref1->isInnerRef() != Ref2->isInnerRef()) @@ -738,8 +739,8 @@ } case Type::MemberPointer: { - const auto *MemPtr1 = cast(T1); - const auto *MemPtr2 = cast(T2); + auto const *MemPtr1 = cast(T1); + auto const *MemPtr2 = cast(T2); if (!IsStructurallyEquivalent(Context, MemPtr1->getPointeeType(), MemPtr2->getPointeeType())) return false; @@ -750,8 +751,8 @@ } case Type::ConstantArray: { - const auto *Array1 = cast(T1); - const auto *Array2 = cast(T2); + auto const *Array1 = cast(T1); + auto const *Array2 = cast(T2); if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize())) return false; @@ -767,8 +768,8 @@ break; case Type::VariableArray: { - const auto *Array1 = cast(T1); - const auto *Array2 = cast(T2); + auto const *Array1 = cast(T1); + auto const *Array2 = cast(T2); if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(), Array2->getSizeExpr())) return false; @@ -780,8 +781,8 @@ } case Type::DependentSizedArray: { - const auto *Array1 = cast(T1); - const auto *Array2 = cast(T2); + auto const *Array1 = cast(T1); + auto const *Array2 = cast(T2); if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(), Array2->getSizeExpr())) return false; @@ -793,8 +794,8 @@ } case Type::DependentAddressSpace: { - const auto *DepAddressSpace1 = cast(T1); - const auto *DepAddressSpace2 = cast(T2); + auto const *DepAddressSpace1 = cast(T1); + auto const *DepAddressSpace2 = cast(T2); if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getAddrSpaceExpr(), DepAddressSpace2->getAddrSpaceExpr())) return false; @@ -806,8 +807,8 @@ } case Type::DependentSizedExtVector: { - const auto *Vec1 = cast(T1); - const auto *Vec2 = cast(T2); + auto const *Vec1 = cast(T1); + auto const *Vec2 = cast(T2); if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(), Vec2->getSizeExpr())) return false; @@ -818,8 +819,8 @@ } case Type::DependentVector: { - const auto *Vec1 = cast(T1); - const auto *Vec2 = cast(T2); + auto const *Vec1 = cast(T1); + auto const *Vec2 = cast(T2); if (Vec1->getVectorKind() != Vec2->getVectorKind()) return false; if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(), @@ -833,8 +834,8 @@ case Type::Vector: case Type::ExtVector: { - const auto *Vec1 = cast(T1); - const auto *Vec2 = cast(T2); + auto const *Vec1 = cast(T1); + auto const *Vec2 = cast(T2); if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), Vec2->getElementType())) return false; @@ -846,8 +847,8 @@ } case Type::DependentSizedMatrix: { - const DependentSizedMatrixType *Mat1 = cast(T1); - const DependentSizedMatrixType *Mat2 = cast(T2); + DependentSizedMatrixType const *Mat1 = cast(T1); + DependentSizedMatrixType const *Mat2 = cast(T2); // The element types, row and column expressions must be structurally // equivalent. if (!IsStructurallyEquivalent(Context, Mat1->getRowExpr(), @@ -861,8 +862,8 @@ } case Type::ConstantMatrix: { - const ConstantMatrixType *Mat1 = cast(T1); - const ConstantMatrixType *Mat2 = cast(T2); + ConstantMatrixType const *Mat1 = cast(T1); + ConstantMatrixType const *Mat2 = cast(T2); // The element types must be structurally equivalent and the number of rows // and columns must match. if (!IsStructurallyEquivalent(Context, Mat1->getElementType(), @@ -874,8 +875,8 @@ } case Type::FunctionProto: { - const auto *Proto1 = cast(T1); - const auto *Proto2 = cast(T2); + auto const *Proto1 = cast(T1); + auto const *Proto2 = cast(T2); if (Proto1->getNumParams() != Proto2->getNumParams()) return false; @@ -891,9 +892,9 @@ return false; // Check exceptions, this information is lost in canonical type. - const auto *OrigProto1 = + auto const *OrigProto1 = cast(OrigT1.getDesugaredType(Context.FromCtx)); - const auto *OrigProto2 = + auto const *OrigProto2 = cast(OrigT2.getDesugaredType(Context.ToCtx)); if (!IsEquivalentExceptionSpec(Context, OrigProto1, OrigProto2)) return false; @@ -903,8 +904,8 @@ } case Type::FunctionNoProto: { - const auto *Function1 = cast(T1); - const auto *Function2 = cast(T2); + auto const *Function1 = cast(T1); + auto const *Function2 = cast(T2); if (!IsStructurallyEquivalent(Context, Function1->getReturnType(), Function2->getReturnType())) return false; @@ -1006,8 +1007,8 @@ } case Type::DeducedTemplateSpecialization: { - const auto *DT1 = cast(T1); - const auto *DT2 = cast(T2); + auto const *DT1 = cast(T1); + auto const *DT2 = cast(T2); if (!IsStructurallyEquivalent(Context, DT1->getTemplateName(), DT2->getTemplateName())) return false; @@ -1025,8 +1026,8 @@ break; case Type::TemplateTypeParm: { - const auto *Parm1 = cast(T1); - const auto *Parm2 = cast(T2); + auto const *Parm1 = cast(T1); + auto const *Parm2 = cast(T2); if (Parm1->getDepth() != Parm2->getDepth()) return false; if (Parm1->getIndex() != Parm2->getIndex()) @@ -1039,8 +1040,8 @@ } case Type::SubstTemplateTypeParm: { - const auto *Subst1 = cast(T1); - const auto *Subst2 = cast(T2); + auto const *Subst1 = cast(T1); + auto const *Subst2 = cast(T2); if (!IsStructurallyEquivalent(Context, QualType(Subst1->getReplacedParameter(), 0), QualType(Subst2->getReplacedParameter(), 0))) @@ -1052,8 +1053,8 @@ } case Type::SubstTemplateTypeParmPack: { - const auto *Subst1 = cast(T1); - const auto *Subst2 = cast(T2); + auto const *Subst1 = cast(T1); + auto const *Subst2 = cast(T2); if (!IsStructurallyEquivalent(Context, QualType(Subst1->getReplacedParameter(), 0), QualType(Subst2->getReplacedParameter(), 0))) @@ -1065,8 +1066,8 @@ } case Type::TemplateSpecialization: { - const auto *Spec1 = cast(T1); - const auto *Spec2 = cast(T2); + auto const *Spec1 = cast(T1); + auto const *Spec2 = cast(T2); if (!IsStructurallyEquivalent(Context, Spec1->getTemplateName(), Spec2->getTemplateName())) return false; @@ -1081,8 +1082,8 @@ } case Type::Elaborated: { - const auto *Elab1 = cast(T1); - const auto *Elab2 = cast(T2); + auto const *Elab1 = cast(T1); + auto const *Elab2 = cast(T2); // CHECKME: what if a keyword is ETK_None or ETK_typename ? if (Elab1->getKeyword() != Elab2->getKeyword()) return false; @@ -1096,8 +1097,8 @@ } case Type::InjectedClassName: { - const auto *Inj1 = cast(T1); - const auto *Inj2 = cast(T2); + auto const *Inj1 = cast(T1); + auto const *Inj2 = cast(T2); if (!IsStructurallyEquivalent(Context, Inj1->getInjectedSpecializationType(), Inj2->getInjectedSpecializationType())) @@ -1106,8 +1107,8 @@ } case Type::DependentName: { - const auto *Typename1 = cast(T1); - const auto *Typename2 = cast(T2); + auto const *Typename1 = cast(T1); + auto const *Typename2 = cast(T2); if (!IsStructurallyEquivalent(Context, Typename1->getQualifier(), Typename2->getQualifier())) return false; @@ -1119,8 +1120,8 @@ } case Type::DependentTemplateSpecialization: { - const auto *Spec1 = cast(T1); - const auto *Spec2 = cast(T2); + auto const *Spec1 = cast(T1); + auto const *Spec2 = cast(T2); if (!IsStructurallyEquivalent(Context, Spec1->getQualifier(), Spec2->getQualifier())) return false; @@ -1145,8 +1146,8 @@ break; case Type::ObjCInterface: { - const auto *Iface1 = cast(T1); - const auto *Iface2 = cast(T2); + auto const *Iface1 = cast(T1); + auto const *Iface2 = cast(T2); if (!IsStructurallyEquivalent(Context, Iface1->getDecl(), Iface2->getDecl())) return false; @@ -1154,8 +1155,8 @@ } case Type::ObjCTypeParam: { - const auto *Obj1 = cast(T1); - const auto *Obj2 = cast(T2); + auto const *Obj1 = cast(T1); + auto const *Obj2 = cast(T2); if (!IsStructurallyEquivalent(Context, Obj1->getDecl(), Obj2->getDecl())) return false; @@ -1170,8 +1171,8 @@ } case Type::ObjCObject: { - const auto *Obj1 = cast(T1); - const auto *Obj2 = cast(T2); + auto const *Obj1 = cast(T1); + auto const *Obj2 = cast(T2); if (!IsStructurallyEquivalent(Context, Obj1->getBaseType(), Obj2->getBaseType())) return false; @@ -1186,8 +1187,8 @@ } case Type::ObjCObjectPointer: { - const auto *Ptr1 = cast(T1); - const auto *Ptr2 = cast(T2); + auto const *Ptr1 = cast(T1); + auto const *Ptr2 = cast(T2); if (!IsStructurallyEquivalent(Context, Ptr1->getPointeeType(), Ptr2->getPointeeType())) return false; @@ -1206,8 +1207,8 @@ return false; break; case Type::ExtInt: { - const auto *Int1 = cast(T1); - const auto *Int2 = cast(T2); + auto const *Int1 = cast(T1); + auto const *Int2 = cast(T2); if (Int1->isUnsigned() != Int2->isUnsigned() || Int1->getNumBits() != Int2->getNumBits()) @@ -1215,8 +1216,8 @@ break; } case Type::DependentExtInt: { - const auto *Int1 = cast(T1); - const auto *Int2 = cast(T2); + auto const *Int1 = cast(T1); + auto const *Int2 = cast(T2); if (Int1->isUnsigned() != Int2->isUnsigned() || !IsStructurallyEquivalent(Context, Int1->getNumBitsExpr(), @@ -1231,7 +1232,7 @@ /// Determine structural equivalence of two fields. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, FieldDecl *Field1, FieldDecl *Field2) { - const auto *Owner2 = cast(Field2->getDeclContext()); + auto const *Owner2 = cast(Field2->getDeclContext()); // For anonymous structs/unions, match up the anonymous struct/union type // declarations directly, so that we don't go off searching for anonymous @@ -1319,16 +1320,16 @@ return false; } - const IdentifierInfo *Name1 = Method1->getIdentifier(); - const IdentifierInfo *Name2 = Method2->getIdentifier(); + IdentifierInfo const *Name1 = Method1->getIdentifier(); + IdentifierInfo const *Name2 = Method2->getIdentifier(); if (!::IsStructurallyEquivalent(Name1, Name2)) { return false; // TODO: Names do not match, add warning like at check for FieldDecl. } // Check the prototypes. - if (!::IsStructurallyEquivalent(Context, - Method1->getType(), Method2->getType())) + if (!::IsStructurallyEquivalent(Context, Method1->getType(), + Method2->getType())) return false; return true; @@ -1388,8 +1389,8 @@ // If both declarations are class template specializations, we know // the ODR applies, so check the template and template arguments. - const auto *Spec1 = dyn_cast(D1); - const auto *Spec2 = dyn_cast(D2); + auto const *Spec1 = dyn_cast(D1); + auto const *Spec2 = dyn_cast(D2); if (Spec1 && Spec2) { // Check that the specialized templates are the same. if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(), @@ -1544,7 +1545,7 @@ Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); - const CXXBaseSpecifier *Base1 = D1CXX->bases_begin(); + CXXBaseSpecifier const *Base1 = D1CXX->bases_begin(); Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base) << Base1->getType() << Base1->getSourceRange(); Context.Diag2(D2->getLocation(), diag::note_odr_missing_base); @@ -1767,8 +1768,9 @@ D2->getTemplateParameters()); } -static bool IsTemplateDeclCommonStructurallyEquivalent( - StructuralEquivalenceContext &Ctx, TemplateDecl *D1, TemplateDecl *D2) { +static bool +IsTemplateDeclCommonStructurallyEquivalent(StructuralEquivalenceContext &Ctx, + TemplateDecl *D1, TemplateDecl *D2) { if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) return false; if (!D1->getIdentifier()) // Special name @@ -1803,8 +1805,7 @@ } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, - ConceptDecl *D1, - ConceptDecl *D2) { + ConceptDecl *D1, ConceptDecl *D2) { // Check template parameters. if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2)) return false; @@ -1818,11 +1819,10 @@ FriendDecl *D1, FriendDecl *D2) { if ((D1->getFriendType() && D2->getFriendDecl()) || (D1->getFriendDecl() && D2->getFriendType())) { - return false; + return false; } if (D1->getFriendType() && D2->getFriendType()) - return IsStructurallyEquivalent(Context, - D1->getFriendType()->getType(), + return IsStructurallyEquivalent(Context, D1->getFriendType()->getType(), D2->getFriendType()->getType()); if (D1->getFriendDecl() && D2->getFriendDecl()) return IsStructurallyEquivalent(Context, D1->getFriendDecl(), @@ -1907,13 +1907,13 @@ ASTContext &Context = Anon->getASTContext(); QualType AnonTy = Context.getRecordType(Anon); - const auto *Owner = dyn_cast(Anon->getDeclContext()); + auto const *Owner = dyn_cast(Anon->getDeclContext()); if (!Owner) return None; unsigned Index = 0; - for (const auto *D : Owner->noload_decls()) { - const auto *F = dyn_cast(D); + for (auto const *D : Owner->noload_decls()) { + auto const *F = dyn_cast(D); if (!F) continue; @@ -1928,11 +1928,11 @@ // struct { ... } A; QualType FieldType = F->getType(); // In case of nested structs. - while (const auto *ElabType = dyn_cast(FieldType)) + while (auto const *ElabType = dyn_cast(FieldType)) FieldType = ElabType->getNamedType(); - if (const auto *RecType = dyn_cast(FieldType)) { - const RecordDecl *RecDecl = RecType->getDecl(); + if (auto const *RecType = dyn_cast(FieldType)) { + RecordDecl const *RecDecl = RecType->getDecl(); if (RecDecl->getDeclContext() == Owner && !RecDecl->getIdentifier()) { if (Context.hasSameType(FieldType, AnonTy)) break; @@ -2042,8 +2042,8 @@ return true; } -bool StructuralEquivalenceContext::CheckKindSpecificEquivalence( - Decl *D1, Decl *D2) { +bool StructuralEquivalenceContext::CheckKindSpecificEquivalence(Decl *D1, + Decl *D2) { // Kind mismatch. if (D1->getKind() != D2->getKind()) Index: clang/lib/AST/ASTTypeTraits.cpp =================================================================== --- clang/lib/AST/ASTTypeTraits.cpp +++ clang/lib/AST/ASTTypeTraits.cpp @@ -33,13 +33,13 @@ {NKI_None, "CXXCtorInitializer"}, {NKI_None, "NestedNameSpecifier"}, {NKI_None, "Decl"}, -#define DECL(DERIVED, BASE) { NKI_##BASE, #DERIVED "Decl" }, +#define DECL(DERIVED, BASE) {NKI_##BASE, #DERIVED "Decl"}, #include "clang/AST/DeclNodes.inc" {NKI_None, "Stmt"}, -#define STMT(DERIVED, BASE) { NKI_##BASE, #DERIVED }, +#define STMT(DERIVED, BASE) {NKI_##BASE, #DERIVED}, #include "clang/AST/StmtNodes.inc" {NKI_None, "Type"}, -#define TYPE(DERIVED, BASE) { NKI_##BASE, #DERIVED "Type" }, +#define TYPE(DERIVED, BASE) {NKI_##BASE, #DERIVED "Type"}, #include "clang/AST/TypeNodes.inc" {NKI_None, "OMPClause"}, #define GEN_CLANG_CLAUSE_CLASS @@ -56,7 +56,8 @@ bool ASTNodeKind::isBaseOf(NodeKindId Base, NodeKindId Derived, unsigned *Distance) { - if (Base == NKI_None || Derived == NKI_None) return false; + if (Base == NKI_None || Derived == NKI_None) + return false; unsigned Dist = 0; while (Derived != Base && Derived != NKI_None) { Derived = AllKindInfo[Derived].ParentId; @@ -82,8 +83,10 @@ ASTNodeKind ASTNodeKind::getMostDerivedType(ASTNodeKind Kind1, ASTNodeKind Kind2) { - if (Kind1.isBaseOf(Kind2)) return Kind2; - if (Kind2.isBaseOf(Kind1)) return Kind1; + if (Kind1.isBaseOf(Kind2)) + return Kind2; + if (Kind2.isBaseOf(Kind1)) + return Kind1; return ASTNodeKind(); } @@ -96,38 +99,42 @@ return ASTNodeKind(Parent); } -ASTNodeKind ASTNodeKind::getFromNode(const Decl &D) { +ASTNodeKind ASTNodeKind::getFromNode(Decl const &D) { switch (D.getKind()) { #define DECL(DERIVED, BASE) \ - case Decl::DERIVED: return ASTNodeKind(NKI_##DERIVED##Decl); + case Decl::DERIVED: \ + return ASTNodeKind(NKI_##DERIVED##Decl); #define ABSTRACT_DECL(D) #include "clang/AST/DeclNodes.inc" }; llvm_unreachable("invalid decl kind"); } -ASTNodeKind ASTNodeKind::getFromNode(const Stmt &S) { +ASTNodeKind ASTNodeKind::getFromNode(Stmt const &S) { switch (S.getStmtClass()) { - case Stmt::NoStmtClass: return NKI_None; + case Stmt::NoStmtClass: + return NKI_None; #define STMT(CLASS, PARENT) \ - case Stmt::CLASS##Class: return ASTNodeKind(NKI_##CLASS); + case Stmt::CLASS##Class: \ + return ASTNodeKind(NKI_##CLASS); #define ABSTRACT_STMT(S) #include "clang/AST/StmtNodes.inc" } llvm_unreachable("invalid stmt kind"); } -ASTNodeKind ASTNodeKind::getFromNode(const Type &T) { +ASTNodeKind ASTNodeKind::getFromNode(Type const &T) { switch (T.getTypeClass()) { #define TYPE(Class, Base) \ - case Type::Class: return ASTNodeKind(NKI_##Class##Type); + case Type::Class: \ + return ASTNodeKind(NKI_##Class##Type); #define ABSTRACT_TYPE(Class, Base) #include "clang/AST/TypeNodes.inc" } llvm_unreachable("invalid type kind"); - } +} -ASTNodeKind ASTNodeKind::getFromNode(const OMPClause &C) { +ASTNodeKind ASTNodeKind::getFromNode(OMPClause const &C) { switch (C.getClauseKind()) { #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) \ @@ -141,7 +148,7 @@ llvm_unreachable("invalid omp clause kind"); } -ASTNodeKind ASTNodeKind::getFromNode(const Attr &A) { +ASTNodeKind ASTNodeKind::getFromNode(Attr const &A) { switch (A.getKind()) { #define ATTR(A) \ case attr::A: \ @@ -152,66 +159,66 @@ } void DynTypedNode::print(llvm::raw_ostream &OS, - const PrintingPolicy &PP) const { - if (const TemplateArgument *TA = get()) + PrintingPolicy const &PP) const { + if (TemplateArgument const *TA = get()) TA->print(PP, OS, /*IncludeType*/ true); - else if (const TemplateArgumentLoc *TAL = get()) + else if (TemplateArgumentLoc const *TAL = get()) TAL->getArgument().print(PP, OS, /*IncludeType*/ true); - else if (const TemplateName *TN = get()) + else if (TemplateName const *TN = get()) TN->print(OS, PP); - else if (const NestedNameSpecifier *NNS = get()) + else if (NestedNameSpecifier const *NNS = get()) NNS->print(OS, PP); - else if (const NestedNameSpecifierLoc *NNSL = get()) { - if (const NestedNameSpecifier *NNS = NNSL->getNestedNameSpecifier()) + else if (NestedNameSpecifierLoc const *NNSL = get()) { + if (NestedNameSpecifier const *NNS = NNSL->getNestedNameSpecifier()) NNS->print(OS, PP); else OS << "(empty NestedNameSpecifierLoc)"; - } else if (const QualType *QT = get()) + } else if (QualType const *QT = get()) QT->print(OS, PP); - else if (const TypeLoc *TL = get()) + else if (TypeLoc const *TL = get()) TL->getType().print(OS, PP); - else if (const Decl *D = get()) + else if (Decl const *D = get()) D->print(OS, PP); - else if (const Stmt *S = get()) + else if (Stmt const *S = get()) S->printPretty(OS, nullptr, PP); - else if (const Type *T = get()) + else if (Type const *T = get()) QualType(T, 0).print(OS, PP); - else if (const Attr *A = get()) + else if (Attr const *A = get()) A->printPretty(OS, PP); else OS << "Unable to print values of type " << NodeKind.asStringRef() << "\n"; } void DynTypedNode::dump(llvm::raw_ostream &OS, - const ASTContext &Context) const { - if (const Decl *D = get()) + ASTContext const &Context) const { + if (Decl const *D = get()) D->dump(OS); - else if (const Stmt *S = get()) + else if (Stmt const *S = get()) S->dump(OS, Context); - else if (const Type *T = get()) + else if (Type const *T = get()) T->dump(OS, Context); else OS << "Unable to dump values of type " << NodeKind.asStringRef() << "\n"; } SourceRange DynTypedNode::getSourceRange() const { - if (const CXXCtorInitializer *CCI = get()) + if (CXXCtorInitializer const *CCI = get()) return CCI->getSourceRange(); - if (const NestedNameSpecifierLoc *NNSL = get()) + if (NestedNameSpecifierLoc const *NNSL = get()) return NNSL->getSourceRange(); - if (const TypeLoc *TL = get()) + if (TypeLoc const *TL = get()) return TL->getSourceRange(); - if (const Decl *D = get()) + if (Decl const *D = get()) return D->getSourceRange(); - if (const Stmt *S = get()) + if (Stmt const *S = get()) return S->getSourceRange(); - if (const TemplateArgumentLoc *TAL = get()) + if (TemplateArgumentLoc const *TAL = get()) return TAL->getSourceRange(); - if (const auto *C = get()) + if (auto const *C = get()) return SourceRange(C->getBeginLoc(), C->getEndLoc()); - if (const auto *CBS = get()) + if (auto const *CBS = get()) return CBS->getSourceRange(); - if (const auto *A = get()) + if (auto const *A = get()) return A->getRange(); return SourceRange(); } Index: clang/lib/AST/AttrDocTable.cpp =================================================================== --- clang/lib/AST/AttrDocTable.cpp +++ clang/lib/AST/AttrDocTable.cpp @@ -21,7 +21,7 @@ }; llvm::StringRef clang::Attr::getDocumentation(clang::attr::Kind K) { - if(K < llvm::array_lengthof(AttrDoc)) + if (K < llvm::array_lengthof(AttrDoc)) return AttrDoc[K]; return ""; } Index: clang/lib/AST/AttrImpl.cpp =================================================================== --- clang/lib/AST/AttrImpl.cpp +++ clang/lib/AST/AttrImpl.cpp @@ -17,7 +17,7 @@ using namespace clang; void LoopHintAttr::printPrettyPragma(raw_ostream &OS, - const PrintingPolicy &Policy) const { + PrintingPolicy const &Policy) const { unsigned SpellingIndex = getAttributeSpellingListIndex(); // For "#pragma unroll" and "#pragma nounroll" the string "unroll" or // "nounroll" is already emitted as the pragma name. @@ -36,7 +36,7 @@ // Return a string containing the loop hint argument including the // enclosing parentheses. -std::string LoopHintAttr::getValueString(const PrintingPolicy &Policy) const { +std::string LoopHintAttr::getValueString(PrintingPolicy const &Policy) const { std::string ValueName; llvm::raw_string_ostream OS(ValueName); OS << "("; @@ -65,7 +65,7 @@ // Return a string suitable for identifying this attribute in diagnostics. std::string -LoopHintAttr::getDiagnosticName(const PrintingPolicy &Policy) const { +LoopHintAttr::getDiagnosticName(PrintingPolicy const &Policy) const { unsigned SpellingIndex = getAttributeSpellingListIndex(); if (SpellingIndex == Pragma_nounroll) return "#pragma nounroll"; @@ -83,7 +83,7 @@ } void OMPDeclareSimdDeclAttr::printPrettyPragma( - raw_ostream &OS, const PrintingPolicy &Policy) const { + raw_ostream &OS, PrintingPolicy const &Policy) const { if (getBranchState() != BS_Undefined) OS << ' ' << ConvertBranchStateTyToStr(getBranchState()); if (auto *E = getSimdlen()) { @@ -133,7 +133,7 @@ } void OMPDeclareTargetDeclAttr::printPrettyPragma( - raw_ostream &OS, const PrintingPolicy &Policy) const { + raw_ostream &OS, PrintingPolicy const &Policy) const { // Use fake syntax because it is for testing and debugging purpose only. if (getDevType() != DT_Any) OS << " device_type(" << ConvertDevTypeTyToStr(getDevType()) << ")"; @@ -142,7 +142,7 @@ } llvm::Optional -OMPDeclareTargetDeclAttr::getActiveAttr(const ValueDecl *VD) { +OMPDeclareTargetDeclAttr::getActiveAttr(ValueDecl const *VD) { if (!VD->hasAttrs()) return llvm::None; unsigned Level = 0; @@ -159,7 +159,7 @@ } llvm::Optional -OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(const ValueDecl *VD) { +OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(ValueDecl const *VD) { llvm::Optional ActiveAttr = getActiveAttr(VD); if (ActiveAttr.hasValue()) return ActiveAttr.getValue()->getMapType(); @@ -167,7 +167,7 @@ } llvm::Optional -OMPDeclareTargetDeclAttr::getDeviceType(const ValueDecl *VD) { +OMPDeclareTargetDeclAttr::getDeviceType(ValueDecl const *VD) { llvm::Optional ActiveAttr = getActiveAttr(VD); if (ActiveAttr.hasValue()) return ActiveAttr.getValue()->getDevType(); @@ -175,7 +175,7 @@ } llvm::Optional -OMPDeclareTargetDeclAttr::getLocation(const ValueDecl *VD) { +OMPDeclareTargetDeclAttr::getLocation(ValueDecl const *VD) { llvm::Optional ActiveAttr = getActiveAttr(VD); if (ActiveAttr.hasValue()) return ActiveAttr.getValue()->getRange().getBegin(); @@ -183,13 +183,13 @@ } namespace clang { -llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo &TI); -llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo *TI); -} +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, OMPTraitInfo const &TI); +llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, OMPTraitInfo const *TI); +} // namespace clang void OMPDeclareVariantAttr::printPrettyPragma( - raw_ostream &OS, const PrintingPolicy &Policy) const { - if (const Expr *E = getVariantFuncRef()) { + raw_ostream &OS, PrintingPolicy const &Policy) const { + if (Expr const *E = getVariantFuncRef()) { OS << "("; E->printPretty(OS, nullptr, Policy); OS << ")"; Index: clang/lib/AST/CXXInheritance.cpp =================================================================== --- clang/lib/AST/CXXInheritance.cpp +++ clang/lib/AST/CXXInheritance.cpp @@ -27,8 +27,8 @@ #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Casting.h" #include -#include #include +#include #include using namespace clang; @@ -65,28 +65,28 @@ std::swap(DetectedVirtual, Other.DetectedVirtual); } -bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const { +bool CXXRecordDecl::isDerivedFrom(CXXRecordDecl const *Base) const { CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false, /*DetectVirtual=*/false); return isDerivedFrom(Base, Paths); } -bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base, +bool CXXRecordDecl::isDerivedFrom(CXXRecordDecl const *Base, CXXBasePaths &Paths) const { if (getCanonicalDecl() == Base->getCanonicalDecl()) return false; - Paths.setOrigin(const_cast(this)); + Paths.setOrigin(const_cast(this)); - const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl(); + CXXRecordDecl const *BaseDecl = Base->getCanonicalDecl(); return lookupInBases( - [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { + [BaseDecl](CXXBaseSpecifier const *Specifier, CXXBasePath &Path) { return FindBaseClass(Specifier, Path, BaseDecl); }, Paths); } -bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const { +bool CXXRecordDecl::isVirtuallyDerivedFrom(CXXRecordDecl const *Base) const { if (!getNumVBases()) return false; @@ -96,25 +96,25 @@ if (getCanonicalDecl() == Base->getCanonicalDecl()) return false; - Paths.setOrigin(const_cast(this)); + Paths.setOrigin(const_cast(this)); - const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl(); + CXXRecordDecl const *BaseDecl = Base->getCanonicalDecl(); return lookupInBases( - [BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { + [BaseDecl](CXXBaseSpecifier const *Specifier, CXXBasePath &Path) { return FindVirtualBaseClass(Specifier, Path, BaseDecl); }, Paths); } -bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const { - const CXXRecordDecl *TargetDecl = Base->getCanonicalDecl(); - return forallBases([TargetDecl](const CXXRecordDecl *Base) { +bool CXXRecordDecl::isProvablyNotDerivedFrom(CXXRecordDecl const *Base) const { + CXXRecordDecl const *TargetDecl = Base->getCanonicalDecl(); + return forallBases([TargetDecl](CXXRecordDecl const *Base) { return Base->getCanonicalDecl() != TargetDecl; }); } -bool -CXXRecordDecl::isCurrentInstantiation(const DeclContext *CurContext) const { +bool CXXRecordDecl::isCurrentInstantiation( + DeclContext const *CurContext) const { assert(isDependentContext()); for (; !CurContext->isFileContext(); CurContext = CurContext->getParent()) @@ -125,20 +125,19 @@ } bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches) const { - SmallVector Queue; + SmallVector Queue; - const CXXRecordDecl *Record = this; + CXXRecordDecl const *Record = this; while (true) { - for (const auto &I : Record->bases()) { - const RecordType *Ty = I.getType()->getAs(); + for (auto const &I : Record->bases()) { + RecordType const *Ty = I.getType()->getAs(); if (!Ty) return false; CXXRecordDecl *Base = - cast_or_null(Ty->getDecl()->getDefinition()); - if (!Base || - (Base->isDependentContext() && - !Base->isCurrentInstantiation(Record))) { + cast_or_null(Ty->getDecl()->getDefinition()); + if (!Base || (Base->isDependentContext() && + !Base->isCurrentInstantiation(Record))) { return false; } @@ -156,7 +155,7 @@ } bool CXXBasePaths::lookupInBases(ASTContext &Context, - const CXXRecordDecl *Record, + CXXRecordDecl const *Record, CXXRecordDecl::BaseMatchesCallback BaseMatches, bool LookupInDependent) { bool FoundPath = false; @@ -165,7 +164,7 @@ AccessSpecifier AccessToHere = ScratchPath.Access; bool IsFirstStep = ScratchPath.empty(); - for (const auto &BaseSpec : Record->bases()) { + for (auto const &BaseSpec : Record->bases()) { // Find the record of the base class subobjects for this type. QualType BaseType = Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType(); @@ -225,8 +224,8 @@ if (IsFirstStep) ScratchPath.Access = BaseSpec.getAccessSpecifier(); else - ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere, - BaseSpec.getAccessSpecifier()); + ScratchPath.Access = CXXRecordDecl::MergeAccess( + AccessToHere, BaseSpec.getAccessSpecifier()); } // Track whether there's a path involving this specific base. @@ -247,7 +246,7 @@ CXXRecordDecl *BaseRecord; if (LookupInDependent) { BaseRecord = nullptr; - const TemplateSpecializationType *TST = + TemplateSpecializationType const *TST = BaseSpec.getType()->getAs(); if (!TST) { if (auto *RT = BaseSpec.getType()->getAs()) @@ -327,7 +326,7 @@ // // FIXME: This is an O(N^2) algorithm, but DPG doesn't see an easy // way to make it any faster. - Paths.Paths.remove_if([&Paths](const CXXBasePath &Path) { + Paths.Paths.remove_if([&Paths](CXXBasePath const &Path) { for (const CXXBasePathElement &PE : Path) { if (!PE.Base->isVirtual()) continue; @@ -360,31 +359,34 @@ return true; } -bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier, +bool CXXRecordDecl::FindBaseClass(CXXBaseSpecifier const *Specifier, CXXBasePath &Path, - const CXXRecordDecl *BaseRecord) { + CXXRecordDecl const *BaseRecord) { assert(BaseRecord->getCanonicalDecl() == BaseRecord && "User data for FindBaseClass is not canonical!"); - return Specifier->getType()->castAs()->getDecl() - ->getCanonicalDecl() == BaseRecord; + return Specifier->getType() + ->castAs() + ->getDecl() + ->getCanonicalDecl() == BaseRecord; } -bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, +bool CXXRecordDecl::FindVirtualBaseClass(CXXBaseSpecifier const *Specifier, CXXBasePath &Path, - const CXXRecordDecl *BaseRecord) { + CXXRecordDecl const *BaseRecord) { assert(BaseRecord->getCanonicalDecl() == BaseRecord && "User data for FindBaseClass is not canonical!"); - return Specifier->isVirtual() && - Specifier->getType()->castAs()->getDecl() - ->getCanonicalDecl() == BaseRecord; + return Specifier->isVirtual() && Specifier->getType() + ->castAs() + ->getDecl() + ->getCanonicalDecl() == BaseRecord; } -static bool isOrdinaryMember(const NamedDecl *ND) { +static bool isOrdinaryMember(NamedDecl const *ND) { return ND->isInIdentifierNamespace(Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member); } -static bool findOrdinaryMember(const CXXRecordDecl *RD, CXXBasePath &Path, +static bool findOrdinaryMember(CXXRecordDecl const *RD, CXXBasePath &Path, DeclarationName Name) { Path.Decls = RD->lookup(Name).begin(); for (DeclContext::lookup_iterator I = Path.Decls, E = I.end(); I != E; ++I) @@ -401,7 +403,7 @@ CXXBasePaths Paths(false, false, false); return lookupInBases( - [Name](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { + [Name](CXXBaseSpecifier const *Specifier, CXXBasePath &Path) { return findOrdinaryMember(Specifier->getType()->getAsCXXRecordDecl(), Path, Name); }, @@ -409,9 +411,9 @@ } static bool -findOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier, +findOrdinaryMemberInDependentClasses(CXXBaseSpecifier const *Specifier, CXXBasePath &Path, DeclarationName Name) { - const TemplateSpecializationType *TST = + TemplateSpecializationType const *TST = Specifier->getType()->getAs(); if (!TST) { auto *RT = Specifier->getType()->getAs(); @@ -420,7 +422,7 @@ return findOrdinaryMember(cast(RT->getDecl()), Path, Name); } TemplateName TN = TST->getTemplateName(); - const auto *TD = dyn_cast_or_null(TN.getAsTemplateDecl()); + auto const *TD = dyn_cast_or_null(TN.getAsTemplateDecl()); if (!TD) return false; CXXRecordDecl *RD = TD->getTemplatedDecl(); @@ -429,13 +431,13 @@ return findOrdinaryMember(RD, Path, Name); } -std::vector CXXRecordDecl::lookupDependentName( +std::vector CXXRecordDecl::lookupDependentName( DeclarationName Name, - llvm::function_ref Filter) { - std::vector Results; + llvm::function_ref Filter) { + std::vector Results; // Lookup in the class. bool AnyOrdinaryMembers = false; - for (const NamedDecl *ND : lookup(Name)) { + for (NamedDecl const *ND : lookup(Name)) { if (isOrdinaryMember(ND)) AnyOrdinaryMembers = true; if (Filter(ND)) @@ -448,7 +450,7 @@ CXXBasePaths Paths; Paths.setOrigin(this); if (!lookupInBases( - [&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { + [&](CXXBaseSpecifier const *Specifier, CXXBasePath &Path) { return findOrdinaryMemberInDependentClasses(Specifier, Path, Name); }, Paths, /*LookupInDependent=*/true)) @@ -463,18 +465,17 @@ void OverridingMethods::add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding) { - SmallVectorImpl &SubobjectOverrides - = Overrides[OverriddenSubobject]; + SmallVectorImpl &SubobjectOverrides = + Overrides[OverriddenSubobject]; if (llvm::find(SubobjectOverrides, Overriding) == SubobjectOverrides.end()) SubobjectOverrides.push_back(Overriding); } -void OverridingMethods::add(const OverridingMethods &Other) { +void OverridingMethods::add(OverridingMethods const &Other) { for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) { for (overriding_const_iterator M = I->second.begin(), - MEnd = I->second.end(); - M != MEnd; - ++M) + MEnd = I->second.end(); + M != MEnd; ++M) add(I->first, *M); } } @@ -491,35 +492,35 @@ class FinalOverriderCollector { /// The number of subobjects of a given class type that /// occur within the class hierarchy. - llvm::DenseMap SubobjectCount; + llvm::DenseMap SubobjectCount; /// Overriders for each virtual base subobject. - llvm::DenseMap VirtualOverriders; + llvm::DenseMap + VirtualOverriders; CXXFinalOverriderMap FinalOverriders; public: ~FinalOverriderCollector(); - void Collect(const CXXRecordDecl *RD, bool VirtualBase, - const CXXRecordDecl *InVirtualSubobject, + void Collect(CXXRecordDecl const *RD, bool VirtualBase, + CXXRecordDecl const *InVirtualSubobject, CXXFinalOverriderMap &Overriders); }; } // namespace -void FinalOverriderCollector::Collect(const CXXRecordDecl *RD, - bool VirtualBase, - const CXXRecordDecl *InVirtualSubobject, +void FinalOverriderCollector::Collect(CXXRecordDecl const *RD, bool VirtualBase, + CXXRecordDecl const *InVirtualSubobject, CXXFinalOverriderMap &Overriders) { unsigned SubobjectNumber = 0; if (!VirtualBase) - SubobjectNumber - = ++SubobjectCount[cast(RD->getCanonicalDecl())]; + SubobjectNumber = + ++SubobjectCount[cast(RD->getCanonicalDecl())]; - for (const auto &Base : RD->bases()) { - if (const RecordType *RT = Base.getType()->getAs()) { - const CXXRecordDecl *BaseDecl = cast(RT->getDecl()); + for (auto const &Base : RD->bases()) { + if (RecordType const *RT = Base.getType()->getAs()) { + CXXRecordDecl const *BaseDecl = cast(RT->getDecl()); if (!BaseDecl->isPolymorphic()) continue; @@ -538,7 +539,8 @@ CXXFinalOverriderMap ComputedBaseOverriders; CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders; if (Base.isVirtual()) { - CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl]; + CXXFinalOverriderMap *&MyVirtualOverriders = + VirtualOverriders[BaseDecl]; BaseOverriders = MyVirtualOverriders; if (!MyVirtualOverriders) { MyVirtualOverriders = new CXXFinalOverriderMap; @@ -556,10 +558,9 @@ // Merge the overriders from this base class into our own set of // overriders. for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(), - OMEnd = BaseOverriders->end(); - OM != OMEnd; - ++OM) { - const CXXMethodDecl *CanonOM = OM->first->getCanonicalDecl(); + OMEnd = BaseOverriders->end(); + OM != OMEnd; ++OM) { + CXXMethodDecl const *CanonOM = OM->first->getCanonicalDecl(); Overriders[CanonOM].add(OM->second); } } @@ -582,9 +583,9 @@ // C++ [class.virtual]p2: // For convenience we say that any virtual function overrides itself. - Overriders[CanonM].add(SubobjectNumber, - UniqueVirtualMethod(CanonM, SubobjectNumber, - InVirtualSubobject)); + Overriders[CanonM].add( + SubobjectNumber, + UniqueVirtualMethod(CanonM, SubobjectNumber, InVirtualSubobject)); continue; } @@ -596,8 +597,8 @@ // overrides. SmallVector Stack(1, OverriddenMethods); while (!Stack.empty()) { - for (const CXXMethodDecl *OM : Stack.pop_back_val()) { - const CXXMethodDecl *CanonOM = OM->getCanonicalDecl(); + for (CXXMethodDecl const *OM : Stack.pop_back_val()) { + CXXMethodDecl const *CanonOM = OM->getCanonicalDecl(); // C++ [class.virtual]p2: // A virtual member function C::vf of a class object S is @@ -609,8 +610,7 @@ // replace any overrides from base classes with this // overriding virtual function. Overriders[CanonOM].replaceAll( - UniqueVirtualMethod(CanonM, SubobjectNumber, - InVirtualSubobject)); + UniqueVirtualMethod(CanonM, SubobjectNumber, InVirtualSubobject)); auto OverriddenMethods = CanonOM->overridden_methods(); if (OverriddenMethods.begin() == OverriddenMethods.end()) @@ -624,22 +624,22 @@ // C++ [class.virtual]p2: // For convenience we say that any virtual function overrides itself. - Overriders[CanonM].add(SubobjectNumber, - UniqueVirtualMethod(CanonM, SubobjectNumber, - InVirtualSubobject)); + Overriders[CanonM].add( + SubobjectNumber, + UniqueVirtualMethod(CanonM, SubobjectNumber, InVirtualSubobject)); } } FinalOverriderCollector::~FinalOverriderCollector() { - for (llvm::DenseMap::iterator - VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end(); - VO != VOEnd; - ++VO) + for (llvm::DenseMap::iterator + VO = VirtualOverriders.begin(), + VOEnd = VirtualOverriders.end(); + VO != VOEnd; ++VO) delete VO->second; } -void -CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const { +void CXXRecordDecl::getFinalOverriders( + CXXFinalOverriderMap &FinalOverriders) const { FinalOverriderCollector Collector; Collector.Collect(this, false, nullptr, FinalOverriders); @@ -652,7 +652,7 @@ if (Overriding.size() < 2) continue; - auto IsHidden = [&Overriding](const UniqueVirtualMethod &M) { + auto IsHidden = [&Overriding](UniqueVirtualMethod const &M) { if (!M.InVirtualSubobject) return false; @@ -662,9 +662,8 @@ // in a base class subobject that hides the virtual base class // subobject. for (const UniqueVirtualMethod &OP : Overriding) - if (&M != &OP && - OP.Method->getParent()->isVirtuallyDerivedFrom( - M.InVirtualSubobject)) + if (&M != &OP && OP.Method->getParent()->isVirtuallyDerivedFrom( + M.InVirtualSubobject)) return true; return false; }; @@ -678,42 +677,41 @@ } } -static void -AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context, - CXXIndirectPrimaryBaseSet& Bases) { +static void AddIndirectPrimaryBases(CXXRecordDecl const *RD, + ASTContext &Context, + CXXIndirectPrimaryBaseSet &Bases) { // If the record has a virtual primary base class, add it to our set. - const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); + ASTRecordLayout const &Layout = Context.getASTRecordLayout(RD); if (Layout.isPrimaryBaseVirtual()) Bases.insert(Layout.getPrimaryBase()); - for (const auto &I : RD->bases()) { + for (auto const &I : RD->bases()) { assert(!I.getType()->isDependentType() && "Cannot get indirect primary bases for class with dependent bases."); - const CXXRecordDecl *BaseDecl = - cast(I.getType()->castAs()->getDecl()); + CXXRecordDecl const *BaseDecl = + cast(I.getType()->castAs()->getDecl()); // Only bases with virtual bases participate in computing the // indirect primary virtual base classes. if (BaseDecl->getNumVBases()) AddIndirectPrimaryBases(BaseDecl, Context, Bases); } - } -void -CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const { +void CXXRecordDecl::getIndirectPrimaryBases( + CXXIndirectPrimaryBaseSet &Bases) const { ASTContext &Context = getASTContext(); if (!getNumVBases()) return; - for (const auto &I : bases()) { + for (auto const &I : bases()) { assert(!I.getType()->isDependentType() && "Cannot get indirect primary bases for class with dependent bases."); - const CXXRecordDecl *BaseDecl = - cast(I.getType()->castAs()->getDecl()); + CXXRecordDecl const *BaseDecl = + cast(I.getType()->castAs()->getDecl()); // Only bases with virtual bases participate in computing the // indirect primary virtual base classes. Index: clang/lib/AST/Comment.cpp =================================================================== --- clang/lib/AST/Comment.cpp +++ clang/lib/AST/Comment.cpp @@ -32,12 +32,13 @@ static_assert(std::is_trivially_destructible::value, "DeclInfo should be trivially destructible!"); -const char *Comment::getCommentKindName() const { +char const *Comment::getCommentKindName() const { switch (getCommentKind()) { - case NoCommentKind: return "NoCommentKind"; + case NoCommentKind: + return "NoCommentKind"; #define ABSTRACT_COMMENT(COMMENT) -#define COMMENT(CLASS, PARENT) \ - case CLASS##Kind: \ +#define COMMENT(CLASS, PARENT) \ + case CLASS##Kind: \ return #CLASS; #include "clang/AST/CommentNodes.inc" #undef COMMENT @@ -56,19 +57,19 @@ } LLVM_ATTRIBUTE_UNUSED -static inline bad implements_child_begin_end( - Comment::child_iterator (Comment::*)() const) { +inline static bad +implements_child_begin_end(Comment::child_iterator (Comment::*)() const) { return bad(); } -#define ASSERT_IMPLEMENTS_child_begin(function) \ - (void) good(implements_child_begin_end(function)) +#define ASSERT_IMPLEMENTS_child_begin(function) \ + (void)good(implements_child_begin_end(function)) LLVM_ATTRIBUTE_UNUSED -static inline void CheckCommentASTNodes() { +inline static void CheckCommentASTNodes() { #define ABSTRACT_COMMENT(COMMENT) -#define COMMENT(CLASS, PARENT) \ - ASSERT_IMPLEMENTS_child_begin(&CLASS::child_begin); \ +#define COMMENT(CLASS, PARENT) \ + ASSERT_IMPLEMENTS_child_begin(&CLASS::child_begin); \ ASSERT_IMPLEMENTS_child_begin(&CLASS::child_end); #include "clang/AST/CommentNodes.inc" #undef COMMENT @@ -81,10 +82,11 @@ Comment::child_iterator Comment::child_begin() const { switch (getCommentKind()) { - case NoCommentKind: llvm_unreachable("comment without a kind"); + case NoCommentKind: + llvm_unreachable("comment without a kind"); #define ABSTRACT_COMMENT(COMMENT) -#define COMMENT(CLASS, PARENT) \ - case CLASS##Kind: \ +#define COMMENT(CLASS, PARENT) \ + case CLASS##Kind: \ return static_cast(this)->child_begin(); #include "clang/AST/CommentNodes.inc" #undef COMMENT @@ -95,10 +97,11 @@ Comment::child_iterator Comment::child_end() const { switch (getCommentKind()) { - case NoCommentKind: llvm_unreachable("comment without a kind"); + case NoCommentKind: + llvm_unreachable("comment without a kind"); #define ABSTRACT_COMMENT(COMMENT) -#define COMMENT(CLASS, PARENT) \ - case CLASS##Kind: \ +#define COMMENT(CLASS, PARENT) \ + case CLASS##Kind: \ return static_cast(this)->child_end(); #include "clang/AST/CommentNodes.inc" #undef COMMENT @@ -108,8 +111,8 @@ } bool TextComment::isWhitespaceNoCache() const { - for (StringRef::const_iterator I = Text.begin(), E = Text.end(); - I != E; ++I) { + for (StringRef::const_iterator I = Text.begin(), E = Text.end(); I != E; + ++I) { if (!clang::isWhitespace(*I)) return false; } @@ -118,7 +121,7 @@ bool ParagraphComment::isWhitespaceNoCache() const { for (child_iterator I = child_begin(), E = child_end(); I != E; ++I) { - if (const TextComment *TC = dyn_cast(*I)) { + if (TextComment const *TC = dyn_cast(*I)) { if (!TC->isWhitespace()) return false; } else @@ -189,7 +192,7 @@ return false; } -const char *ParamCommandComment::getDirectionAsString(PassDirection D) { +char const *ParamCommandComment::getDirectionAsString(PassDirection D) { switch (D) { case ParamCommandComment::In: return "[in]"; @@ -230,27 +233,26 @@ case Decl::CXXConstructor: case Decl::CXXDestructor: case Decl::CXXConversion: { - const FunctionDecl *FD = cast(CommentDecl); + FunctionDecl const *FD = cast(CommentDecl); Kind = FunctionKind; ParamVars = FD->parameters(); ReturnType = FD->getReturnType(); unsigned NumLists = FD->getNumTemplateParameterLists(); if (NumLists != 0) { TemplateKind = TemplateSpecialization; - TemplateParameters = - FD->getTemplateParameterList(NumLists - 1); + TemplateParameters = FD->getTemplateParameterList(NumLists - 1); } if (K == Decl::CXXMethod || K == Decl::CXXConstructor || K == Decl::CXXDestructor || K == Decl::CXXConversion) { - const CXXMethodDecl *MD = cast(CommentDecl); + CXXMethodDecl const *MD = cast(CommentDecl); IsInstanceMethod = MD->isInstance(); IsClassMethod = !IsInstanceMethod; } break; } case Decl::ObjCMethod: { - const ObjCMethodDecl *MD = cast(CommentDecl); + ObjCMethodDecl const *MD = cast(CommentDecl); Kind = FunctionKind; ParamVars = MD->parameters(); ReturnType = MD->getReturnType(); @@ -260,24 +262,24 @@ break; } case Decl::FunctionTemplate: { - const FunctionTemplateDecl *FTD = cast(CommentDecl); + FunctionTemplateDecl const *FTD = cast(CommentDecl); Kind = FunctionKind; TemplateKind = Template; - const FunctionDecl *FD = FTD->getTemplatedDecl(); + FunctionDecl const *FD = FTD->getTemplatedDecl(); ParamVars = FD->parameters(); ReturnType = FD->getReturnType(); TemplateParameters = FTD->getTemplateParameters(); break; } case Decl::ClassTemplate: { - const ClassTemplateDecl *CTD = cast(CommentDecl); + ClassTemplateDecl const *CTD = cast(CommentDecl); Kind = ClassKind; TemplateKind = Template; TemplateParameters = CTD->getTemplateParameters(); break; } case Decl::ClassTemplatePartialSpecialization: { - const ClassTemplatePartialSpecializationDecl *CTPSD = + ClassTemplatePartialSpecializationDecl const *CTPSD = cast(CommentDecl); Kind = ClassKind; TemplateKind = TemplatePartialSpecialization; @@ -298,10 +300,10 @@ case Decl::ObjCIvar: case Decl::ObjCAtDefsField: case Decl::ObjCProperty: { - const TypeSourceInfo *TSI; - if (const auto *VD = dyn_cast(CommentDecl)) + TypeSourceInfo const *TSI; + if (auto const *VD = dyn_cast(CommentDecl)) TSI = VD->getTypeSourceInfo(); - else if (const auto *PD = dyn_cast(CommentDecl)) + else if (auto const *PD = dyn_cast(CommentDecl)) TSI = PD->getTypeSourceInfo(); else TSI = nullptr; @@ -324,7 +326,7 @@ Kind = TypedefKind; // If this is a typedef / using to something we consider a function, extract // arguments and return type. - const TypeSourceInfo *TSI = + TypeSourceInfo const *TSI = K == Decl::Typedef ? cast(CommentDecl)->getTypeSourceInfo() : cast(CommentDecl)->getTypeSourceInfo(); @@ -340,7 +342,7 @@ break; } case Decl::TypeAliasTemplate: { - const TypeAliasTemplateDecl *TAT = cast(CommentDecl); + TypeAliasTemplateDecl const *TAT = cast(CommentDecl); Kind = TypedefKind; TemplateKind = Template; TemplateParameters = TAT->getTemplateParameters(); @@ -348,7 +350,7 @@ if (!TAD) break; - const TypeSourceInfo *TSI = TAD->getTypeSourceInfo(); + TypeSourceInfo const *TSI = TAD->getTypeSourceInfo(); if (!TSI) break; TypeLoc TL = TSI->getTypeLoc().getUnqualifiedLoc(); @@ -368,21 +370,21 @@ IsFilled = true; } -StringRef ParamCommandComment::getParamName(const FullComment *FC) const { +StringRef ParamCommandComment::getParamName(FullComment const *FC) const { assert(isParamIndexValid()); if (isVarArgParam()) return "..."; return FC->getDeclInfo()->ParamVars[getParamIndex()]->getName(); } -StringRef TParamCommandComment::getParamName(const FullComment *FC) const { +StringRef TParamCommandComment::getParamName(FullComment const *FC) const { assert(isPositionValid()); - const TemplateParameterList *TPL = FC->getDeclInfo()->TemplateParameters; + TemplateParameterList const *TPL = FC->getDeclInfo()->TemplateParameters; for (unsigned i = 0, e = getDepth(); i != e; ++i) { assert(TPL && "Unknown TemplateParameterList"); if (i == e - 1) return TPL->getParam(getIndex(i))->getName(); - const NamedDecl *Param = TPL->getParam(getIndex(i)); + NamedDecl const *Param = TPL->getParam(getIndex(i)); if (auto *TTP = dyn_cast(Param)) TPL = TTP->getTemplateParameters(); } @@ -391,4 +393,3 @@ } // end namespace comments } // end namespace clang - Index: clang/lib/AST/CommentBriefParser.cpp =================================================================== --- clang/lib/AST/CommentBriefParser.cpp +++ clang/lib/AST/CommentBriefParser.cpp @@ -14,8 +14,8 @@ namespace { inline bool isWhitespace(char C) { - return C == ' ' || C == '\n' || C == '\r' || - C == '\t' || C == '\f' || C == '\v'; + return C == ' ' || C == '\n' || C == '\r' || C == '\t' || C == '\f' || + C == '\v'; } /// Convert all whitespace into spaces, remove leading and trailing spaces, @@ -23,9 +23,8 @@ void cleanupBrief(std::string &S) { bool PrevWasSpace = true; std::string::iterator O = S.begin(); - for (std::string::iterator I = S.begin(), E = S.end(); - I != E; ++I) { - const char C = *I; + for (std::string::iterator I = S.begin(), E = S.end(); I != E; ++I) { + char const C = *I; if (isWhitespace(C)) { if (!PrevWasSpace) { *O++ = ' '; @@ -44,8 +43,8 @@ } bool isWhitespace(StringRef Text) { - for (StringRef::const_iterator I = Text.begin(), E = Text.end(); - I != E; ++I) { + for (StringRef::const_iterator I = Text.begin(), E = Text.end(); I != E; + ++I) { if (!isWhitespace(*I)) return false; } @@ -53,8 +52,8 @@ } } // unnamed namespace -BriefParser::BriefParser(Lexer &L, const CommandTraits &Traits) : - L(L), Traits(Traits) { +BriefParser::BriefParser(Lexer &L, CommandTraits const &Traits) + : L(L), Traits(Traits) { // Get lookahead token. ConsumeToken(); } @@ -77,7 +76,7 @@ } if (Tok.is(tok::backslash_command) || Tok.is(tok::at_command)) { - const CommandInfo *Info = Traits.getCommandInfo(Tok.getCommandID()); + CommandInfo const *Info = Traits.getCommandInfo(Tok.getCommandID()); if (Info->IsBriefCommand) { FirstParagraphOrBrief.clear(); InBrief = true; @@ -149,5 +148,3 @@ } // end namespace comments } // end namespace clang - - Index: clang/lib/AST/CommentCommandTraits.cpp =================================================================== --- clang/lib/AST/CommentCommandTraits.cpp +++ clang/lib/AST/CommentCommandTraits.cpp @@ -16,13 +16,13 @@ #include "clang/AST/CommentCommandInfo.inc" CommandTraits::CommandTraits(llvm::BumpPtrAllocator &Allocator, - const CommentOptions &CommentOptions) : - NextID(llvm::array_lengthof(Commands)), Allocator(Allocator) { + CommentOptions const &CommentOptions) + : NextID(llvm::array_lengthof(Commands)), Allocator(Allocator) { registerCommentOptions(CommentOptions); } void CommandTraits::registerCommentOptions( - const CommentOptions &CommentOptions) { + CommentOptions const &CommentOptions) { for (CommentOptions::BlockCommandNamesTy::const_iterator I = CommentOptions.BlockCommandNames.begin(), E = CommentOptions.BlockCommandNames.end(); @@ -31,19 +31,19 @@ } } -const CommandInfo *CommandTraits::getCommandInfoOrNULL(StringRef Name) const { - if (const CommandInfo *Info = getBuiltinCommandInfo(Name)) +CommandInfo const *CommandTraits::getCommandInfoOrNULL(StringRef Name) const { + if (CommandInfo const *Info = getBuiltinCommandInfo(Name)) return Info; return getRegisteredCommandInfo(Name); } -const CommandInfo *CommandTraits::getCommandInfo(unsigned CommandID) const { - if (const CommandInfo *Info = getBuiltinCommandInfo(CommandID)) +CommandInfo const *CommandTraits::getCommandInfo(unsigned CommandID) const { + if (CommandInfo const *Info = getBuiltinCommandInfo(CommandID)) return Info; return getRegisteredCommandInfo(CommandID); } -const CommandInfo * +CommandInfo const * CommandTraits::getTypoCorrectCommandInfo(StringRef Typo) const { // Single-character command impostures, such as \t or \n, should not go // through the fixit logic. @@ -51,12 +51,12 @@ return nullptr; // The maximum edit distance we're prepared to accept. - const unsigned MaxEditDistance = 1; + unsigned const MaxEditDistance = 1; unsigned BestEditDistance = MaxEditDistance; - SmallVector BestCommand; + SmallVector BestCommand; - auto ConsiderCorrection = [&](const CommandInfo *Command) { + auto ConsiderCorrection = [&](CommandInfo const *Command) { StringRef Name = Command->Name; unsigned MinPossibleEditDistance = abs((int)Name.size() - (int)Typo.size()); @@ -71,10 +71,10 @@ } }; - for (const auto &Command : Commands) + for (auto const &Command : Commands) ConsiderCorrection(&Command); - for (const auto *Command : RegisteredCommands) + for (auto const *Command : RegisteredCommands) if (!Command->IsUnknownCommand) ConsiderCorrection(Command); @@ -91,8 +91,8 @@ Info->Name = Name; // We only have a limited number of bits to encode command IDs in the // CommandInfo structure, so the ID numbers can potentially wrap around. - assert((NextID < (1 << CommandInfo::NumCommandIDBits)) - && "Too many commands. We have limited bits for the command ID."); + assert((NextID < (1 << CommandInfo::NumCommandIDBits)) && + "Too many commands. We have limited bits for the command ID."); Info->ID = NextID++; RegisteredCommands.push_back(Info); @@ -100,28 +100,27 @@ return Info; } -const CommandInfo *CommandTraits::registerUnknownCommand( - StringRef CommandName) { +CommandInfo const * +CommandTraits::registerUnknownCommand(StringRef CommandName) { CommandInfo *Info = createCommandInfoWithName(CommandName); Info->IsUnknownCommand = true; return Info; } -const CommandInfo *CommandTraits::registerBlockCommand(StringRef CommandName) { +CommandInfo const *CommandTraits::registerBlockCommand(StringRef CommandName) { CommandInfo *Info = createCommandInfoWithName(CommandName); Info->IsBlockCommand = true; return Info; } -const CommandInfo *CommandTraits::getBuiltinCommandInfo( - unsigned CommandID) { +CommandInfo const *CommandTraits::getBuiltinCommandInfo(unsigned CommandID) { if (CommandID < llvm::array_lengthof(Commands)) return &Commands[CommandID]; return nullptr; } -const CommandInfo *CommandTraits::getRegisteredCommandInfo( - StringRef Name) const { +CommandInfo const * +CommandTraits::getRegisteredCommandInfo(StringRef Name) const { for (unsigned i = 0, e = RegisteredCommands.size(); i != e; ++i) { if (RegisteredCommands[i]->Name == Name) return RegisteredCommands[i]; @@ -129,11 +128,10 @@ return nullptr; } -const CommandInfo *CommandTraits::getRegisteredCommandInfo( - unsigned CommandID) const { +CommandInfo const * +CommandTraits::getRegisteredCommandInfo(unsigned CommandID) const { return RegisteredCommands[CommandID - llvm::array_lengthof(Commands)]; } } // end namespace comments } // end namespace clang - Index: clang/lib/AST/CommentLexer.cpp =================================================================== --- clang/lib/AST/CommentLexer.cpp +++ clang/lib/AST/CommentLexer.cpp @@ -18,27 +18,26 @@ namespace clang { namespace comments { -void Token::dump(const Lexer &L, const SourceManager &SM) const { +void Token::dump(Lexer const &L, SourceManager const &SM) const { llvm::errs() << "comments::Token Kind=" << Kind << " "; Loc.print(llvm::errs(), SM); llvm::errs() << " " << Length << " \"" << L.getSpelling(*this, SM) << "\"\n"; } -static inline bool isHTMLNamedCharacterReferenceCharacter(char C) { +inline static bool isHTMLNamedCharacterReferenceCharacter(char C) { return isLetter(C); } -static inline bool isHTMLDecimalCharacterReferenceCharacter(char C) { +inline static bool isHTMLDecimalCharacterReferenceCharacter(char C) { return isDigit(C); } -static inline bool isHTMLHexCharacterReferenceCharacter(char C) { +inline static bool isHTMLHexCharacterReferenceCharacter(char C) { return isHexDigit(C); } -static inline StringRef convertCodePointToUTF8( - llvm::BumpPtrAllocator &Allocator, - unsigned CodePoint) { +inline static StringRef +convertCodePointToUTF8(llvm::BumpPtrAllocator &Allocator, unsigned CodePoint) { char *Resolved = Allocator.Allocate(UNI_MAX_UTF8_BYTES_PER_CODE_POINT); char *ResolvedPtr = Resolved; if (llvm::ConvertCodePointToUTF8(CodePoint, ResolvedPtr)) @@ -49,8 +48,8 @@ namespace { -#include "clang/AST/CommentHTMLTags.inc" #include "clang/AST/CommentHTMLNamedCharacterReferences.inc" +#include "clang/AST/CommentHTMLTags.inc" } // end anonymous namespace @@ -80,7 +79,7 @@ unsigned CodePoint = 0; for (unsigned i = 0, e = Name.size(); i != e; ++i) { CodePoint *= 16; - const char C = Name[i]; + char const C = Name[i]; assert(isHTMLHexCharacterReferenceCharacter(C)); CodePoint += llvm::hexDigitValue(C); } @@ -99,7 +98,7 @@ case '\t': case '\f': case '\v': { - const char *NewBufferPtr = BufferPtr; + char const *NewBufferPtr = BufferPtr; NewBufferPtr++; if (NewBufferPtr == CommentEnd) return; @@ -123,15 +122,15 @@ namespace { /// Returns pointer to the first newline character in the string. -const char *findNewline(const char *BufferPtr, const char *BufferEnd) { - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { +char const *findNewline(char const *BufferPtr, char const *BufferEnd) { + for (; BufferPtr != BufferEnd; ++BufferPtr) { if (isVerticalWhitespace(*BufferPtr)) return BufferPtr; } return BufferEnd; } -const char *skipNewline(const char *BufferPtr, const char *BufferEnd) { +char const *skipNewline(char const *BufferPtr, char const *BufferEnd) { if (BufferPtr == BufferEnd) return BufferPtr; @@ -146,43 +145,39 @@ return BufferPtr; } -const char *skipNamedCharacterReference(const char *BufferPtr, - const char *BufferEnd) { - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { +char const *skipNamedCharacterReference(char const *BufferPtr, + char const *BufferEnd) { + for (; BufferPtr != BufferEnd; ++BufferPtr) { if (!isHTMLNamedCharacterReferenceCharacter(*BufferPtr)) return BufferPtr; } return BufferEnd; } -const char *skipDecimalCharacterReference(const char *BufferPtr, - const char *BufferEnd) { - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { +char const *skipDecimalCharacterReference(char const *BufferPtr, + char const *BufferEnd) { + for (; BufferPtr != BufferEnd; ++BufferPtr) { if (!isHTMLDecimalCharacterReferenceCharacter(*BufferPtr)) return BufferPtr; } return BufferEnd; } -const char *skipHexCharacterReference(const char *BufferPtr, - const char *BufferEnd) { - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { +char const *skipHexCharacterReference(char const *BufferPtr, + char const *BufferEnd) { + for (; BufferPtr != BufferEnd; ++BufferPtr) { if (!isHTMLHexCharacterReferenceCharacter(*BufferPtr)) return BufferPtr; } return BufferEnd; } -bool isHTMLIdentifierStartingCharacter(char C) { - return isLetter(C); -} +bool isHTMLIdentifierStartingCharacter(char C) { return isLetter(C); } -bool isHTMLIdentifierCharacter(char C) { - return isAlphanumeric(C); -} +bool isHTMLIdentifierCharacter(char C) { return isAlphanumeric(C); } -const char *skipHTMLIdentifier(const char *BufferPtr, const char *BufferEnd) { - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { +char const *skipHTMLIdentifier(char const *BufferPtr, char const *BufferEnd) { + for (; BufferPtr != BufferEnd; ++BufferPtr) { if (!isHTMLIdentifierCharacter(*BufferPtr)) return BufferPtr; } @@ -193,42 +188,37 @@ /// string allowed. /// /// Returns pointer to closing quote. -const char *skipHTMLQuotedString(const char *BufferPtr, const char *BufferEnd) -{ - const char Quote = *BufferPtr; +char const *skipHTMLQuotedString(char const *BufferPtr, char const *BufferEnd) { + char const Quote = *BufferPtr; assert(Quote == '\"' || Quote == '\''); BufferPtr++; - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { - const char C = *BufferPtr; + for (; BufferPtr != BufferEnd; ++BufferPtr) { + char const C = *BufferPtr; if (C == Quote && BufferPtr[-1] != '\\') return BufferPtr; } return BufferEnd; } -const char *skipWhitespace(const char *BufferPtr, const char *BufferEnd) { - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { +char const *skipWhitespace(char const *BufferPtr, char const *BufferEnd) { + for (; BufferPtr != BufferEnd; ++BufferPtr) { if (!isWhitespace(*BufferPtr)) return BufferPtr; } return BufferEnd; } -bool isWhitespace(const char *BufferPtr, const char *BufferEnd) { +bool isWhitespace(char const *BufferPtr, char const *BufferEnd) { return skipWhitespace(BufferPtr, BufferEnd) == BufferEnd; } -bool isCommandNameStartCharacter(char C) { - return isLetter(C); -} +bool isCommandNameStartCharacter(char C) { return isLetter(C); } -bool isCommandNameCharacter(char C) { - return isAlphanumeric(C); -} +bool isCommandNameCharacter(char C) { return isAlphanumeric(C); } -const char *skipCommandName(const char *BufferPtr, const char *BufferEnd) { - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { +char const *skipCommandName(char const *BufferPtr, char const *BufferEnd) { + for (; BufferPtr != BufferEnd; ++BufferPtr) { if (!isCommandNameCharacter(*BufferPtr)) return BufferPtr; } @@ -237,8 +227,8 @@ /// Return the one past end pointer for BCPL comments. /// Handles newlines escaped with backslash or trigraph for backslahs. -const char *findBCPLCommentEnd(const char *BufferPtr, const char *BufferEnd) { - const char *CurPtr = BufferPtr; +char const *findBCPLCommentEnd(char const *BufferPtr, char const *BufferEnd) { + char const *CurPtr = BufferPtr; while (CurPtr != BufferEnd) { while (!isVerticalWhitespace(*CurPtr)) { CurPtr++; @@ -246,8 +236,8 @@ return BufferEnd; } // We found a newline, check if it is escaped. - const char *EscapePtr = CurPtr - 1; - while(isHorizontalWhitespace(*EscapePtr)) + char const *EscapePtr = CurPtr - 1; + while (isHorizontalWhitespace(*EscapePtr)) EscapePtr--; if (*EscapePtr == '\\' || @@ -263,8 +253,8 @@ /// Return the one past end pointer for C comments. /// Very dumb, does not handle escaped newlines or trigraphs. -const char *findCCommentEnd(const char *BufferPtr, const char *BufferEnd) { - for ( ; BufferPtr != BufferEnd; ++BufferPtr) { +char const *findCCommentEnd(char const *BufferPtr, char const *BufferEnd) { + for (; BufferPtr != BufferEnd; ++BufferPtr) { if (*BufferPtr == '*') { assert(BufferPtr + 1 != BufferEnd); if (*(BufferPtr + 1) == '/') @@ -276,9 +266,9 @@ } // end anonymous namespace -void Lexer::formTokenWithChars(Token &Result, const char *TokEnd, +void Lexer::formTokenWithChars(Token &Result, char const *TokEnd, tok::TokenKind Kind) { - const unsigned TokLen = TokEnd - BufferPtr; + unsigned const TokLen = TokEnd - BufferPtr; Result.setLocation(getSourceLocation(BufferPtr)); Result.setKind(Kind); Result.setLength(TokLen); @@ -300,26 +290,26 @@ const char *TokenPtr = BufferPtr; assert(TokenPtr < CommentEnd); switch (*TokenPtr) { - case '\n': - case '\r': - TokenPtr = skipNewline(TokenPtr, CommentEnd); - formTokenWithChars(T, TokenPtr, tok::newline); - - if (CommentState == LCS_InsideCComment) - skipLineStartingDecorations(); - return; - - default: { - StringRef TokStartSymbols = ParseCommands ? "\n\r\\@&<" : "\n\r"; - size_t End = StringRef(TokenPtr, CommentEnd - TokenPtr) - .find_first_of(TokStartSymbols); - if (End != StringRef::npos) - TokenPtr += End; - else - TokenPtr = CommentEnd; - formTextToken(T, TokenPtr); - return; - } + case '\n': + case '\r': + TokenPtr = skipNewline(TokenPtr, CommentEnd); + formTokenWithChars(T, TokenPtr, tok::newline); + + if (CommentState == LCS_InsideCComment) + skipLineStartingDecorations(); + return; + + default: { + StringRef TokStartSymbols = ParseCommands ? "\n\r\\@&<" : "\n\r"; + size_t End = StringRef(TokenPtr, CommentEnd - TokenPtr) + .find_first_of(TokStartSymbols); + if (End != StringRef::npos) + TokenPtr += End; + else + TokenPtr = CommentEnd; + formTextToken(T, TokenPtr); + return; + } } }; @@ -347,122 +337,129 @@ } assert(State == LS_Normal); - const char *TokenPtr = BufferPtr; + char const *TokenPtr = BufferPtr; assert(TokenPtr < CommentEnd); - switch(*TokenPtr) { + switch (*TokenPtr) { + case '\\': + case '@': { + // Commands that start with a backslash and commands that start with + // 'at' have equivalent semantics. But we keep information about the + // exact syntax in AST for comments. + tok::TokenKind CommandKind = + (*TokenPtr == '@') ? tok::at_command : tok::backslash_command; + TokenPtr++; + if (TokenPtr == CommentEnd) { + formTextToken(T, TokenPtr); + return; + } + char C = *TokenPtr; + switch (C) { + default: + break; + case '\\': - case '@': { - // Commands that start with a backslash and commands that start with - // 'at' have equivalent semantics. But we keep information about the - // exact syntax in AST for comments. - tok::TokenKind CommandKind = - (*TokenPtr == '@') ? tok::at_command : tok::backslash_command; + case '@': + case '&': + case '$': + case '#': + case '<': + case '>': + case '%': + case '\"': + case '.': + case ':': + // This is one of \\ \@ \& \$ etc escape sequences. TokenPtr++; - if (TokenPtr == CommentEnd) { - formTextToken(T, TokenPtr); - return; - } - char C = *TokenPtr; - switch (C) { - default: - break; - - case '\\': case '@': case '&': case '$': - case '#': case '<': case '>': case '%': - case '\"': case '.': case ':': - // This is one of \\ \@ \& \$ etc escape sequences. + if (C == ':' && TokenPtr != CommentEnd && *TokenPtr == ':') { + // This is the \:: escape sequence. TokenPtr++; - if (C == ':' && TokenPtr != CommentEnd && *TokenPtr == ':') { - // This is the \:: escape sequence. - TokenPtr++; - } - StringRef UnescapedText(BufferPtr + 1, TokenPtr - (BufferPtr + 1)); - formTokenWithChars(T, TokenPtr, tok::text); - T.setText(UnescapedText); - return; } + StringRef UnescapedText(BufferPtr + 1, TokenPtr - (BufferPtr + 1)); + formTokenWithChars(T, TokenPtr, tok::text); + T.setText(UnescapedText); + return; + } - // Don't make zero-length commands. - if (!isCommandNameStartCharacter(*TokenPtr)) { - formTextToken(T, TokenPtr); - return; - } + // Don't make zero-length commands. + if (!isCommandNameStartCharacter(*TokenPtr)) { + formTextToken(T, TokenPtr); + return; + } + + TokenPtr = skipCommandName(TokenPtr, CommentEnd); + unsigned Length = TokenPtr - (BufferPtr + 1); - TokenPtr = skipCommandName(TokenPtr, CommentEnd); - unsigned Length = TokenPtr - (BufferPtr + 1); - - // Hardcoded support for lexing LaTeX formula commands - // \f$ \f[ \f] \f{ \f} as a single command. - if (Length == 1 && TokenPtr[-1] == 'f' && TokenPtr != CommentEnd) { - C = *TokenPtr; - if (C == '$' || C == '[' || C == ']' || C == '{' || C == '}') { - TokenPtr++; - Length++; - } + // Hardcoded support for lexing LaTeX formula commands + // \f$ \f[ \f] \f{ \f} as a single command. + if (Length == 1 && TokenPtr[-1] == 'f' && TokenPtr != CommentEnd) { + C = *TokenPtr; + if (C == '$' || C == '[' || C == ']' || C == '{' || C == '}') { + TokenPtr++; + Length++; } + } - StringRef CommandName(BufferPtr + 1, Length); - - const CommandInfo *Info = Traits.getCommandInfoOrNULL(CommandName); - if (!Info) { - if ((Info = Traits.getTypoCorrectCommandInfo(CommandName))) { - StringRef CorrectedName = Info->Name; - SourceLocation Loc = getSourceLocation(BufferPtr); - SourceLocation EndLoc = getSourceLocation(TokenPtr); - SourceRange FullRange = SourceRange(Loc, EndLoc); - SourceRange CommandRange(Loc.getLocWithOffset(1), EndLoc); - Diag(Loc, diag::warn_correct_comment_command_name) + StringRef CommandName(BufferPtr + 1, Length); + + CommandInfo const *Info = Traits.getCommandInfoOrNULL(CommandName); + if (!Info) { + if ((Info = Traits.getTypoCorrectCommandInfo(CommandName))) { + StringRef CorrectedName = Info->Name; + SourceLocation Loc = getSourceLocation(BufferPtr); + SourceLocation EndLoc = getSourceLocation(TokenPtr); + SourceRange FullRange = SourceRange(Loc, EndLoc); + SourceRange CommandRange(Loc.getLocWithOffset(1), EndLoc); + Diag(Loc, diag::warn_correct_comment_command_name) << FullRange << CommandName << CorrectedName << FixItHint::CreateReplacement(CommandRange, CorrectedName); - } else { - formTokenWithChars(T, TokenPtr, tok::unknown_command); - T.setUnknownCommandName(CommandName); - Diag(T.getLocation(), diag::warn_unknown_comment_command_name) - << SourceRange(T.getLocation(), T.getEndLocation()); - return; - } - } - if (Info->IsVerbatimBlockCommand) { - setupAndLexVerbatimBlock(T, TokenPtr, *BufferPtr, Info); - return; - } - if (Info->IsVerbatimLineCommand) { - setupAndLexVerbatimLine(T, TokenPtr, Info); + } else { + formTokenWithChars(T, TokenPtr, tok::unknown_command); + T.setUnknownCommandName(CommandName); + Diag(T.getLocation(), diag::warn_unknown_comment_command_name) + << SourceRange(T.getLocation(), T.getEndLocation()); return; } - formTokenWithChars(T, TokenPtr, CommandKind); - T.setCommandID(Info->getID()); + } + if (Info->IsVerbatimBlockCommand) { + setupAndLexVerbatimBlock(T, TokenPtr, *BufferPtr, Info); return; } - - case '&': - lexHTMLCharacterReference(T); + if (Info->IsVerbatimLineCommand) { + setupAndLexVerbatimLine(T, TokenPtr, Info); return; + } + formTokenWithChars(T, TokenPtr, CommandKind); + T.setCommandID(Info->getID()); + return; + } - case '<': { - TokenPtr++; - if (TokenPtr == CommentEnd) { - formTextToken(T, TokenPtr); - return; - } - const char C = *TokenPtr; - if (isHTMLIdentifierStartingCharacter(C)) - setupAndLexHTMLStartTag(T); - else if (C == '/') - setupAndLexHTMLEndTag(T); - else - formTextToken(T, TokenPtr); + case '&': + lexHTMLCharacterReference(T); + return; + + case '<': { + TokenPtr++; + if (TokenPtr == CommentEnd) { + formTextToken(T, TokenPtr); return; } + char const C = *TokenPtr; + if (isHTMLIdentifierStartingCharacter(C)) + setupAndLexHTMLStartTag(T); + else if (C == '/') + setupAndLexHTMLEndTag(T); + else + formTextToken(T, TokenPtr); + return; + } - default: - return HandleNonCommandToken(); + default: + return HandleNonCommandToken(); } } -void Lexer::setupAndLexVerbatimBlock(Token &T, - const char *TextBegin, - char Marker, const CommandInfo *Info) { +void Lexer::setupAndLexVerbatimBlock(Token &T, char const *TextBegin, + char Marker, CommandInfo const *Info) { assert(Info->IsVerbatimBlockCommand); VerbatimBlockEndCommandName.clear(); @@ -475,8 +472,7 @@ // If there is a newline following the verbatim opening command, skip the // newline so that we don't create an tok::verbatim_block_line with empty // text content. - if (BufferPtr != CommentEnd && - isVerticalWhitespace(*BufferPtr)) { + if (BufferPtr != CommentEnd && isVerticalWhitespace(*BufferPtr)) { BufferPtr = skipNewline(BufferPtr, CommentEnd); State = LS_VerbatimBlockBody; return; @@ -493,20 +489,20 @@ // end command or newline. // // Extract current line. - const char *Newline = findNewline(BufferPtr, CommentEnd); + char const *Newline = findNewline(BufferPtr, CommentEnd); StringRef Line(BufferPtr, Newline - BufferPtr); // Look for end command in current line. size_t Pos = Line.find(VerbatimBlockEndCommandName); - const char *TextEnd; - const char *NextLine; + char const *TextEnd; + char const *NextLine; if (Pos == StringRef::npos) { // Current line is completely verbatim. TextEnd = Newline; NextLine = skipNewline(Newline, CommentEnd); } else if (Pos == 0) { // Current line contains just an end command. - const char *End = BufferPtr + VerbatimBlockEndCommandName.size(); + char const *End = BufferPtr + VerbatimBlockEndCommandName.size(); StringRef Name(BufferPtr + 1, End - (BufferPtr + 1)); formTokenWithChars(T, End, tok::verbatim_block_end); T.setVerbatimBlockID(Traits.getCommandInfo(Name)->getID()); @@ -545,8 +541,8 @@ lexVerbatimBlockFirstLine(T); } -void Lexer::setupAndLexVerbatimLine(Token &T, const char *TextBegin, - const CommandInfo *Info) { +void Lexer::setupAndLexVerbatimLine(Token &T, char const *TextBegin, + CommandInfo const *Info) { assert(Info->IsVerbatimLineCommand); formTokenWithChars(T, TextBegin, tok::verbatim_line_name); T.setVerbatimLineID(Info->getID()); @@ -558,7 +554,7 @@ assert(State == LS_VerbatimLineText); // Extract current line. - const char *Newline = findNewline(BufferPtr, CommentEnd); + char const *Newline = findNewline(BufferPtr, CommentEnd); StringRef Text(BufferPtr, Newline - BufferPtr); formTokenWithChars(T, Newline, tok::verbatim_line_text); T.setVerbatimLineText(Text); @@ -567,14 +563,14 @@ } void Lexer::lexHTMLCharacterReference(Token &T) { - const char *TokenPtr = BufferPtr; + char const *TokenPtr = BufferPtr; assert(*TokenPtr == '&'); TokenPtr++; if (TokenPtr == CommentEnd) { formTextToken(T, TokenPtr); return; } - const char *NamePtr; + char const *NamePtr; bool isNamed = false; bool isDecimal = false; char C = *TokenPtr; @@ -605,8 +601,7 @@ formTextToken(T, TokenPtr); return; } - if (NamePtr == TokenPtr || TokenPtr == CommentEnd || - *TokenPtr != ';') { + if (NamePtr == TokenPtr || TokenPtr == CommentEnd || *TokenPtr != ';') { formTextToken(T, TokenPtr); return; } @@ -631,7 +626,7 @@ void Lexer::setupAndLexHTMLStartTag(Token &T) { assert(BufferPtr[0] == '<' && isHTMLIdentifierStartingCharacter(BufferPtr[1])); - const char *TagNameEnd = skipHTMLIdentifier(BufferPtr + 2, CommentEnd); + char const *TagNameEnd = skipHTMLIdentifier(BufferPtr + 2, CommentEnd); StringRef Name(BufferPtr + 1, TagNameEnd - (BufferPtr + 1)); if (!isHTMLTagName(Name)) { formTextToken(T, TagNameEnd); @@ -643,7 +638,7 @@ BufferPtr = skipWhitespace(BufferPtr, CommentEnd); - const char C = *BufferPtr; + char const C = *BufferPtr; if (BufferPtr != CommentEnd && (C == '>' || C == '/' || isHTMLIdentifierStartingCharacter(C))) State = LS_HTMLStartTag; @@ -652,7 +647,7 @@ void Lexer::lexHTMLStartTag(Token &T) { assert(State == LS_HTMLStartTag); - const char *TokenPtr = BufferPtr; + char const *TokenPtr = BufferPtr; char C = *TokenPtr; if (isHTMLIdentifierCharacter(C)) { TokenPtr = skipHTMLIdentifier(TokenPtr, CommentEnd); @@ -667,14 +662,14 @@ break; case '\"': case '\'': { - const char *OpenQuote = TokenPtr; + char const *OpenQuote = TokenPtr; TokenPtr = skipHTMLQuotedString(TokenPtr, CommentEnd); - const char *ClosingQuote = TokenPtr; + char const *ClosingQuote = TokenPtr; if (TokenPtr != CommentEnd) // Skip closing quote. TokenPtr++; formTokenWithChars(T, TokenPtr, tok::html_quoted_string); - T.setHTMLQuotedString(StringRef(OpenQuote + 1, - ClosingQuote - (OpenQuote + 1))); + T.setHTMLQuotedString( + StringRef(OpenQuote + 1, ClosingQuote - (OpenQuote + 1))); break; } case '>': @@ -704,8 +699,8 @@ } C = *BufferPtr; - if (!isHTMLIdentifierStartingCharacter(C) && - C != '=' && C != '\"' && C != '\'' && C != '>') { + if (!isHTMLIdentifierStartingCharacter(C) && C != '=' && C != '\"' && + C != '\'' && C != '>') { State = LS_Normal; return; } @@ -714,15 +709,15 @@ void Lexer::setupAndLexHTMLEndTag(Token &T) { assert(BufferPtr[0] == '<' && BufferPtr[1] == '/'); - const char *TagNameBegin = skipWhitespace(BufferPtr + 2, CommentEnd); - const char *TagNameEnd = skipHTMLIdentifier(TagNameBegin, CommentEnd); + char const *TagNameBegin = skipWhitespace(BufferPtr + 2, CommentEnd); + char const *TagNameEnd = skipHTMLIdentifier(TagNameBegin, CommentEnd); StringRef Name(TagNameBegin, TagNameEnd - TagNameBegin); if (!isHTMLTagName(Name)) { formTextToken(T, TagNameEnd); return; } - const char *End = skipWhitespace(TagNameEnd, CommentEnd); + char const *End = skipWhitespace(TagNameEnd, CommentEnd); formTokenWithChars(T, End, tok::html_end_tag); T.setHTMLTagEndName(Name); @@ -739,8 +734,8 @@ } Lexer::Lexer(llvm::BumpPtrAllocator &Allocator, DiagnosticsEngine &Diags, - const CommandTraits &Traits, SourceLocation FileLoc, - const char *BufferStart, const char *BufferEnd, bool ParseCommands) + CommandTraits const &Traits, SourceLocation FileLoc, + char const *BufferStart, char const *BufferEnd, bool ParseCommands) : Allocator(Allocator), Diags(Diags), Traits(Traits), BufferStart(BufferStart), BufferEnd(BufferEnd), BufferPtr(BufferStart), FileLoc(FileLoc), ParseCommands(ParseCommands), @@ -757,8 +752,8 @@ assert(*BufferPtr == '/'); BufferPtr++; // Skip first slash. - switch(*BufferPtr) { - case '/': { // BCPL comment. + switch (*BufferPtr) { + case '/': { // BCPL comment. BufferPtr++; // Skip second slash. if (BufferPtr != BufferEnd) { @@ -766,7 +761,7 @@ // It might be missing because of a typo //< or /*<, or because we // merged this non-Doxygen comment into a bunch of Doxygen comments // around it: /** ... */ /* ... */ /** ... */ - const char C = *BufferPtr; + char const C = *BufferPtr; if (C == '/' || C == '!') BufferPtr++; } @@ -783,11 +778,11 @@ CommentEnd = findBCPLCommentEnd(BufferPtr, BufferEnd); goto again; } - case '*': { // C comment. + case '*': { // C comment. BufferPtr++; // Skip star. // Skip Doxygen magic marker. - const char C = *BufferPtr; + char const C = *BufferPtr; if ((C == '*' && *(BufferPtr + 1) != '/') || C == '!') BufferPtr++; @@ -807,8 +802,8 @@ case LCS_BetweenComments: { // Consecutive comments are extracted only if there is only whitespace // between them. So we can search for the start of the next comment. - const char *EndWhitespace = BufferPtr; - while(EndWhitespace != BufferEnd && *EndWhitespace != '/') + char const *EndWhitespace = BufferPtr; + while (EndWhitespace != BufferEnd && *EndWhitespace != '/') EndWhitespace++; // Turn any whitespace between comments (and there is only whitespace @@ -848,8 +843,8 @@ } } -StringRef Lexer::getSpelling(const Token &Tok, - const SourceManager &SourceMgr) const { +StringRef Lexer::getSpelling(Token const &Tok, + SourceManager const &SourceMgr) const { SourceLocation Loc = Tok.getLocation(); std::pair LocInfo = SourceMgr.getDecomposedLoc(Loc); @@ -858,7 +853,7 @@ if (InvalidTemp) return StringRef(); - const char *Begin = File.data() + LocInfo.second; + char const *Begin = File.data() + LocInfo.second; return StringRef(Begin, Tok.getLength()); } Index: clang/lib/AST/CommentParser.cpp =================================================================== --- clang/lib/AST/CommentParser.cpp +++ clang/lib/AST/CommentParser.cpp @@ -16,7 +16,7 @@ namespace clang { -static inline bool isWhitespace(llvm::StringRef S) { +inline static bool isWhitespace(llvm::StringRef S) { for (StringRef::const_iterator I = S.begin(), E = S.end(); I != E; ++I) { if (!isWhitespace(*I)) return false; @@ -39,9 +39,9 @@ /// A position in \c Toks. struct Position { - const char *BufferStart; - const char *BufferEnd; - const char *BufferPtr; + char const *BufferStart; + char const *BufferEnd; + char const *BufferPtr; SourceLocation BufferStartLoc; unsigned CurToken; }; @@ -49,14 +49,12 @@ /// Current position in Toks. Position Pos; - bool isEnd() const { - return Pos.CurToken >= Toks.size(); - } + bool isEnd() const { return Pos.CurToken >= Toks.size(); } /// Sets up the buffer pointers to point to current token. void setupBuffer() { assert(!isEnd()); - const Token &Tok = Toks[Pos.CurToken]; + Token const &Tok = Toks[Pos.CurToken]; Pos.BufferStart = Tok.getText().begin(); Pos.BufferEnd = Tok.getText().end(); @@ -65,7 +63,7 @@ } SourceLocation getSourceLocation() const { - const unsigned CharNo = Pos.BufferPtr - Pos.BufferStart; + unsigned const CharNo = Pos.BufferPtr - Pos.BufferStart; return Pos.BufferStartLoc.getLocWithOffset(CharNo); } @@ -127,10 +125,8 @@ } } - void formTokenWithChars(Token &Result, - SourceLocation Loc, - const char *TokBegin, - unsigned TokLength, + void formTokenWithChars(Token &Result, SourceLocation Loc, + char const *TokBegin, unsigned TokLength, StringRef Text) { Result.setLocation(Loc); Result.setKind(tok::text); @@ -143,8 +139,8 @@ } public: - TextTokenRetokenizer(llvm::BumpPtrAllocator &Allocator, Parser &P): - Allocator(Allocator), P(P), NoMoreInterestingTokens(false) { + TextTokenRetokenizer(llvm::BumpPtrAllocator &Allocator, Parser &P) + : Allocator(Allocator), P(P), NoMoreInterestingTokens(false) { Pos.CurToken = 0; addToken(); } @@ -158,17 +154,17 @@ consumeWhitespace(); SmallString<32> WordText; - const char *WordBegin = Pos.BufferPtr; + char const *WordBegin = Pos.BufferPtr; SourceLocation Loc = getSourceLocation(); while (!isEnd()) { - const char C = peek(); + char const C = peek(); if (!isWhitespace(C)) { WordText.push_back(C); consumeChar(); } else break; } - const unsigned Length = WordText.size(); + unsigned const Length = WordText.size(); if (Length == 0) { Pos = SavedPos; return false; @@ -191,11 +187,11 @@ consumeWhitespace(); SmallString<32> WordText; - const char *WordBegin = Pos.BufferPtr; + char const *WordBegin = Pos.BufferPtr; SourceLocation Loc = getSourceLocation(); bool Error = false; if (!isEnd()) { - const char C = peek(); + char const C = peek(); if (C == OpenDelim) { WordText.push_back(C); consumeChar(); @@ -218,14 +214,13 @@ return false; } - const unsigned Length = WordText.size(); + unsigned const Length = WordText.size(); char *TextPtr = Allocator.Allocate(Length + 1); memcpy(TextPtr, WordText.c_str(), Length + 1); StringRef Text = StringRef(TextPtr, Length); - formTokenWithChars(Tok, Loc, WordBegin, - Pos.BufferPtr - WordBegin, Text); + formTokenWithChars(Tok, Loc, WordBegin, Pos.BufferPtr - WordBegin, Text); return true; } @@ -237,10 +232,10 @@ bool HavePartialTok = false; Token PartialTok; if (Pos.BufferPtr != Pos.BufferStart) { - formTokenWithChars(PartialTok, getSourceLocation(), - Pos.BufferPtr, Pos.BufferEnd - Pos.BufferPtr, - StringRef(Pos.BufferPtr, - Pos.BufferEnd - Pos.BufferPtr)); + formTokenWithChars( + PartialTok, getSourceLocation(), Pos.BufferPtr, + Pos.BufferEnd - Pos.BufferPtr, + StringRef(Pos.BufferPtr, Pos.BufferEnd - Pos.BufferPtr)); HavePartialTok = true; Pos.CurToken++; } @@ -254,10 +249,10 @@ }; Parser::Parser(Lexer &L, Sema &S, llvm::BumpPtrAllocator &Allocator, - const SourceManager &SourceMgr, DiagnosticsEngine &Diags, - const CommandTraits &Traits): - L(L), S(S), Allocator(Allocator), SourceMgr(SourceMgr), Diags(Diags), - Traits(Traits) { + SourceManager const &SourceMgr, DiagnosticsEngine &Diags, + CommandTraits const &Traits) + : L(L), S(S), Allocator(Allocator), SourceMgr(SourceMgr), Diags(Diags), + Traits(Traits) { consumeToken(); } @@ -267,15 +262,11 @@ // Check if argument looks like direction specification: [dir] // e.g., [in], [out], [in,out] if (Retokenizer.lexDelimitedSeq(Arg, '[', ']')) - S.actOnParamCommandDirectionArg(PC, - Arg.getLocation(), - Arg.getEndLocation(), + S.actOnParamCommandDirectionArg(PC, Arg.getLocation(), Arg.getEndLocation(), Arg.getText()); if (Retokenizer.lexWord(Arg)) - S.actOnParamCommandParamNameArg(PC, - Arg.getLocation(), - Arg.getEndLocation(), + S.actOnParamCommandParamNameArg(PC, Arg.getLocation(), Arg.getEndLocation(), Arg.getText()); } @@ -283,10 +274,8 @@ TextTokenRetokenizer &Retokenizer) { Token Arg; if (Retokenizer.lexWord(Arg)) - S.actOnTParamCommandParamNameArg(TPC, - Arg.getLocation(), - Arg.getEndLocation(), - Arg.getText()); + S.actOnTParamCommandParamNameArg(TPC, Arg.getLocation(), + Arg.getEndLocation(), Arg.getText()); } void Parser::parseBlockCommandArgs(BlockCommandComment *BC, @@ -298,9 +287,8 @@ unsigned ParsedArgs = 0; Token Arg; while (ParsedArgs < NumArgs && Retokenizer.lexWord(Arg)) { - Args[ParsedArgs] = Argument(SourceRange(Arg.getLocation(), - Arg.getEndLocation()), - Arg.getText()); + Args[ParsedArgs] = Argument( + SourceRange(Arg.getLocation(), Arg.getEndLocation()), Arg.getText()); ParsedArgs++; } @@ -313,24 +301,18 @@ ParamCommandComment *PC = nullptr; TParamCommandComment *TPC = nullptr; BlockCommandComment *BC = nullptr; - const CommandInfo *Info = Traits.getCommandInfo(Tok.getCommandID()); + CommandInfo const *Info = Traits.getCommandInfo(Tok.getCommandID()); CommandMarkerKind CommandMarker = Tok.is(tok::backslash_command) ? CMK_Backslash : CMK_At; if (Info->IsParamCommand) { - PC = S.actOnParamCommandStart(Tok.getLocation(), - Tok.getEndLocation(), - Tok.getCommandID(), - CommandMarker); + PC = S.actOnParamCommandStart(Tok.getLocation(), Tok.getEndLocation(), + Tok.getCommandID(), CommandMarker); } else if (Info->IsTParamCommand) { - TPC = S.actOnTParamCommandStart(Tok.getLocation(), - Tok.getEndLocation(), - Tok.getCommandID(), - CommandMarker); + TPC = S.actOnTParamCommandStart(Tok.getLocation(), Tok.getEndLocation(), + Tok.getCommandID(), CommandMarker); } else { - BC = S.actOnBlockCommandStart(Tok.getLocation(), - Tok.getEndLocation(), - Tok.getCommandID(), - CommandMarker); + BC = S.actOnBlockCommandStart(Tok.getLocation(), Tok.getEndLocation(), + Tok.getCommandID(), CommandMarker); } consumeToken(); @@ -414,10 +396,8 @@ if (ArgTokValid) { IC = S.actOnInlineCommand(CommandTok.getLocation(), CommandTok.getEndLocation(), - CommandTok.getCommandID(), - ArgTok.getLocation(), - ArgTok.getEndLocation(), - ArgTok.getText()); + CommandTok.getCommandID(), ArgTok.getLocation(), + ArgTok.getEndLocation(), ArgTok.getText()); } else { IC = S.actOnInlineCommand(CommandTok.getLocation(), CommandTok.getEndLocation(), @@ -438,8 +418,7 @@ HTMLStartTagComment *Parser::parseHTMLStartTag() { assert(Tok.is(tok::html_start_tag)); HTMLStartTagComment *HST = - S.actOnHTMLStartTagStart(Tok.getLocation(), - Tok.getHTMLTagStartName()); + S.actOnHTMLStartTagStart(Tok.getLocation(), Tok.getHTMLTagStartName()); consumeToken(); SmallVector Attrs; @@ -458,36 +437,30 @@ if (Tok.isNot(tok::html_quoted_string)) { Diag(Tok.getLocation(), diag::warn_doc_html_start_tag_expected_quoted_string) - << SourceRange(Equals.getLocation()); + << SourceRange(Equals.getLocation()); Attrs.push_back(HTMLStartTagComment::Attribute(Ident.getLocation(), Ident.getHTMLIdent())); - while (Tok.is(tok::html_equals) || - Tok.is(tok::html_quoted_string)) + while (Tok.is(tok::html_equals) || Tok.is(tok::html_quoted_string)) consumeToken(); continue; } Attrs.push_back(HTMLStartTagComment::Attribute( - Ident.getLocation(), - Ident.getHTMLIdent(), - Equals.getLocation(), - SourceRange(Tok.getLocation(), - Tok.getEndLocation()), - Tok.getHTMLQuotedString())); + Ident.getLocation(), Ident.getHTMLIdent(), Equals.getLocation(), + SourceRange(Tok.getLocation(), Tok.getEndLocation()), + Tok.getHTMLQuotedString())); consumeToken(); continue; } case tok::html_greater: - S.actOnHTMLStartTagFinish(HST, - S.copyArray(llvm::makeArrayRef(Attrs)), + S.actOnHTMLStartTagFinish(HST, S.copyArray(llvm::makeArrayRef(Attrs)), Tok.getLocation(), /* IsSelfClosing = */ false); consumeToken(); return HST; case tok::html_slash_greater: - S.actOnHTMLStartTagFinish(HST, - S.copyArray(llvm::makeArrayRef(Attrs)), + S.actOnHTMLStartTagFinish(HST, S.copyArray(llvm::makeArrayRef(Attrs)), Tok.getLocation(), /* IsSelfClosing = */ true); consumeToken(); @@ -497,43 +470,37 @@ case tok::html_quoted_string: Diag(Tok.getLocation(), diag::warn_doc_html_start_tag_expected_ident_or_greater); - while (Tok.is(tok::html_equals) || - Tok.is(tok::html_quoted_string)) + while (Tok.is(tok::html_equals) || Tok.is(tok::html_quoted_string)) consumeToken(); - if (Tok.is(tok::html_ident) || - Tok.is(tok::html_greater) || + if (Tok.is(tok::html_ident) || Tok.is(tok::html_greater) || Tok.is(tok::html_slash_greater)) continue; - S.actOnHTMLStartTagFinish(HST, - S.copyArray(llvm::makeArrayRef(Attrs)), + S.actOnHTMLStartTagFinish(HST, S.copyArray(llvm::makeArrayRef(Attrs)), SourceLocation(), /* IsSelfClosing = */ false); return HST; default: // Not a token from an HTML start tag. Thus HTML tag prematurely ended. - S.actOnHTMLStartTagFinish(HST, - S.copyArray(llvm::makeArrayRef(Attrs)), + S.actOnHTMLStartTagFinish(HST, S.copyArray(llvm::makeArrayRef(Attrs)), SourceLocation(), /* IsSelfClosing = */ false); bool StartLineInvalid; - const unsigned StartLine = SourceMgr.getPresumedLineNumber( - HST->getLocation(), - &StartLineInvalid); + unsigned const StartLine = SourceMgr.getPresumedLineNumber( + HST->getLocation(), &StartLineInvalid); bool EndLineInvalid; - const unsigned EndLine = SourceMgr.getPresumedLineNumber( - Tok.getLocation(), - &EndLineInvalid); + unsigned const EndLine = + SourceMgr.getPresumedLineNumber(Tok.getLocation(), &EndLineInvalid); if (StartLineInvalid || EndLineInvalid || StartLine == EndLine) Diag(Tok.getLocation(), diag::warn_doc_html_start_tag_expected_ident_or_greater) - << HST->getSourceRange(); + << HST->getSourceRange(); else { Diag(Tok.getLocation(), diag::warn_doc_html_start_tag_expected_ident_or_greater); Diag(HST->getLocation(), diag::note_doc_html_tag_started_here) - << HST->getSourceRange(); + << HST->getSourceRange(); } return HST; } @@ -550,8 +517,7 @@ consumeToken(); } - return S.actOnHTMLEndTag(TokEndTag.getLocation(), - Loc, + return S.actOnHTMLEndTag(TokEndTag.getLocation(), Loc, TokEndTag.getHTMLTagEndName()); } @@ -574,25 +540,22 @@ case tok::backslash_command: case tok::at_command: { - const CommandInfo *Info = Traits.getCommandInfo(Tok.getCommandID()); + CommandInfo const *Info = Traits.getCommandInfo(Tok.getCommandID()); if (Info->IsBlockCommand) { if (Content.size() == 0) return parseBlockCommand(); break; // Block command ahead, finish this parapgaph. } if (Info->IsVerbatimBlockEndCommand) { - Diag(Tok.getLocation(), - diag::warn_verbatim_block_end_without_start) - << Tok.is(tok::at_command) - << Info->Name - << SourceRange(Tok.getLocation(), Tok.getEndLocation()); + Diag(Tok.getLocation(), diag::warn_verbatim_block_end_without_start) + << Tok.is(tok::at_command) << Info->Name + << SourceRange(Tok.getLocation(), Tok.getEndLocation()); consumeToken(); continue; } if (Info->IsUnknownCommand) { - Content.push_back(S.actOnUnknownCommand(Tok.getLocation(), - Tok.getEndLocation(), - Info->getID())); + Content.push_back(S.actOnUnknownCommand( + Tok.getLocation(), Tok.getEndLocation(), Info->getID())); consumeToken(); continue; } @@ -634,9 +597,8 @@ continue; case tok::text: - Content.push_back(S.actOnText(Tok.getLocation(), - Tok.getEndLocation(), - Tok.getText())); + Content.push_back( + S.actOnText(Tok.getLocation(), Tok.getEndLocation(), Tok.getText())); consumeToken(); continue; @@ -660,8 +622,7 @@ assert(Tok.is(tok::verbatim_block_begin)); VerbatimBlockComment *VB = - S.actOnVerbatimBlockStart(Tok.getLocation(), - Tok.getVerbatimBlockID()); + S.actOnVerbatimBlockStart(Tok.getLocation(), Tok.getVerbatimBlockID()); consumeToken(); // Don't create an empty line if verbatim opening command is followed @@ -670,8 +631,7 @@ consumeToken(); SmallVector Lines; - while (Tok.is(tok::verbatim_block_line) || - Tok.is(tok::newline)) { + while (Tok.is(tok::verbatim_block_line) || Tok.is(tok::newline)) { VerbatimBlockLineComment *Line; if (Tok.is(tok::verbatim_block_line)) { Line = S.actOnVerbatimBlockLine(Tok.getLocation(), @@ -689,9 +649,8 @@ } if (Tok.is(tok::verbatim_block_end)) { - const CommandInfo *Info = Traits.getCommandInfo(Tok.getVerbatimBlockID()); - S.actOnVerbatimBlockFinish(VB, Tok.getLocation(), - Info->Name, + CommandInfo const *Info = Traits.getCommandInfo(Tok.getVerbatimBlockID()); + S.actOnVerbatimBlockFinish(VB, Tok.getLocation(), Info->Name, S.copyArray(llvm::makeArrayRef(Lines))); consumeToken(); } else { @@ -721,10 +680,8 @@ Text = ""; } - VerbatimLineComment *VL = S.actOnVerbatimLine(NameTok.getLocation(), - NameTok.getVerbatimLineID(), - TextBegin, - Text); + VerbatimLineComment *VL = S.actOnVerbatimLine( + NameTok.getLocation(), NameTok.getVerbatimLineID(), TextBegin, Text); consumeToken(); return VL; } Index: clang/lib/AST/CommentSema.cpp =================================================================== --- clang/lib/AST/CommentSema.cpp +++ clang/lib/AST/CommentSema.cpp @@ -25,15 +25,14 @@ #include "clang/AST/CommentHTMLTagsProperties.inc" } // end anonymous namespace -Sema::Sema(llvm::BumpPtrAllocator &Allocator, const SourceManager &SourceMgr, +Sema::Sema(llvm::BumpPtrAllocator &Allocator, SourceManager const &SourceMgr, DiagnosticsEngine &Diags, CommandTraits &Traits, - const Preprocessor *PP) : - Allocator(Allocator), SourceMgr(SourceMgr), Diags(Diags), Traits(Traits), - PP(PP), ThisDeclInfo(nullptr), BriefCommand(nullptr), - HeaderfileCommand(nullptr) { -} + Preprocessor const *PP) + : Allocator(Allocator), SourceMgr(SourceMgr), Diags(Diags), Traits(Traits), + PP(PP), ThisDeclInfo(nullptr), BriefCommand(nullptr), + HeaderfileCommand(nullptr) {} -void Sema::setDecl(const Decl *D) { +void Sema::setDecl(Decl const *D) { if (!D) return; @@ -42,19 +41,17 @@ ThisDeclInfo->IsFilled = false; } -ParagraphComment *Sema::actOnParagraphComment( - ArrayRef Content) { +ParagraphComment * +Sema::actOnParagraphComment(ArrayRef Content) { return new (Allocator) ParagraphComment(Content); } -BlockCommandComment *Sema::actOnBlockCommandStart( - SourceLocation LocBegin, - SourceLocation LocEnd, - unsigned CommandID, - CommandMarkerKind CommandMarker) { - BlockCommandComment *BC = new (Allocator) BlockCommandComment(LocBegin, LocEnd, - CommandID, - CommandMarker); +BlockCommandComment * +Sema::actOnBlockCommandStart(SourceLocation LocBegin, SourceLocation LocEnd, + unsigned CommandID, + CommandMarkerKind CommandMarker) { + BlockCommandComment *BC = new (Allocator) + BlockCommandComment(LocBegin, LocEnd, CommandID, CommandMarker); checkContainerDecl(BC); return BC; } @@ -77,144 +74,137 @@ } } -ParamCommandComment *Sema::actOnParamCommandStart( - SourceLocation LocBegin, - SourceLocation LocEnd, - unsigned CommandID, - CommandMarkerKind CommandMarker) { - ParamCommandComment *Command = - new (Allocator) ParamCommandComment(LocBegin, LocEnd, CommandID, - CommandMarker); +ParamCommandComment * +Sema::actOnParamCommandStart(SourceLocation LocBegin, SourceLocation LocEnd, + unsigned CommandID, + CommandMarkerKind CommandMarker) { + ParamCommandComment *Command = new (Allocator) + ParamCommandComment(LocBegin, LocEnd, CommandID, CommandMarker); if (!isFunctionDecl() && !isFunctionOrBlockPointerVarLikeDecl()) Diag(Command->getLocation(), diag::warn_doc_param_not_attached_to_a_function_decl) - << CommandMarker - << Command->getCommandNameRange(Traits); + << CommandMarker << Command->getCommandNameRange(Traits); return Command; } -void Sema::checkFunctionDeclVerbatimLine(const BlockCommandComment *Comment) { - const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID()); +void Sema::checkFunctionDeclVerbatimLine(BlockCommandComment const *Comment) { + CommandInfo const *Info = Traits.getCommandInfo(Comment->getCommandID()); if (!Info->IsFunctionDeclarationCommand) return; unsigned DiagSelect; switch (Comment->getCommandID()) { - case CommandTraits::KCI_function: - DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl())? 1 : 0; - break; - case CommandTraits::KCI_functiongroup: - DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl())? 2 : 0; - break; - case CommandTraits::KCI_method: - DiagSelect = !isObjCMethodDecl() ? 3 : 0; - break; - case CommandTraits::KCI_methodgroup: - DiagSelect = !isObjCMethodDecl() ? 4 : 0; - break; - case CommandTraits::KCI_callback: - DiagSelect = !isFunctionPointerVarDecl() ? 5 : 0; - break; - default: - DiagSelect = 0; - break; + case CommandTraits::KCI_function: + DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl()) ? 1 : 0; + break; + case CommandTraits::KCI_functiongroup: + DiagSelect = (!isAnyFunctionDecl() && !isFunctionTemplateDecl()) ? 2 : 0; + break; + case CommandTraits::KCI_method: + DiagSelect = !isObjCMethodDecl() ? 3 : 0; + break; + case CommandTraits::KCI_methodgroup: + DiagSelect = !isObjCMethodDecl() ? 4 : 0; + break; + case CommandTraits::KCI_callback: + DiagSelect = !isFunctionPointerVarDecl() ? 5 : 0; + break; + default: + DiagSelect = 0; + break; } if (DiagSelect) Diag(Comment->getLocation(), diag::warn_doc_function_method_decl_mismatch) - << Comment->getCommandMarker() - << (DiagSelect-1) << (DiagSelect-1) - << Comment->getSourceRange(); + << Comment->getCommandMarker() << (DiagSelect - 1) << (DiagSelect - 1) + << Comment->getSourceRange(); } -void Sema::checkContainerDeclVerbatimLine(const BlockCommandComment *Comment) { - const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID()); +void Sema::checkContainerDeclVerbatimLine(BlockCommandComment const *Comment) { + CommandInfo const *Info = Traits.getCommandInfo(Comment->getCommandID()); if (!Info->IsRecordLikeDeclarationCommand) return; unsigned DiagSelect; switch (Comment->getCommandID()) { - case CommandTraits::KCI_class: - DiagSelect = - (!isClassOrStructOrTagTypedefDecl() && !isClassTemplateDecl()) ? 1 - : 0; - // Allow @class command on @interface declarations. - // FIXME. Currently, \class and @class are indistinguishable. So, - // \class is also allowed on an @interface declaration - if (DiagSelect && Comment->getCommandMarker() && isObjCInterfaceDecl()) - DiagSelect = 0; - break; - case CommandTraits::KCI_interface: - DiagSelect = !isObjCInterfaceDecl() ? 2 : 0; - break; - case CommandTraits::KCI_protocol: - DiagSelect = !isObjCProtocolDecl() ? 3 : 0; - break; - case CommandTraits::KCI_struct: - DiagSelect = !isClassOrStructOrTagTypedefDecl() ? 4 : 0; - break; - case CommandTraits::KCI_union: - DiagSelect = !isUnionDecl() ? 5 : 0; - break; - default: + case CommandTraits::KCI_class: + DiagSelect = + (!isClassOrStructOrTagTypedefDecl() && !isClassTemplateDecl()) ? 1 : 0; + // Allow @class command on @interface declarations. + // FIXME. Currently, \class and @class are indistinguishable. So, + // \class is also allowed on an @interface declaration + if (DiagSelect && Comment->getCommandMarker() && isObjCInterfaceDecl()) DiagSelect = 0; - break; + break; + case CommandTraits::KCI_interface: + DiagSelect = !isObjCInterfaceDecl() ? 2 : 0; + break; + case CommandTraits::KCI_protocol: + DiagSelect = !isObjCProtocolDecl() ? 3 : 0; + break; + case CommandTraits::KCI_struct: + DiagSelect = !isClassOrStructOrTagTypedefDecl() ? 4 : 0; + break; + case CommandTraits::KCI_union: + DiagSelect = !isUnionDecl() ? 5 : 0; + break; + default: + DiagSelect = 0; + break; } if (DiagSelect) Diag(Comment->getLocation(), diag::warn_doc_api_container_decl_mismatch) - << Comment->getCommandMarker() - << (DiagSelect-1) << (DiagSelect-1) - << Comment->getSourceRange(); + << Comment->getCommandMarker() << (DiagSelect - 1) << (DiagSelect - 1) + << Comment->getSourceRange(); } -void Sema::checkContainerDecl(const BlockCommandComment *Comment) { - const CommandInfo *Info = Traits.getCommandInfo(Comment->getCommandID()); +void Sema::checkContainerDecl(BlockCommandComment const *Comment) { + CommandInfo const *Info = Traits.getCommandInfo(Comment->getCommandID()); if (!Info->IsRecordLikeDetailCommand || isRecordLikeDecl()) return; unsigned DiagSelect; switch (Comment->getCommandID()) { - case CommandTraits::KCI_classdesign: - DiagSelect = 1; - break; - case CommandTraits::KCI_coclass: - DiagSelect = 2; - break; - case CommandTraits::KCI_dependency: - DiagSelect = 3; - break; - case CommandTraits::KCI_helper: - DiagSelect = 4; - break; - case CommandTraits::KCI_helperclass: - DiagSelect = 5; - break; - case CommandTraits::KCI_helps: - DiagSelect = 6; - break; - case CommandTraits::KCI_instancesize: - DiagSelect = 7; - break; - case CommandTraits::KCI_ownership: - DiagSelect = 8; - break; - case CommandTraits::KCI_performance: - DiagSelect = 9; - break; - case CommandTraits::KCI_security: - DiagSelect = 10; - break; - case CommandTraits::KCI_superclass: - DiagSelect = 11; - break; - default: - DiagSelect = 0; - break; + case CommandTraits::KCI_classdesign: + DiagSelect = 1; + break; + case CommandTraits::KCI_coclass: + DiagSelect = 2; + break; + case CommandTraits::KCI_dependency: + DiagSelect = 3; + break; + case CommandTraits::KCI_helper: + DiagSelect = 4; + break; + case CommandTraits::KCI_helperclass: + DiagSelect = 5; + break; + case CommandTraits::KCI_helps: + DiagSelect = 6; + break; + case CommandTraits::KCI_instancesize: + DiagSelect = 7; + break; + case CommandTraits::KCI_ownership: + DiagSelect = 8; + break; + case CommandTraits::KCI_performance: + DiagSelect = 9; + break; + case CommandTraits::KCI_security: + DiagSelect = 10; + break; + case CommandTraits::KCI_superclass: + DiagSelect = 11; + break; + default: + DiagSelect = 0; + break; } if (DiagSelect) Diag(Comment->getLocation(), diag::warn_doc_container_decl_mismatch) - << Comment->getCommandMarker() - << (DiagSelect-1) - << Comment->getSourceRange(); + << Comment->getCommandMarker() << (DiagSelect - 1) + << Comment->getSourceRange(); } /// Turn a string into the corresponding PassDirection or -1 if it's not @@ -243,7 +233,7 @@ SourceRange ArgRange(ArgLocBegin, ArgLocEnd); if (Direction != -1) { - const char *FixedName = ParamCommandComment::getDirectionAsString( + char const *FixedName = ParamCommandComment::getDirectionAsString( (ParamCommandComment::PassDirection)Direction); Diag(ArgLocBegin, diag::warn_doc_param_spaces_in_direction) << ArgRange << FixItHint::CreateReplacement(ArgRange, FixedName); @@ -268,9 +258,8 @@ Command->setDirection(ParamCommandComment::In, /* Explicit = */ false); } typedef BlockCommandComment::Argument Argument; - Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin, - ArgLocEnd), - Arg); + Argument *A = + new (Allocator) Argument(SourceRange(ArgLocBegin, ArgLocEnd), Arg); Command->setArgs(llvm::makeArrayRef(A, 1)); } @@ -280,20 +269,17 @@ checkBlockCommandEmptyParagraph(Command); } -TParamCommandComment *Sema::actOnTParamCommandStart( - SourceLocation LocBegin, - SourceLocation LocEnd, - unsigned CommandID, - CommandMarkerKind CommandMarker) { - TParamCommandComment *Command = - new (Allocator) TParamCommandComment(LocBegin, LocEnd, CommandID, - CommandMarker); +TParamCommandComment * +Sema::actOnTParamCommandStart(SourceLocation LocBegin, SourceLocation LocEnd, + unsigned CommandID, + CommandMarkerKind CommandMarker) { + TParamCommandComment *Command = new (Allocator) + TParamCommandComment(LocBegin, LocEnd, CommandID, CommandMarker); if (!isTemplateOrSpecialization()) Diag(Command->getLocation(), diag::warn_doc_tparam_not_attached_to_a_template_decl) - << CommandMarker - << Command->getCommandNameRange(Traits); + << CommandMarker << Command->getCommandNameRange(Traits); return Command; } @@ -306,9 +292,8 @@ assert(Command->getNumArgs() == 0); typedef BlockCommandComment::Argument Argument; - Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin, - ArgLocEnd), - Arg); + Argument *A = + new (Allocator) Argument(SourceRange(ArgLocBegin, ArgLocEnd), Arg); Command->setArgs(llvm::makeArrayRef(A, 1)); if (!isTemplateOrSpecialization()) { @@ -316,7 +301,7 @@ return; } - const TemplateParameterList *TemplateParameters = + TemplateParameterList const *TemplateParameters = ThisDeclInfo->TemplateParameters; SmallVector Position; if (resolveTParamReference(Arg, TemplateParameters, &Position)) { @@ -324,26 +309,24 @@ TParamCommandComment *&PrevCommand = TemplateParameterDocs[Arg]; if (PrevCommand) { SourceRange ArgRange(ArgLocBegin, ArgLocEnd); - Diag(ArgLocBegin, diag::warn_doc_tparam_duplicate) - << Arg << ArgRange; + Diag(ArgLocBegin, diag::warn_doc_tparam_duplicate) << Arg << ArgRange; Diag(PrevCommand->getLocation(), diag::note_doc_tparam_previous) - << PrevCommand->getParamNameRange(); + << PrevCommand->getParamNameRange(); } PrevCommand = Command; return; } SourceRange ArgRange(ArgLocBegin, ArgLocEnd); - Diag(ArgLocBegin, diag::warn_doc_tparam_not_found) - << Arg << ArgRange; + Diag(ArgLocBegin, diag::warn_doc_tparam_not_found) << Arg << ArgRange; if (!TemplateParameters || TemplateParameters->size() == 0) return; StringRef CorrectedName; if (TemplateParameters->size() == 1) { - const NamedDecl *Param = TemplateParameters->getParam(0); - const IdentifierInfo *II = Param->getIdentifier(); + NamedDecl const *Param = TemplateParameters->getParam(0); + IdentifierInfo const *II = Param->getIdentifier(); if (II) CorrectedName = II->getName(); } else { @@ -352,8 +335,8 @@ if (!CorrectedName.empty()) { Diag(ArgLocBegin, diag::note_doc_tparam_name_suggestion) - << CorrectedName - << FixItHint::CreateReplacement(ArgRange, CorrectedName); + << CorrectedName + << FixItHint::CreateReplacement(ArgRange, CorrectedName); } } @@ -368,12 +351,9 @@ unsigned CommandID) { ArrayRef Args; StringRef CommandName = Traits.getCommandInfo(CommandID)->Name; - return new (Allocator) InlineCommandComment( - CommandLocBegin, - CommandLocEnd, - CommandID, - getInlineCommandRenderKind(CommandName), - Args); + return new (Allocator) + InlineCommandComment(CommandLocBegin, CommandLocEnd, CommandID, + getInlineCommandRenderKind(CommandName), Args); } InlineCommandComment *Sema::actOnInlineCommand(SourceLocation CommandLocBegin, @@ -383,17 +363,13 @@ SourceLocation ArgLocEnd, StringRef Arg) { typedef InlineCommandComment::Argument Argument; - Argument *A = new (Allocator) Argument(SourceRange(ArgLocBegin, - ArgLocEnd), - Arg); + Argument *A = + new (Allocator) Argument(SourceRange(ArgLocBegin, ArgLocEnd), Arg); StringRef CommandName = Traits.getCommandInfo(CommandID)->Name; return new (Allocator) InlineCommandComment( - CommandLocBegin, - CommandLocEnd, - CommandID, - getInlineCommandRenderKind(CommandName), - llvm::makeArrayRef(A, 1)); + CommandLocBegin, CommandLocEnd, CommandID, + getInlineCommandRenderKind(CommandName), llvm::makeArrayRef(A, 1)); } InlineContentComment *Sema::actOnUnknownCommand(SourceLocation LocBegin, @@ -408,13 +384,10 @@ unsigned CommandID) { ArrayRef Args; return new (Allocator) InlineCommandComment( - LocBegin, LocEnd, CommandID, - InlineCommandComment::RenderNormal, - Args); + LocBegin, LocEnd, CommandID, InlineCommandComment::RenderNormal, Args); } -TextComment *Sema::actOnText(SourceLocation LocBegin, - SourceLocation LocEnd, +TextComment *Sema::actOnText(SourceLocation LocBegin, SourceLocation LocEnd, StringRef Text) { return new (Allocator) TextComment(LocBegin, LocEnd, Text); } @@ -423,9 +396,7 @@ unsigned CommandID) { StringRef CommandName = Traits.getCommandInfo(CommandID)->Name; return new (Allocator) VerbatimBlockComment( - Loc, - Loc.getLocWithOffset(1 + CommandName.size()), - CommandID); + Loc, Loc.getLocWithOffset(1 + CommandName.size()), CommandID); } VerbatimBlockLineComment *Sema::actOnVerbatimBlockLine(SourceLocation Loc, @@ -434,10 +405,8 @@ } void Sema::actOnVerbatimBlockFinish( - VerbatimBlockComment *Block, - SourceLocation CloseNameLocBegin, - StringRef CloseName, - ArrayRef Lines) { + VerbatimBlockComment *Block, SourceLocation CloseNameLocBegin, + StringRef CloseName, ArrayRef Lines) { Block->setCloseName(CloseName, CloseNameLocBegin); Block->setLines(Lines); } @@ -446,12 +415,9 @@ unsigned CommandID, SourceLocation TextBegin, StringRef Text) { - VerbatimLineComment *VL = new (Allocator) VerbatimLineComment( - LocBegin, - TextBegin.getLocWithOffset(Text.size()), - CommandID, - TextBegin, - Text); + VerbatimLineComment *VL = new (Allocator) + VerbatimLineComment(LocBegin, TextBegin.getLocWithOffset(Text.size()), + CommandID, TextBegin, Text); checkFunctionDeclVerbatimLine(VL); checkContainerDeclVerbatimLine(VL); return VL; @@ -463,10 +429,8 @@ } void Sema::actOnHTMLStartTagFinish( - HTMLStartTagComment *Tag, - ArrayRef Attrs, - SourceLocation GreaterLoc, - bool IsSelfClosing) { + HTMLStartTagComment *Tag, ArrayRef Attrs, + SourceLocation GreaterLoc, bool IsSelfClosing) { Tag->setAttrs(Attrs); Tag->setGreaterLoc(GreaterLoc); if (IsSelfClosing) @@ -482,14 +446,15 @@ new (Allocator) HTMLEndTagComment(LocBegin, LocEnd, TagName); if (isHTMLEndTagForbidden(TagName)) { Diag(HET->getLocation(), diag::warn_doc_html_end_forbidden) - << TagName << HET->getSourceRange(); + << TagName << HET->getSourceRange(); HET->setIsMalformed(); return HET; } bool FoundOpen = false; for (SmallVectorImpl::const_reverse_iterator - I = HTMLOpenTags.rbegin(), E = HTMLOpenTags.rend(); + I = HTMLOpenTags.rbegin(), + E = HTMLOpenTags.rend(); I != E; ++I) { if ((*I)->getTagName() == TagName) { FoundOpen = true; @@ -498,7 +463,7 @@ } if (!FoundOpen) { Diag(HET->getLocation(), diag::warn_doc_html_end_unbalanced) - << HET->getSourceRange(); + << HET->getSourceRange(); HET->setIsMalformed(); return HET; } @@ -517,25 +482,22 @@ continue; bool OpenLineInvalid; - const unsigned OpenLine = SourceMgr.getPresumedLineNumber( - HST->getLocation(), - &OpenLineInvalid); + unsigned const OpenLine = + SourceMgr.getPresumedLineNumber(HST->getLocation(), &OpenLineInvalid); bool CloseLineInvalid; - const unsigned CloseLine = SourceMgr.getPresumedLineNumber( - HET->getLocation(), - &CloseLineInvalid); + unsigned const CloseLine = + SourceMgr.getPresumedLineNumber(HET->getLocation(), &CloseLineInvalid); if (OpenLineInvalid || CloseLineInvalid || OpenLine == CloseLine) { Diag(HST->getLocation(), diag::warn_doc_html_start_end_mismatch) - << HST->getTagName() << HET->getTagName() - << HST->getSourceRange() << HET->getSourceRange(); + << HST->getTagName() << HET->getTagName() << HST->getSourceRange() + << HET->getSourceRange(); HST->setIsMalformed(); } else { Diag(HST->getLocation(), diag::warn_doc_html_start_end_mismatch) - << HST->getTagName() << HET->getTagName() - << HST->getSourceRange(); + << HST->getTagName() << HET->getTagName() << HST->getSourceRange(); Diag(HET->getLocation(), diag::note_doc_html_end_tag) - << HET->getSourceRange(); + << HET->getSourceRange(); HST->setIsMalformed(); } } @@ -543,8 +505,7 @@ return HET; } -FullComment *Sema::actOnFullComment( - ArrayRef Blocks) { +FullComment *Sema::actOnFullComment(ArrayRef Blocks) { FullComment *FC = new (Allocator) FullComment(Blocks, ThisDeclInfo); resolveParamCommandIndexes(FC); @@ -555,7 +516,7 @@ continue; Diag(HST->getLocation(), diag::warn_doc_html_missing_end_tag) - << HST->getTagName() << HST->getSourceRange(); + << HST->getTagName() << HST->getSourceRange(); HST->setIsMalformed(); } @@ -574,13 +535,12 @@ if (!DiagLoc.isValid()) DiagLoc = Command->getCommandNameRange(Traits).getEnd(); Diag(DiagLoc, diag::warn_doc_block_command_empty_paragraph) - << Command->getCommandMarker() - << Command->getCommandName(Traits) - << Command->getSourceRange(); + << Command->getCommandMarker() << Command->getCommandName(Traits) + << Command->getSourceRange(); } } -void Sema::checkReturnsCommand(const BlockCommandComment *Command) { +void Sema::checkReturnsCommand(BlockCommandComment const *Command) { if (!Traits.getCommandInfo(Command->getCommandID())->IsReturnsCommand) return; @@ -611,24 +571,21 @@ } Diag(Command->getLocation(), diag::warn_doc_returns_attached_to_a_void_function) - << Command->getCommandMarker() - << Command->getCommandName(Traits) - << DiagKind - << Command->getSourceRange(); + << Command->getCommandMarker() << Command->getCommandName(Traits) + << DiagKind << Command->getSourceRange(); } return; } Diag(Command->getLocation(), diag::warn_doc_returns_not_attached_to_a_function_decl) - << Command->getCommandMarker() - << Command->getCommandName(Traits) - << Command->getSourceRange(); + << Command->getCommandMarker() << Command->getCommandName(Traits) + << Command->getSourceRange(); } -void Sema::checkBlockCommandDuplicate(const BlockCommandComment *Command) { - const CommandInfo *Info = Traits.getCommandInfo(Command->getCommandID()); - const BlockCommandComment *PrevCommand = nullptr; +void Sema::checkBlockCommandDuplicate(BlockCommandComment const *Command) { + CommandInfo const *Info = Traits.getCommandInfo(Command->getCommandID()); + BlockCommandComment const *PrevCommand = nullptr; if (Info->IsBriefCommand) { if (!BriefCommand) { BriefCommand = Command; @@ -648,34 +605,29 @@ StringRef CommandName = Command->getCommandName(Traits); StringRef PrevCommandName = PrevCommand->getCommandName(Traits); Diag(Command->getLocation(), diag::warn_doc_block_command_duplicate) - << Command->getCommandMarker() - << CommandName + << Command->getCommandMarker() << CommandName << Command->getSourceRange(); if (CommandName == PrevCommandName) Diag(PrevCommand->getLocation(), diag::note_doc_block_command_previous) - << PrevCommand->getCommandMarker() - << PrevCommandName + << PrevCommand->getCommandMarker() << PrevCommandName << PrevCommand->getSourceRange(); else Diag(PrevCommand->getLocation(), diag::note_doc_block_command_previous_alias) - << PrevCommand->getCommandMarker() - << PrevCommandName - << CommandName; + << PrevCommand->getCommandMarker() << PrevCommandName << CommandName; } -void Sema::checkDeprecatedCommand(const BlockCommandComment *Command) { +void Sema::checkDeprecatedCommand(BlockCommandComment const *Command) { if (!Traits.getCommandInfo(Command->getCommandID())->IsDeprecatedCommand) return; assert(ThisDeclInfo && "should not call this check on a bare comment"); - const Decl *D = ThisDeclInfo->CommentDecl; + Decl const *D = ThisDeclInfo->CommentDecl; if (!D) return; - if (D->hasAttr() || - D->hasAttr() || + if (D->hasAttr() || D->hasAttr() || D->hasAttr()) return; @@ -683,16 +635,15 @@ << Command->getSourceRange() << Command->getCommandMarker(); // Try to emit a fixit with a deprecation attribute. - if (const FunctionDecl *FD = dyn_cast(D)) { + if (FunctionDecl const *FD = dyn_cast(D)) { // Don't emit a Fix-It for non-member function definitions. GCC does not // accept attributes on them. - const DeclContext *Ctx = FD->getDeclContext(); - if ((!Ctx || !Ctx->isRecord()) && - FD->doesThisDeclarationHaveABody()) + DeclContext const *Ctx = FD->getDeclContext(); + if ((!Ctx || !Ctx->isRecord()) && FD->doesThisDeclarationHaveABody()) return; - const LangOptions &LO = FD->getLangOpts(); - const bool DoubleSquareBracket = LO.CPlusPlus14 || LO.C2x; + LangOptions const &LO = FD->getLangOpts(); + bool const DoubleSquareBracket = LO.CPlusPlus14 || LO.C2x; StringRef AttributeSpelling = DoubleSquareBracket ? "[[deprecated]]" : "__attribute__((deprecated))"; if (PP) { @@ -729,7 +680,7 @@ } } -void Sema::resolveParamCommandIndexes(const FullComment *FC) { +void Sema::resolveParamCommandIndexes(FullComment const *FC) { if (!isFunctionDecl()) { // We already warned that \\param commands are not attached to a function // decl. @@ -742,7 +693,7 @@ // found a \\param command or NULL if no documentation was found so far. SmallVector ParamVarDocs; - ArrayRef ParamVars = getParamVars(); + ArrayRef ParamVars = getParamVars(); ParamVarDocs.resize(ParamVars.size(), nullptr); // First pass over all \\param commands: resolve all parameter names. @@ -754,8 +705,8 @@ StringRef ParamName = PCC->getParamNameAsWritten(); // Check that referenced parameter name is in the function decl. - const unsigned ResolvedParamIndex = resolveParmVarReference(ParamName, - ParamVars); + unsigned const ResolvedParamIndex = + resolveParmVarReference(ParamName, ParamVars); if (ResolvedParamIndex == ParamCommandComment::VarArgParamIndex) { PCC->setIsVarArgParam(); continue; @@ -768,16 +719,16 @@ if (ParamVarDocs[ResolvedParamIndex]) { SourceRange ArgRange = PCC->getParamNameRange(); Diag(ArgRange.getBegin(), diag::warn_doc_param_duplicate) - << ParamName << ArgRange; + << ParamName << ArgRange; ParamCommandComment *PrevCommand = ParamVarDocs[ResolvedParamIndex]; Diag(PrevCommand->getLocation(), diag::note_doc_param_previous) - << PrevCommand->getParamNameRange(); + << PrevCommand->getParamNameRange(); } ParamVarDocs[ResolvedParamIndex] = PCC; } // Find parameter declarations that have no corresponding \\param. - SmallVector OrphanedParamDecls; + SmallVector OrphanedParamDecls; for (unsigned i = 0, e = ParamVarDocs.size(); i != e; ++i) { if (!ParamVarDocs[i]) OrphanedParamDecls.push_back(ParamVars[i]); @@ -787,12 +738,12 @@ // Suggest corrections from a set of parameter declarations that have no // corresponding \\param. for (unsigned i = 0, e = UnresolvedParamCommands.size(); i != e; ++i) { - const ParamCommandComment *PCC = UnresolvedParamCommands[i]; + ParamCommandComment const *PCC = UnresolvedParamCommands[i]; SourceRange ArgRange = PCC->getParamNameRange(); StringRef ParamName = PCC->getParamNameAsWritten(); Diag(ArgRange.getBegin(), diag::warn_doc_param_not_found) - << ParamName << ArgRange; + << ParamName << ArgRange; // All parameters documented -- can't suggest a correction. if (OrphanedParamDecls.size() == 0) @@ -805,15 +756,15 @@ CorrectedParamIndex = 0; } else { // Do typo correction. - CorrectedParamIndex = correctTypoInParmVarReference(ParamName, - OrphanedParamDecls); + CorrectedParamIndex = + correctTypoInParmVarReference(ParamName, OrphanedParamDecls); } if (CorrectedParamIndex != ParamCommandComment::InvalidParamIndex) { - const ParmVarDecl *CorrectedPVD = OrphanedParamDecls[CorrectedParamIndex]; - if (const IdentifierInfo *CorrectedII = CorrectedPVD->getIdentifier()) + ParmVarDecl const *CorrectedPVD = OrphanedParamDecls[CorrectedParamIndex]; + if (IdentifierInfo const *CorrectedII = CorrectedPVD->getIdentifier()) Diag(ArgRange.getBegin(), diag::note_doc_param_name_suggestion) - << CorrectedII->getName() - << FixItHint::CreateReplacement(ArgRange, CorrectedII->getName()); + << CorrectedII->getName() + << FixItHint::CreateReplacement(ArgRange, CorrectedII->getName()); } } } @@ -834,21 +785,21 @@ bool Sema::isFunctionOrMethodVariadic() { if (!isFunctionDecl() || !ThisDeclInfo->CurrentDecl) return false; - if (const FunctionDecl *FD = - dyn_cast(ThisDeclInfo->CurrentDecl)) + if (FunctionDecl const *FD = + dyn_cast(ThisDeclInfo->CurrentDecl)) return FD->isVariadic(); - if (const FunctionTemplateDecl *FTD = - dyn_cast(ThisDeclInfo->CurrentDecl)) + if (FunctionTemplateDecl const *FTD = + dyn_cast(ThisDeclInfo->CurrentDecl)) return FTD->getTemplatedDecl()->isVariadic(); - if (const ObjCMethodDecl *MD = - dyn_cast(ThisDeclInfo->CurrentDecl)) + if (ObjCMethodDecl const *MD = + dyn_cast(ThisDeclInfo->CurrentDecl)) return MD->isVariadic(); - if (const TypedefNameDecl *TD = + if (TypedefNameDecl const *TD = dyn_cast(ThisDeclInfo->CurrentDecl)) { QualType Type = TD->getUnderlyingType(); if (Type->isFunctionPointerType() || Type->isBlockPointerType()) Type = Type->getPointeeType(); - if (const auto *FT = Type->getAs()) + if (auto const *FT = Type->getAs()) return FT->isVariadic(); } return false; @@ -865,7 +816,8 @@ if (!ThisDeclInfo->IsFilled) inspectThisDecl(); if (ThisDeclInfo->getKind() == DeclInfo::VariableKind) { - if (const VarDecl *VD = dyn_cast_or_null(ThisDeclInfo->CurrentDecl)) { + if (VarDecl const *VD = + dyn_cast_or_null(ThisDeclInfo->CurrentDecl)) { QualType QT = VD->getType(); return QT->isFunctionPointerType(); } @@ -882,9 +834,9 @@ !ThisDeclInfo->CurrentDecl) return false; QualType QT; - if (const auto *VD = dyn_cast(ThisDeclInfo->CurrentDecl)) + if (auto const *VD = dyn_cast(ThisDeclInfo->CurrentDecl)) QT = VD->getType(); - else if (const auto *PD = + else if (auto const *PD = dyn_cast(ThisDeclInfo->CurrentDecl)) QT = PD->getType(); else @@ -894,10 +846,10 @@ // can be ignored. if (QT->getAs()) return false; - if (const auto *P = QT->getAs()) + if (auto const *P = QT->getAs()) if (P->getPointeeType()->getAs()) return false; - if (const auto *P = QT->getAs()) + if (auto const *P = QT->getAs()) if (P->getPointeeType()->getAs()) return false; return QT->isFunctionPointerType() || QT->isBlockPointerType(); @@ -933,12 +885,12 @@ return false; if (!ThisDeclInfo->IsFilled) inspectThisDecl(); - if (const RecordDecl *RD = - dyn_cast_or_null(ThisDeclInfo->CurrentDecl)) + if (RecordDecl const *RD = + dyn_cast_or_null(ThisDeclInfo->CurrentDecl)) return RD->isUnion(); return false; } -static bool isClassOrStructDeclImpl(const Decl *D) { +static bool isClassOrStructDeclImpl(Decl const *D) { if (auto *record = dyn_cast_or_null(D)) return !record->isUnion(); @@ -969,7 +921,8 @@ if (isClassOrStructDeclImpl(ThisDeclInfo->CurrentDecl)) return true; - if (auto *ThisTypedefDecl = dyn_cast(ThisDeclInfo->CurrentDecl)) { + if (auto *ThisTypedefDecl = + dyn_cast(ThisDeclInfo->CurrentDecl)) { auto UnderlyingType = ThisTypedefDecl->getUnderlyingType(); if (auto ThisElaboratedType = dyn_cast(UnderlyingType)) { auto DesugaredType = ThisElaboratedType->desugar(); @@ -990,7 +943,7 @@ if (!ThisDeclInfo->IsFilled) inspectThisDecl(); return ThisDeclInfo->CurrentDecl && - (isa(ThisDeclInfo->CurrentDecl)); + (isa(ThisDeclInfo->CurrentDecl)); } bool Sema::isFunctionTemplateDecl() { @@ -1020,20 +973,19 @@ isa(ThisDeclInfo->CurrentDecl); } -ArrayRef Sema::getParamVars() { +ArrayRef Sema::getParamVars() { if (!ThisDeclInfo->IsFilled) inspectThisDecl(); return ThisDeclInfo->ParamVars; } -void Sema::inspectThisDecl() { - ThisDeclInfo->fill(); -} +void Sema::inspectThisDecl() { ThisDeclInfo->fill(); } -unsigned Sema::resolveParmVarReference(StringRef Name, - ArrayRef ParamVars) { +unsigned +Sema::resolveParmVarReference(StringRef Name, + ArrayRef ParamVars) { for (unsigned i = 0, e = ParamVars.size(); i != e; ++i) { - const IdentifierInfo *II = ParamVars[i]->getIdentifier(); + IdentifierInfo const *II = ParamVars[i]->getIdentifier(); if (II && II->getName() == Name) return i; } @@ -1044,10 +996,10 @@ namespace { class SimpleTypoCorrector { - const NamedDecl *BestDecl; + NamedDecl const *BestDecl; StringRef Typo; - const unsigned MaxEditDistance; + unsigned const MaxEditDistance; unsigned BestEditDistance; unsigned BestIndex; @@ -1058,9 +1010,9 @@ : BestDecl(nullptr), Typo(Typo), MaxEditDistance((Typo.size() + 2) / 3), BestEditDistance(MaxEditDistance + 1), BestIndex(0), NextIndex(0) {} - void addDecl(const NamedDecl *ND); + void addDecl(NamedDecl const *ND); - const NamedDecl *getBestDecl() const { + NamedDecl const *getBestDecl() const { if (BestEditDistance > MaxEditDistance) return nullptr; @@ -1073,17 +1025,16 @@ } }; -void SimpleTypoCorrector::addDecl(const NamedDecl *ND) { +void SimpleTypoCorrector::addDecl(NamedDecl const *ND) { unsigned CurrIndex = NextIndex++; - const IdentifierInfo *II = ND->getIdentifier(); + IdentifierInfo const *II = ND->getIdentifier(); if (!II) return; StringRef Name = II->getName(); unsigned MinPossibleEditDistance = abs((int)Name.size() - (int)Typo.size()); - if (MinPossibleEditDistance > 0 && - Typo.size() / MinPossibleEditDistance < 3) + if (MinPossibleEditDistance > 0 && Typo.size() / MinPossibleEditDistance < 3) return; unsigned EditDistance = Typo.edit_distance(Name, true, MaxEditDistance); @@ -1095,9 +1046,9 @@ } } // end anonymous namespace -unsigned Sema::correctTypoInParmVarReference( - StringRef Typo, - ArrayRef ParamVars) { +unsigned +Sema::correctTypoInParmVarReference(StringRef Typo, + ArrayRef ParamVars) { SimpleTypoCorrector Corrector(Typo); for (unsigned i = 0, e = ParamVars.size(); i != e; ++i) Corrector.addDecl(ParamVars[i]); @@ -1109,18 +1060,17 @@ namespace { bool ResolveTParamReferenceHelper( - StringRef Name, - const TemplateParameterList *TemplateParameters, - SmallVectorImpl *Position) { + StringRef Name, TemplateParameterList const *TemplateParameters, + SmallVectorImpl *Position) { for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) { - const NamedDecl *Param = TemplateParameters->getParam(i); - const IdentifierInfo *II = Param->getIdentifier(); + NamedDecl const *Param = TemplateParameters->getParam(i); + IdentifierInfo const *II = Param->getIdentifier(); if (II && II->getName() == Name) { Position->push_back(i); return true; } - if (const TemplateTemplateParmDecl *TTP = + if (TemplateTemplateParmDecl const *TTP = dyn_cast(Param)) { Position->push_back(i); if (ResolveTParamReferenceHelper(Name, TTP->getTemplateParameters(), @@ -1134,9 +1084,8 @@ } // end anonymous namespace bool Sema::resolveTParamReference( - StringRef Name, - const TemplateParameterList *TemplateParameters, - SmallVectorImpl *Position) { + StringRef Name, TemplateParameterList const *TemplateParameters, + SmallVectorImpl *Position) { Position->clear(); if (!TemplateParameters) return false; @@ -1146,13 +1095,13 @@ namespace { void CorrectTypoInTParamReferenceHelper( - const TemplateParameterList *TemplateParameters, - SimpleTypoCorrector &Corrector) { + TemplateParameterList const *TemplateParameters, + SimpleTypoCorrector &Corrector) { for (unsigned i = 0, e = TemplateParameters->size(); i != e; ++i) { - const NamedDecl *Param = TemplateParameters->getParam(i); + NamedDecl const *Param = TemplateParameters->getParam(i); Corrector.addDecl(Param); - if (const TemplateTemplateParmDecl *TTP = + if (TemplateTemplateParmDecl const *TTP = dyn_cast(Param)) CorrectTypoInTParamReferenceHelper(TTP->getTemplateParameters(), Corrector); @@ -1161,12 +1110,11 @@ } // end anonymous namespace StringRef Sema::correctTypoInTParamReference( - StringRef Typo, - const TemplateParameterList *TemplateParameters) { + StringRef Typo, TemplateParameterList const *TemplateParameters) { SimpleTypoCorrector Corrector(Typo); CorrectTypoInTParamReferenceHelper(TemplateParameters, Corrector); - if (const NamedDecl *ND = Corrector.getBestDecl()) { - const IdentifierInfo *II = ND->getIdentifier(); + if (NamedDecl const *ND = Corrector.getBestDecl()) { + IdentifierInfo const *II = ND->getIdentifier(); assert(II && "SimpleTypoCorrector should not return this decl"); return II->getName(); } Index: clang/lib/AST/ComparisonCategories.cpp =================================================================== --- clang/lib/AST/ComparisonCategories.cpp +++ clang/lib/AST/ComparisonCategories.cpp @@ -86,7 +86,7 @@ return &Objects.back(); } -static const NamespaceDecl *lookupStdNamespace(const ASTContext &Ctx, +static NamespaceDecl const *lookupStdNamespace(ASTContext const &Ctx, NamespaceDecl *&StdNS) { if (!StdNS) { DeclContextLookupResult Lookup = @@ -97,8 +97,8 @@ return StdNS; } -static CXXRecordDecl *lookupCXXRecordDecl(const ASTContext &Ctx, - const NamespaceDecl *StdNS, +static CXXRecordDecl *lookupCXXRecordDecl(ASTContext const &Ctx, + NamespaceDecl const *StdNS, ComparisonCategoryType Kind) { StringRef Name = ComparisonCategories::getCategoryString(Kind); DeclContextLookupResult Lookup = StdNS->lookup(&Ctx.Idents.get(Name)); @@ -108,20 +108,20 @@ return nullptr; } -const ComparisonCategoryInfo * +ComparisonCategoryInfo const * ComparisonCategories::lookupInfo(ComparisonCategoryType Kind) const { auto It = Data.find(static_cast(Kind)); if (It != Data.end()) return &It->second; - if (const NamespaceDecl *NS = lookupStdNamespace(Ctx, StdNS)) + if (NamespaceDecl const *NS = lookupStdNamespace(Ctx, StdNS)) if (CXXRecordDecl *RD = lookupCXXRecordDecl(Ctx, NS, Kind)) return &Data.try_emplace((char)Kind, Ctx, RD, Kind).first->second; return nullptr; } -const ComparisonCategoryInfo * +ComparisonCategoryInfo const * ComparisonCategories::lookupInfoForType(QualType Ty) const { assert(!Ty.isNull() && "type must be non-null"); using CCT = ComparisonCategoryType; @@ -130,9 +130,9 @@ return nullptr; // Check to see if we have information for the specified type cached. - const auto *CanonRD = RD->getCanonicalDecl(); + auto const *CanonRD = RD->getCanonicalDecl(); for (auto &KV : Data) { - const ComparisonCategoryInfo &Info = KV.second; + ComparisonCategoryInfo const &Info = KV.second; if (CanonRD == Info.Record->getCanonicalDecl()) return &Info; } @@ -157,8 +157,9 @@ return nullptr; } -const ComparisonCategoryInfo &ComparisonCategories::getInfoForType(QualType Ty) const { - const ComparisonCategoryInfo *Info = lookupInfoForType(Ty); +ComparisonCategoryInfo const & +ComparisonCategories::getInfoForType(QualType Ty) const { + ComparisonCategoryInfo const *Info = lookupInfoForType(Ty); assert(Info && "info for comparison category not found"); return *Info; } Index: clang/lib/AST/ComputeDependence.cpp =================================================================== --- clang/lib/AST/ComputeDependence.cpp +++ clang/lib/AST/ComputeDependence.cpp @@ -38,7 +38,7 @@ } ExprDependence clang::computeDependence(UnaryOperator *E, - const ASTContext &Ctx) { + ASTContext const &Ctx) { ExprDependence Dep = toExprDependence(E->getType()->getDependence()) | E->getSubExpr()->getDependence(); @@ -60,7 +60,7 @@ // FIXME: This doesn't enforce the C++98 constant expression rules. if (E->getSubExpr()->EvaluateAsConstantExpr(Result, Ctx) && Diag.empty() && Result.Val.isLValue()) { - auto *VD = Result.Val.getLValueBase().dyn_cast(); + auto *VD = Result.Val.getLValueBase().dyn_cast(); if (VD && VD->isTemplated()) { auto *VarD = dyn_cast(VD); if (!VarD || !VarD->hasLocalStorage()) @@ -93,14 +93,14 @@ return Deps; auto *NoParens = E->getArgumentExpr()->IgnoreParens(); - const ValueDecl *D = nullptr; - if (const auto *DRE = dyn_cast(NoParens)) + ValueDecl const *D = nullptr; + if (auto const *DRE = dyn_cast(NoParens)) D = DRE->getDecl(); - else if (const auto *ME = dyn_cast(NoParens)) + else if (auto const *ME = dyn_cast(NoParens)) D = ME->getMemberDecl(); if (!D) return Deps; - for (const auto *I : D->specific_attrs()) { + for (auto const *I : D->specific_attrs()) { if (I->isAlignmentErrorDependent()) Deps |= ExprDependence::Error; if (I->isAlignmentDependent()) @@ -160,9 +160,9 @@ ExprDependence clang::computeDependence(StmtExpr *E, unsigned TemplateDepth) { auto D = toExprDependence(E->getType()->getDependence()); // Propagate dependence of the result. - if (const auto *CompoundExprResult = + if (auto const *CompoundExprResult = dyn_cast_or_null(E->getSubStmt()->getStmtExprResult())) - if (const Expr *ResultExpr = CompoundExprResult->getExprStmt()) + if (Expr const *ResultExpr = CompoundExprResult->getExprStmt()) D |= ResultExpr->getDependence(); // Note: we treat a statement-expression in a dependent context as always // being value- and instantiation-dependent. This matches the behavior of @@ -408,7 +408,7 @@ ExprDependence clang::computeDependence(OMPArrayShapingExpr *E) { auto D = E->getBase()->getDependence() | toExprDependence(E->getType()->getDependence()); - for (Expr *Dim: E->getDimensions()) + for (Expr *Dim : E->getDimensions()) if (Dim) D |= Dim->getDependence(); return D; @@ -433,7 +433,7 @@ /// Compute the type-, value-, and instantiation-dependence of a /// declaration reference /// based on the declaration being referenced. -ExprDependence clang::computeDependence(DeclRefExpr *E, const ASTContext &Ctx) { +ExprDependence clang::computeDependence(DeclRefExpr *E, ASTContext const &Ctx) { auto Deps = ExprDependence::None; if (auto *NNS = E->getQualifier()) @@ -498,9 +498,9 @@ // - it names a potentially-constant variable that is initialized with an // expression that is value-dependent - if (const auto *Var = dyn_cast(Decl)) { + if (auto const *Var = dyn_cast(Decl)) { if (Var->mightBeUsableInConstantExpressions(Ctx)) { - if (const Expr *Init = Var->getAnyInitializer()) { + if (Expr const *Init = Var->getAnyInitializer()) { if (Init->isValueDependent()) Deps |= ExprDependence::ValueInstantiation; if (Init->containsErrors()) @@ -513,7 +513,7 @@ if (Var->isStaticDataMember() && Var->getDeclContext()->isDependentContext() && !Var->getFirstDecl()->hasInit()) { - const VarDecl *First = Var->getFirstDecl(); + VarDecl const *First = Var->getFirstDecl(); TypeSourceInfo *TInfo = First->getTypeSourceInfo(); if (TInfo->getType()->isIncompleteArrayType()) { Deps |= ExprDependence::TypeValueInstantiation; @@ -690,7 +690,7 @@ return D; } -static inline ExprDependence getDependenceInExpr(DeclarationNameInfo Name) { +inline static ExprDependence getDependenceInExpr(DeclarationNameInfo Name) { auto D = ExprDependence::None; if (Name.isInstantiationDependent()) D |= ExprDependence::Instantiation; @@ -787,7 +787,7 @@ ExprDependence clang::computeDependence(CXXFoldExpr *E) { auto D = ExprDependence::TypeValueInstantiation; - for (const auto *C : {E->getLHS(), E->getRHS()}) { + for (auto const *C : {E->getLHS(), E->getRHS()}) { if (C) D |= C->getDependence() & ~ExprDependence::UnexpandedPack; } @@ -796,7 +796,7 @@ ExprDependence clang::computeDependence(TypeTraitExpr *E) { auto D = ExprDependence::None; - for (const auto *A : E->getArgs()) + for (auto const *A : E->getArgs()) D |= toExprDependence(A->getType()->getDependence()) & ~ExprDependence::Type; return D; @@ -805,9 +805,9 @@ ExprDependence clang::computeDependence(ConceptSpecializationExpr *E, bool ValueDependent) { auto TA = TemplateArgumentDependence::None; - const auto InterestingDeps = TemplateArgumentDependence::Instantiation | + auto const InterestingDeps = TemplateArgumentDependence::Instantiation | TemplateArgumentDependence::UnexpandedPack; - for (const TemplateArgumentLoc &ArgLoc : + for (TemplateArgumentLoc const &ArgLoc : E->getTemplateArgsAsWritten()->arguments()) { TA |= ArgLoc.getArgument().getDependence() & InterestingDeps; if (TA == InterestingDeps) Index: clang/lib/AST/Decl.cpp =================================================================== --- clang/lib/AST/Decl.cpp +++ clang/lib/AST/Decl.cpp @@ -79,7 +79,8 @@ void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { SourceLocation Loc = this->Loc; - if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); + if (!Loc.isValid() && TheDecl) + Loc = TheDecl->getLocation(); if (Loc.isValid()) { Loc.print(OS, Context.getSourceManager()); OS << ": "; @@ -162,13 +163,12 @@ /// Given an LVComputationKind, return one of the same type/value sort /// that records that it already has explicit visibility. -static LVComputationKind -withExplicitVisibilityAlready(LVComputationKind Kind) { +static LVComputationKind withExplicitVisibilityAlready(LVComputationKind Kind) { Kind.IgnoreExplicitVisibility = true; return Kind; } -static Optional getExplicitVisibility(const NamedDecl *D, +static Optional getExplicitVisibility(NamedDecl const *D, LVComputationKind kind) { assert(!kind.IgnoreExplicitVisibility && "asking for explicit visibility when we shouldn't be"); @@ -177,19 +177,19 @@ /// Is the given declaration a "type" or a "value" for the purposes of /// visibility computation? -static bool usesTypeVisibility(const NamedDecl *D) { - return isa(D) || - isa(D) || +static bool usesTypeVisibility(NamedDecl const *D) { + return isa(D) || isa(D) || isa(D); } /// Does the given declaration have member specialization information, /// and if so, is it an explicit specialization? -template static typename -std::enable_if::value, bool>::type +template +static typename std::enable_if< + !std::is_base_of::value, bool>::type isExplicitMemberSpecialization(const T *D) { - if (const MemberSpecializationInfo *member = - D->getMemberSpecializationInfo()) { + if (MemberSpecializationInfo const *member = + D->getMemberSpecializationInfo()) { return member->isExplicitSpecialization(); } return false; @@ -198,14 +198,13 @@ /// For templates, this question is easier: a member template can't be /// explicitly instantiated, so there's a single bit indicating whether /// or not this is an explicit member specialization. -static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) { +static bool isExplicitMemberSpecialization(RedeclarableTemplateDecl const *D) { return D->isMemberSpecialization(); } /// Given a visibility attribute, return the explicit visibility /// associated with it. -template -static Visibility getVisibilityFromAttr(const T *attr) { +template static Visibility getVisibilityFromAttr(const T *attr) { switch (attr->getVisibility()) { case T::Default: return DefaultVisibility; @@ -218,25 +217,25 @@ } /// Return the explicit visibility of the given declaration. -static Optional getVisibilityOf(const NamedDecl *D, - NamedDecl::ExplicitVisibilityKind kind) { +static Optional +getVisibilityOf(NamedDecl const *D, NamedDecl::ExplicitVisibilityKind kind) { // If we're ultimately computing the visibility of a type, look for // a 'type_visibility' attribute before looking for 'visibility'. if (kind == NamedDecl::VisibilityForType) { - if (const auto *A = D->getAttr()) { + if (auto const *A = D->getAttr()) { return getVisibilityFromAttr(A); } } // If this declaration has an explicit visibility attribute, use it. - if (const auto *A = D->getAttr()) { + if (auto const *A = D->getAttr()) { return getVisibilityFromAttr(A); } return None; } -LinkageInfo LinkageComputer::getLVForType(const Type &T, +LinkageInfo LinkageComputer::getLVForType(Type const &T, LVComputationKind computation) { if (computation.IgnoreAllVisibility) return LinkageInfo(T.getLinkage(), DefaultVisibility, true); @@ -247,9 +246,9 @@ /// template parameter list. For visibility purposes, template /// parameters are part of the signature of a template. LinkageInfo LinkageComputer::getLVForTemplateParameterList( - const TemplateParameterList *Params, LVComputationKind computation) { + TemplateParameterList const *Params, LVComputationKind computation) { LinkageInfo LV; - for (const NamedDecl *P : *Params) { + for (NamedDecl const *P : *Params) { // Template type parameters are the most common and never // contribute to visibility, pack or not. if (isa(P)) @@ -259,7 +258,7 @@ // template class A { ... }; // We have to be careful here, though, because we can be dealing with // dependent types. - if (const auto *NTTP = dyn_cast(P)) { + if (auto const *NTTP = dyn_cast(P)) { // Handle the non-pack case first. if (!NTTP->isExpandedParameterPack()) { if (!NTTP->getType()->isDependentType()) { @@ -279,7 +278,7 @@ // Template template parameters can be restricted by their // template parameters, recursively. - const auto *TTP = cast(P); + auto const *TTP = cast(P); // Handle the non-pack case first. if (!TTP->isExpandedParameterPack()) { @@ -289,8 +288,8 @@ } // Look at all expansions in an expanded pack. - for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters(); - i != n; ++i) { + for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters(); i != n; + ++i) { LV.merge(getLVForTemplateParameterList( TTP->getExpansionTemplateParameters(i), computation)); } @@ -299,9 +298,9 @@ return LV; } -static const Decl *getOutermostFuncOrBlockContext(const Decl *D) { - const Decl *Ret = nullptr; - const DeclContext *DC = D->getDeclContext(); +static Decl const *getOutermostFuncOrBlockContext(Decl const *D) { + Decl const *Ret = nullptr; + DeclContext const *DC = D->getDeclContext(); while (DC->getDeclKind() != Decl::TranslationUnit) { if (isa(DC) || isa(DC)) Ret = cast(DC); @@ -320,7 +319,7 @@ LVComputationKind computation) { LinkageInfo LV; - for (const TemplateArgument &Arg : Args) { + for (TemplateArgument const &Arg : Args) { switch (Arg.getKind()) { case TemplateArgument::Null: case TemplateArgument::Integral: @@ -332,7 +331,7 @@ continue; case TemplateArgument::Declaration: { - const NamedDecl *ND = Arg.getAsDecl(); + NamedDecl const *ND = Arg.getAsDecl(); assert(!usesTypeVisibility(ND)); LV.merge(getLVForDecl(ND, computation)); continue; @@ -360,13 +359,14 @@ } LinkageInfo -LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, +LinkageComputer::getLVForTemplateArgumentList(TemplateArgumentList const &TArgs, LVComputationKind computation) { return getLVForTemplateArgumentList(TArgs.asArray(), computation); } -static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, - const FunctionTemplateSpecializationInfo *specInfo) { +static bool shouldConsiderTemplateVisibility( + FunctionDecl const *fn, + FunctionTemplateSpecializationInfo const *specInfo) { // Include visibility from the template parameters and arguments // only if this is not an explicit instantiation or specialization // with direct explicit visibility. (Implicit instantiations won't @@ -385,27 +385,26 @@ /// /// \param[out] LV the computation to use for the parent void LinkageComputer::mergeTemplateLV( - LinkageInfo &LV, const FunctionDecl *fn, - const FunctionTemplateSpecializationInfo *specInfo, + LinkageInfo &LV, FunctionDecl const *fn, + FunctionTemplateSpecializationInfo const *specInfo, LVComputationKind computation) { - bool considerVisibility = - shouldConsiderTemplateVisibility(fn, specInfo); + bool considerVisibility = shouldConsiderTemplateVisibility(fn, specInfo); // Merge information from the template parameters. FunctionTemplateDecl *temp = specInfo->getTemplate(); LinkageInfo tempLV = - getLVForTemplateParameterList(temp->getTemplateParameters(), computation); + getLVForTemplateParameterList(temp->getTemplateParameters(), computation); LV.mergeMaybeWithVisibility(tempLV, considerVisibility); // Merge information from the template arguments. - const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments; + TemplateArgumentList const &templateArgs = *specInfo->TemplateArguments; LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); LV.mergeMaybeWithVisibility(argsLV, considerVisibility); } /// Does the given declaration have a direct visibility attribute /// that would match the given rules? -static bool hasDirectVisibilityAttribute(const NamedDecl *D, +static bool hasDirectVisibilityAttribute(NamedDecl const *D, LVComputationKind computation) { if (computation.IgnoreAllVisibility) return false; @@ -416,8 +415,8 @@ /// Should we consider visibility associated with the template /// arguments and parameters of the given class template specialization? -static bool shouldConsiderTemplateVisibility( - const ClassTemplateSpecializationDecl *spec, +static bool +shouldConsiderTemplateVisibility(ClassTemplateSpecializationDecl const *spec, LVComputationKind computation) { // Include visibility from the template parameters and arguments // only if this is not an explicit instantiation or specialization @@ -453,7 +452,7 @@ /// Merge in template-related linkage and visibility for the given /// class template specialization. void LinkageComputer::mergeTemplateLV( - LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec, + LinkageInfo &LV, ClassTemplateSpecializationDecl const *spec, LVComputationKind computation) { bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); @@ -462,14 +461,14 @@ ClassTemplateDecl *temp = spec->getSpecializedTemplate(); LinkageInfo tempLV = - getLVForTemplateParameterList(temp->getTemplateParameters(), computation); - LV.mergeMaybeWithVisibility(tempLV, - considerVisibility && !hasExplicitVisibilityAlready(computation)); + getLVForTemplateParameterList(temp->getTemplateParameters(), computation); + LV.mergeMaybeWithVisibility( + tempLV, considerVisibility && !hasExplicitVisibilityAlready(computation)); // Merge information from the template arguments. We ignore // template-argument visibility if we've got an explicit // instantiation with a visibility attribute. - const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); + TemplateArgumentList const &templateArgs = spec->getTemplateArgs(); LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); if (considerVisibility) LV.mergeVisibility(argsLV); @@ -480,8 +479,8 @@ /// arguments and parameters of the given variable template /// specialization? As usual, follow class template specialization /// logic up to initialization. -static bool shouldConsiderTemplateVisibility( - const VarTemplateSpecializationDecl *spec, +static bool +shouldConsiderTemplateVisibility(VarTemplateSpecializationDecl const *spec, LVComputationKind computation) { // Include visibility from the template parameters and arguments // only if this is not an explicit instantiation or specialization @@ -505,7 +504,7 @@ /// variable template specialization. As usual, follow class template /// specialization logic up to initialization. void LinkageComputer::mergeTemplateLV(LinkageInfo &LV, - const VarTemplateSpecializationDecl *spec, + VarTemplateSpecializationDecl const *spec, LVComputationKind computation) { bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); @@ -514,46 +513,46 @@ VarTemplateDecl *temp = spec->getSpecializedTemplate(); LinkageInfo tempLV = - getLVForTemplateParameterList(temp->getTemplateParameters(), computation); - LV.mergeMaybeWithVisibility(tempLV, - considerVisibility && !hasExplicitVisibilityAlready(computation)); + getLVForTemplateParameterList(temp->getTemplateParameters(), computation); + LV.mergeMaybeWithVisibility( + tempLV, considerVisibility && !hasExplicitVisibilityAlready(computation)); // Merge information from the template arguments. We ignore // template-argument visibility if we've got an explicit // instantiation with a visibility attribute. - const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); + TemplateArgumentList const &templateArgs = spec->getTemplateArgs(); LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation); if (considerVisibility) LV.mergeVisibility(argsLV); LV.mergeExternalVisibility(argsLV); } -static bool useInlineVisibilityHidden(const NamedDecl *D) { +static bool useInlineVisibilityHidden(NamedDecl const *D) { // FIXME: we should warn if -fvisibility-inlines-hidden is used with c. - const LangOptions &Opts = D->getASTContext().getLangOpts(); + LangOptions const &Opts = D->getASTContext().getLangOpts(); if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden) return false; - const auto *FD = dyn_cast(D); + auto const *FD = dyn_cast(D); if (!FD) return false; TemplateSpecializationKind TSK = TSK_Undeclared; - if (FunctionTemplateSpecializationInfo *spec - = FD->getTemplateSpecializationInfo()) { + if (FunctionTemplateSpecializationInfo *spec = + FD->getTemplateSpecializationInfo()) { TSK = spec->getTemplateSpecializationKind(); } else if (MemberSpecializationInfo *MSI = - FD->getMemberSpecializationInfo()) { + FD->getMemberSpecializationInfo()) { TSK = MSI->getTemplateSpecializationKind(); } - const FunctionDecl *Def = nullptr; + FunctionDecl const *Def = nullptr; // InlineVisibilityHidden only applies to definitions, and // isInlined() only gives meaningful answers on definitions // anyway. return TSK != TSK_ExplicitInstantiationDeclaration && - TSK != TSK_ExplicitInstantiationDefinition && - FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr(); + TSK != TSK_ExplicitInstantiationDefinition && FD->hasBody(Def) && + Def->isInlined() && !Def->hasAttr(); } template static bool isFirstInExternCContext(T *D) { @@ -561,21 +560,21 @@ return First->isInExternCContext(); } -static bool isSingleLineLanguageLinkage(const Decl &D) { - if (const auto *SD = dyn_cast(D.getDeclContext())) +static bool isSingleLineLanguageLinkage(Decl const &D) { + if (auto const *SD = dyn_cast(D.getDeclContext())) if (!SD->hasBraces()) return true; return false; } /// Determine whether D is declared in the purview of a named module. -static bool isInModulePurview(const NamedDecl *D) { +static bool isInModulePurview(NamedDecl const *D) { if (auto *M = D->getOwningModule()) return M->isModulePurview(); return false; } -static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) { +static bool isExportedFromModuleInterfaceUnit(NamedDecl const *D) { // FIXME: Handle isModulePrivate. switch (D->getModuleOwnershipKind()) { case Decl::ModuleOwnershipKind::Unowned: @@ -588,7 +587,7 @@ llvm_unreachable("unexpected module ownership kind"); } -static LinkageInfo getInternalLinkageFor(const NamedDecl *D) { +static LinkageInfo getInternalLinkageFor(NamedDecl const *D) { // Internal linkage declarations within a module interface unit are modeled // as "module-internal linkage", which means that they have internal linkage // formally but can be indirectly accessed from outside the module via inline @@ -599,7 +598,7 @@ return LinkageInfo::internal(); } -static LinkageInfo getExternalLinkageFor(const NamedDecl *D) { +static LinkageInfo getExternalLinkageFor(NamedDecl const *D) { // C++ Modules TS [basic.link]/6.8: // - A name declared at namespace scope that does not have internal linkage // by the previous rules and that is introduced by a non-exported @@ -611,7 +610,7 @@ return LinkageInfo::external(); } -static StorageClass getStorageClass(const Decl *D) { +static StorageClass getStorageClass(Decl const *D) { if (auto *TD = dyn_cast(D)) D = TD->getTemplatedDecl(); if (D) { @@ -624,7 +623,7 @@ } LinkageInfo -LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D, +LinkageComputer::getLVForNamespaceScopeDecl(NamedDecl const *D, LVComputationKind computation, bool IgnoreVarTypeLinkage) { assert(D->getDeclContext()->getRedeclContext()->isFileContext() && @@ -642,21 +641,19 @@ return getInternalLinkageFor(D); } - if (const auto *Var = dyn_cast(D)) { + if (auto const *Var = dyn_cast(D)) { // - a non-template variable of non-volatile const-qualified type, unless // - it is explicitly declared extern, or // - it is inline or exported, or // - it was previously declared and the prior declaration did not have // internal linkage // (There is no equivalent in C99.) - if (Context.getLangOpts().CPlusPlus && - Var->getType().isConstQualified() && - !Var->getType().isVolatileQualified() && - !Var->isInline() && + if (Context.getLangOpts().CPlusPlus && Var->getType().isConstQualified() && + !Var->getType().isVolatileQualified() && !Var->isInline() && !isExportedFromModuleInterfaceUnit(Var) && !isa(Var) && !Var->getDescribedVarTemplate()) { - const VarDecl *PrevVar = Var->getPreviousDecl(); + VarDecl const *PrevVar = Var->getPreviousDecl(); if (PrevVar) return getLVForDecl(PrevVar, computation); @@ -666,7 +663,7 @@ return getInternalLinkageFor(Var); } - for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar; + for (VarDecl const *PrevVar = Var->getPreviousDecl(); PrevVar; PrevVar = PrevVar->getPreviousDecl()) { if (PrevVar->getStorageClass() == SC_PrivateExtern && Var->getStorageClass() == SC_None) @@ -675,9 +672,9 @@ if (PrevVar->getStorageClass() == SC_Static) return getInternalLinkageFor(Var); } - } else if (const auto *IFD = dyn_cast(D)) { + } else if (auto const *IFD = dyn_cast(D)) { // - a data member of an anonymous union. - const VarDecl *VD = IFD->getVarDecl(); + VarDecl const *VD = IFD->getVarDecl(); assert(VD && "Expected a VarDecl in this IndirectFieldDecl!"); return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage); } @@ -686,8 +683,8 @@ // FIXME: This gives internal linkage to names that should have no linkage // (those not covered by [basic.link]p6). if (D->isInAnonymousNamespace()) { - const auto *Var = dyn_cast(D); - const auto *Func = dyn_cast(D); + auto const *Var = dyn_cast(D); + auto const *Func = dyn_cast(D); // FIXME: The check for extern "C" here is not justified by the standard // wording, but we retain it from the pre-DR1113 model to avoid breaking // code. @@ -714,11 +711,11 @@ } else { // If we're declared in a namespace with a visibility attribute, // use that namespace's visibility, and it still counts as explicit. - for (const DeclContext *DC = D->getDeclContext(); - !isa(DC); - DC = DC->getParent()) { - const auto *ND = dyn_cast(DC); - if (!ND) continue; + for (DeclContext const *DC = D->getDeclContext(); + !isa(DC); DC = DC->getParent()) { + auto const *ND = dyn_cast(DC); + if (!ND) + continue; if (Optional Vis = getExplicitVisibility(ND, computation)) { LV.mergeVisibility(*Vis, true); break; @@ -758,7 +755,7 @@ // The bullets are: // - a variable; or - if (const auto *Var = dyn_cast(D)) { + if (auto const *Var = dyn_cast(D)) { // GCC applies the following optimization to variables and static // data members, but not to functions: // @@ -799,12 +796,12 @@ // As per function and class template specializations (below), // consider LV for the template and template arguments. We're at file // scope, so we do not need to worry about nested specializations. - if (const auto *spec = dyn_cast(Var)) { + if (auto const *spec = dyn_cast(Var)) { mergeTemplateLV(LV, spec, computation); } - // - a function; or - } else if (const auto *Function = dyn_cast(D)) { + // - a function; or + } else if (auto const *Function = dyn_cast(D)) { // In theory, we can modify the function's LV by the LV of its // type unless it has C linkage (see comment above about variables // for justification). In practice, GCC doesn't do this, so it's @@ -834,18 +831,18 @@ // Consider LV from the template and the template arguments. // We're at file scope, so we do not need to worry about nested // specializations. - if (FunctionTemplateSpecializationInfo *specInfo - = Function->getTemplateSpecializationInfo()) { + if (FunctionTemplateSpecializationInfo *specInfo = + Function->getTemplateSpecializationInfo()) { mergeTemplateLV(LV, Function, specInfo, computation); } - // - a named class (Clause 9), or an unnamed class defined in a - // typedef declaration in which the class has the typedef name - // for linkage purposes (7.1.3); or - // - a named enumeration (7.2), or an unnamed enumeration - // defined in a typedef declaration in which the enumeration - // has the typedef name for linkage purposes (7.1.3); or - } else if (const auto *Tag = dyn_cast(D)) { + // - a named class (Clause 9), or an unnamed class defined in a + // typedef declaration in which the class has the typedef name + // for linkage purposes (7.1.3); or + // - a named enumeration (7.2), or an unnamed enumeration + // defined in a typedef declaration in which the enumeration + // has the typedef name for linkage purposes (7.1.3); or + } else if (auto const *Tag = dyn_cast(D)) { // Unnamed tags have no linkage. if (!Tag->hasNameForLinkage()) return LinkageInfo::none(); @@ -853,50 +850,50 @@ // If this is a class template specialization, consider the // linkage of the template and template arguments. We're at file // scope, so we do not need to worry about nested specializations. - if (const auto *spec = dyn_cast(Tag)) { + if (auto const *spec = dyn_cast(Tag)) { mergeTemplateLV(LV, spec, computation); } - // FIXME: This is not part of the C++ standard any more. - // - an enumerator belonging to an enumeration with external linkage; or + // FIXME: This is not part of the C++ standard any more. + // - an enumerator belonging to an enumeration with external linkage; or } else if (isa(D)) { - LinkageInfo EnumLV = getLVForDecl(cast(D->getDeclContext()), - computation); + LinkageInfo EnumLV = + getLVForDecl(cast(D->getDeclContext()), computation); if (!isExternalFormalLinkage(EnumLV.getLinkage())) return LinkageInfo::none(); LV.merge(EnumLV); - // - a template - } else if (const auto *temp = dyn_cast(D)) { + // - a template + } else if (auto const *temp = dyn_cast(D)) { bool considerVisibility = !hasExplicitVisibilityAlready(computation); - LinkageInfo tempLV = - getLVForTemplateParameterList(temp->getTemplateParameters(), computation); + LinkageInfo tempLV = getLVForTemplateParameterList( + temp->getTemplateParameters(), computation); LV.mergeMaybeWithVisibility(tempLV, considerVisibility); - // An unnamed namespace or a namespace declared directly or indirectly - // within an unnamed namespace has internal linkage. All other namespaces - // have external linkage. - // - // We handled names in anonymous namespaces above. + // An unnamed namespace or a namespace declared directly or indirectly + // within an unnamed namespace has internal linkage. All other + // namespaces have external linkage. + // + // We handled names in anonymous namespaces above. } else if (isa(D)) { return LV; - // By extension, we assign external linkage to Objective-C - // interfaces. + // By extension, we assign external linkage to Objective-C + // interfaces. } else if (isa(D)) { // fallout } else if (auto *TD = dyn_cast(D)) { // A typedef declaration has linkage if it gives a type a name for // linkage purposes. - if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) + if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/ true)) return LinkageInfo::none(); } else if (isa(D)) { // A GUID behaves like an inline variable with external linkage. Fall // through. - // Everything not covered here has no linkage. + // Everything not covered here has no linkage. } else { return LinkageInfo::none(); } @@ -913,10 +910,9 @@ return LV; } -LinkageInfo -LinkageComputer::getLVForClassMember(const NamedDecl *D, - LVComputationKind computation, - bool IgnoreVarTypeLinkage) { +LinkageInfo LinkageComputer::getLVForClassMember(NamedDecl const *D, + LVComputationKind computation, + bool IgnoreVarTypeLinkage) { // Only certain class members have linkage. Note that fields don't // really have linkage, but it's convenient to say they do for the // purposes of calculating linkage of pointer-to-data-member @@ -927,12 +923,8 @@ // linkage and visibility of a template specialization, we might hit // a template template argument that way. If we do, we need to // consider its linkage. - if (!(isa(D) || - isa(D) || - isa(D) || - isa(D) || - isa(D) || - isa(D))) + if (!(isa(D) || isa(D) || isa(D) || + isa(D) || isa(D) || isa(D))) return LinkageInfo::none(); LinkageInfo LV; @@ -958,21 +950,20 @@ classComputation = withExplicitVisibilityAlready(computation); LinkageInfo classLV = - getLVForDecl(cast(D->getDeclContext()), classComputation); + getLVForDecl(cast(D->getDeclContext()), classComputation); // The member has the same linkage as the class. If that's not externally // visible, we don't need to compute anything about the linkage. // FIXME: If we're only computing linkage, can we bail out here? if (!isExternallyVisible(classLV.getLinkage())) return classLV; - // Otherwise, don't merge in classLV yet, because in certain cases // we need to completely ignore the visibility from it. // Specifically, if this decl exists and has an explicit attribute. - const NamedDecl *explicitSpecSuppressor = nullptr; + NamedDecl const *explicitSpecSuppressor = nullptr; - if (const auto *MD = dyn_cast(D)) { + if (auto const *MD = dyn_cast(D)) { // Only look at the type-as-written. Otherwise, deducing the return type // of a function could change its linkage. QualType TypeAsWritten = MD->getType(); @@ -983,8 +974,8 @@ // If this is a method template specialization, use the linkage for // the template parameters and arguments. - if (FunctionTemplateSpecializationInfo *spec - = MD->getTemplateSpecializationInfo()) { + if (FunctionTemplateSpecializationInfo *spec = + MD->getTemplateSpecializationInfo()) { mergeTemplateLV(LV, MD, spec, computation); if (spec->isExplicitSpecialization()) { explicitSpecSuppressor = MD; @@ -995,13 +986,13 @@ explicitSpecSuppressor = MD; } - } else if (const auto *RD = dyn_cast(D)) { - if (const auto *spec = dyn_cast(RD)) { + } else if (auto const *RD = dyn_cast(D)) { + if (auto const *spec = dyn_cast(RD)) { mergeTemplateLV(LV, spec, computation); if (spec->isExplicitSpecialization()) { explicitSpecSuppressor = spec; } else { - const ClassTemplateDecl *temp = spec->getSpecializedTemplate(); + ClassTemplateDecl const *temp = spec->getSpecializedTemplate(); if (isExplicitMemberSpecialization(temp)) { explicitSpecSuppressor = temp->getTemplatedDecl(); } @@ -1010,9 +1001,9 @@ explicitSpecSuppressor = RD; } - // Static data members. - } else if (const auto *VD = dyn_cast(D)) { - if (const auto *spec = dyn_cast(VD)) + // Static data members. + } else if (auto const *VD = dyn_cast(D)) { + if (auto const *spec = dyn_cast(VD)) mergeTemplateLV(LV, spec, computation); // Modify the variable's linkage by its type, but ignore the @@ -1030,17 +1021,16 @@ explicitSpecSuppressor = VD; } - // Template members. - } else if (const auto *temp = dyn_cast(D)) { + // Template members. + } else if (auto const *temp = dyn_cast(D)) { bool considerVisibility = - (!LV.isVisibilityExplicit() && - !classLV.isVisibilityExplicit() && - !hasExplicitVisibilityAlready(computation)); - LinkageInfo tempLV = - getLVForTemplateParameterList(temp->getTemplateParameters(), computation); + (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit() && + !hasExplicitVisibilityAlready(computation)); + LinkageInfo tempLV = getLVForTemplateParameterList( + temp->getTemplateParameters(), computation); LV.mergeMaybeWithVisibility(tempLV, considerVisibility); - if (const auto *redeclTemp = dyn_cast(temp)) { + if (auto const *redeclTemp = dyn_cast(temp)) { if (isExplicitMemberSpecialization(redeclTemp)) { explicitSpecSuppressor = temp->getTemplatedDecl(); } @@ -1079,8 +1069,8 @@ } ReservedIdentifierStatus -NamedDecl::isReserved(const LangOptions &LangOpts) const { - const IdentifierInfo *II = getIdentifier(); +NamedDecl::isReserved(LangOptions const &LangOpts) const { + IdentifierInfo const *II = getIdentifier(); // This triggers at least for CXXLiteralIdentifiers, which we already checked // at lexing time. @@ -1092,7 +1082,7 @@ // Check if we're at TU level or not. if (isa(this) || isTemplateParameter()) return ReservedIdentifierStatus::NotReserved; - const DeclContext *DC = getDeclContext()->getRedeclContext(); + DeclContext const *DC = getDeclContext()->getRedeclContext(); if (!DC->isTranslationUnit()) return ReservedIdentifierStatus::NotReserved; } @@ -1102,7 +1092,8 @@ ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const { StringRef name = getName(); - if (name.empty()) return SFF_None; + if (name.empty()) + return SFF_None; if (name.front() == 'C') if (name == "CFStringCreateWithFormat" || @@ -1126,7 +1117,7 @@ } static Optional -getExplicitVisibilityAux(const NamedDecl *ND, +getExplicitVisibilityAux(NamedDecl const *ND, NamedDecl::ExplicitVisibilityKind kind, bool IsMostRecent) { assert(!IsMostRecent || ND == ND->getMostRecentDecl()); @@ -1137,7 +1128,7 @@ // If this is a member class of a specialization of a class template // and the corresponding decl has explicit visibility, use that. - if (const auto *RD = dyn_cast(ND)) { + if (auto const *RD = dyn_cast(ND)) { CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass(); if (InstantiatedFrom) return getVisibilityOf(InstantiatedFrom, kind); @@ -1146,10 +1137,10 @@ // If there wasn't explicit visibility there, and this is a // specialization of a class template, check for visibility // on the pattern. - if (const auto *spec = dyn_cast(ND)) { + if (auto const *spec = dyn_cast(ND)) { // Walk all the template decl till this point to see if there are // explicit visibility attributes. - const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl(); + auto const *TD = spec->getSpecializedTemplate()->getTemplatedDecl(); while (TD != nullptr) { auto Vis = getVisibilityOf(TD, kind); if (Vis != None) @@ -1161,30 +1152,30 @@ // Use the most recent declaration. if (!IsMostRecent && !isa(ND)) { - const NamedDecl *MostRecent = ND->getMostRecentDecl(); + NamedDecl const *MostRecent = ND->getMostRecentDecl(); if (MostRecent != ND) return getExplicitVisibilityAux(MostRecent, kind, true); } - if (const auto *Var = dyn_cast(ND)) { + if (auto const *Var = dyn_cast(ND)) { if (Var->isStaticDataMember()) { VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember(); if (InstantiatedFrom) return getVisibilityOf(InstantiatedFrom, kind); } - if (const auto *VTSD = dyn_cast(Var)) + if (auto const *VTSD = dyn_cast(Var)) return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(), kind); return None; } // Also handle function template specializations. - if (const auto *fn = dyn_cast(ND)) { + if (auto const *fn = dyn_cast(ND)) { // If the function is a specialization of a template with an // explicit visibility attribute, use that. - if (FunctionTemplateSpecializationInfo *templateInfo - = fn->getTemplateSpecializationInfo()) + if (FunctionTemplateSpecializationInfo *templateInfo = + fn->getTemplateSpecializationInfo()) return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(), kind); @@ -1198,7 +1189,7 @@ } // The visibility of a template is stored in the templated decl. - if (const auto *TD = dyn_cast(ND)) + if (auto const *TD = dyn_cast(ND)) return getVisibilityOf(TD->getTemplatedDecl(), kind); return None; @@ -1209,11 +1200,11 @@ return getExplicitVisibilityAux(this, kind, false); } -LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC, +LinkageInfo LinkageComputer::getLVForClosure(DeclContext const *DC, Decl *ContextDecl, LVComputationKind computation) { // This lambda has its linkage/visibility determined by its owner. - const NamedDecl *Owner; + NamedDecl const *Owner; if (!ContextDecl) Owner = dyn_cast(DC); else if (isa(ContextDecl)) @@ -1232,7 +1223,7 @@ auto *VD = dyn_cast(Owner); LinkageInfo OwnerLV = VD && VD->getType()->getContainedDeducedType() - ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true) + ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/ true) : getLVForDecl(Owner, computation); // A lambda never formally has linkage. But if the owner is externally @@ -1243,9 +1234,9 @@ OwnerLV.isVisibilityExplicit()); } -LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D, +LinkageInfo LinkageComputer::getLVForLocalDecl(NamedDecl const *D, LVComputationKind computation) { - if (const auto *Function = dyn_cast(D)) { + if (auto const *Function = dyn_cast(D)) { if (Function->isInAnonymousNamespace() && !isFirstInExternCContext(Function)) return getInternalLinkageFor(Function); @@ -1268,7 +1259,7 @@ return LV; } - if (const auto *Var = dyn_cast(D)) { + if (auto const *Var = dyn_cast(D)) { if (Var->hasExternalStorage()) { if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var)) return getInternalLinkageFor(Var); @@ -1281,7 +1272,7 @@ LV.mergeVisibility(*Vis, true); } - if (const VarDecl *Prev = Var->getPreviousDecl()) { + if (VarDecl const *Prev = Var->getPreviousDecl()) { LinkageInfo PrevLV = getLVForDecl(Prev, computation); if (PrevLV.getLinkage()) LV.setLinkage(PrevLV.getLinkage()); @@ -1299,19 +1290,19 @@ if (!Context.getLangOpts().CPlusPlus) return LinkageInfo::none(); - const Decl *OuterD = getOutermostFuncOrBlockContext(D); + Decl const *OuterD = getOutermostFuncOrBlockContext(D); if (!OuterD || OuterD->isInvalidDecl()) return LinkageInfo::none(); LinkageInfo LV; - if (const auto *BD = dyn_cast(OuterD)) { + if (auto const *BD = dyn_cast(OuterD)) { if (!BD->getBlockManglingNumber()) return LinkageInfo::none(); LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(), BD->getBlockManglingContextDecl(), computation); } else { - const auto *FD = cast(OuterD); + auto const *FD = cast(OuterD); if (!FD->isInlined() && !isTemplateInstantiation(FD->getTemplateSpecializationKind())) return LinkageInfo::none(); @@ -1327,7 +1318,7 @@ // If this was an implicitly hidden inline method, check again for // explicit visibility on the parent class, and use that for static locals // if present. - if (const auto *MD = dyn_cast(FD)) + if (auto const *MD = dyn_cast(FD)) LV = getLVForDecl(MD->getParent(), computation); if (!LV.isVisibilityExplicit()) { Visibility globalVisibility = @@ -1345,7 +1336,7 @@ LV.isVisibilityExplicit()); } -LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D, +LinkageInfo LinkageComputer::computeLVForDecl(NamedDecl const *D, LVComputationKind computation, bool IgnoreVarTypeLinkage) { // Internal_linkage attribute overrides other considerations. @@ -1355,78 +1346,77 @@ // Objective-C: treat all Objective-C declarations as having external // linkage. switch (D->getKind()) { - default: - break; + default: + break; - // Per C++ [basic.link]p2, only the names of objects, references, - // functions, types, templates, namespaces, and values ever have linkage. - // - // Note that the name of a typedef, namespace alias, using declaration, - // and so on are not the name of the corresponding type, namespace, or - // declaration, so they do *not* have linkage. - case Decl::ImplicitParam: - case Decl::Label: - case Decl::NamespaceAlias: - case Decl::ParmVar: - case Decl::Using: - case Decl::UsingEnum: - case Decl::UsingShadow: - case Decl::UsingDirective: - return LinkageInfo::none(); + // Per C++ [basic.link]p2, only the names of objects, references, + // functions, types, templates, namespaces, and values ever have linkage. + // + // Note that the name of a typedef, namespace alias, using declaration, + // and so on are not the name of the corresponding type, namespace, or + // declaration, so they do *not* have linkage. + case Decl::ImplicitParam: + case Decl::Label: + case Decl::NamespaceAlias: + case Decl::ParmVar: + case Decl::Using: + case Decl::UsingEnum: + case Decl::UsingShadow: + case Decl::UsingDirective: + return LinkageInfo::none(); - case Decl::EnumConstant: - // C++ [basic.link]p4: an enumerator has the linkage of its enumeration. - if (D->getASTContext().getLangOpts().CPlusPlus) - return getLVForDecl(cast(D->getDeclContext()), computation); - return LinkageInfo::visible_none(); - - case Decl::Typedef: - case Decl::TypeAlias: - // A typedef declaration has linkage if it gives a type a name for - // linkage purposes. - if (!cast(D) - ->getAnonDeclWithTypedefName(/*AnyRedecl*/true)) - return LinkageInfo::none(); - break; + case Decl::EnumConstant: + // C++ [basic.link]p4: an enumerator has the linkage of its enumeration. + if (D->getASTContext().getLangOpts().CPlusPlus) + return getLVForDecl(cast(D->getDeclContext()), computation); + return LinkageInfo::visible_none(); - case Decl::TemplateTemplateParm: // count these as external - case Decl::NonTypeTemplateParm: - case Decl::ObjCAtDefsField: - case Decl::ObjCCategory: - case Decl::ObjCCategoryImpl: - case Decl::ObjCCompatibleAlias: - case Decl::ObjCImplementation: - case Decl::ObjCMethod: - case Decl::ObjCProperty: - case Decl::ObjCPropertyImpl: - case Decl::ObjCProtocol: - return getExternalLinkageFor(D); - - case Decl::CXXRecord: { - const auto *Record = cast(D); - if (Record->isLambda()) { - if (Record->hasKnownLambdaInternalLinkage() || - !Record->getLambdaManglingNumber()) { - // This lambda has no mangling number, so it's internal. - return getInternalLinkageFor(D); - } + case Decl::Typedef: + case Decl::TypeAlias: + // A typedef declaration has linkage if it gives a type a name for + // linkage purposes. + if (!cast(D)->getAnonDeclWithTypedefName( + /*AnyRedecl*/ true)) + return LinkageInfo::none(); + break; - return getLVForClosure( - Record->getDeclContext()->getRedeclContext(), - Record->getLambdaContextDecl(), computation); + case Decl::TemplateTemplateParm: // count these as external + case Decl::NonTypeTemplateParm: + case Decl::ObjCAtDefsField: + case Decl::ObjCCategory: + case Decl::ObjCCategoryImpl: + case Decl::ObjCCompatibleAlias: + case Decl::ObjCImplementation: + case Decl::ObjCMethod: + case Decl::ObjCProperty: + case Decl::ObjCPropertyImpl: + case Decl::ObjCProtocol: + return getExternalLinkageFor(D); + + case Decl::CXXRecord: { + auto const *Record = cast(D); + if (Record->isLambda()) { + if (Record->hasKnownLambdaInternalLinkage() || + !Record->getLambdaManglingNumber()) { + // This lambda has no mangling number, so it's internal. + return getInternalLinkageFor(D); } - break; + return getLVForClosure(Record->getDeclContext()->getRedeclContext(), + Record->getLambdaContextDecl(), computation); } - case Decl::TemplateParamObject: { - // The template parameter object can be referenced from anywhere its type - // and value can be referenced. - auto *TPO = cast(D); - LinkageInfo LV = getLVForType(*TPO->getType(), computation); - LV.merge(getLVForValue(TPO->getValue(), computation)); - return LV; - } + break; + } + + case Decl::TemplateParamObject: { + // The template parameter object can be referenced from anywhere its type + // and value can be referenced. + auto *TPO = cast(D); + LinkageInfo LV = getLVForType(*TPO->getType(), computation); + LV.merge(getLVForValue(TPO->getValue(), computation)); + return LV; + } } // Handle linkage for namespace-scope names. @@ -1463,7 +1453,7 @@ } /// getLVForDecl - Get the linkage and visibility for the given declaration. -LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D, +LinkageInfo LinkageComputer::getLVForDecl(NamedDecl const *D, LVComputationKind computation) { // Internal_linkage attribute overrides other considerations. if (D->hasAttr()) @@ -1486,7 +1476,7 @@ // In C (because of gnu inline) and in c++ with microsoft extensions an // static can follow an extern, so we can have two decls with different // linkages. - const LangOptions &Opts = D->getASTContext().getLangOpts(); + LangOptions const &Opts = D->getASTContext().getLangOpts(); if (!Opts.CPlusPlus || Opts.MicrosoftExt) return LV; @@ -1509,7 +1499,7 @@ return LV; } -LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) { +LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(NamedDecl const *D) { NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D) ? NamedDecl::VisibilityForType : NamedDecl::VisibilityForValue; @@ -1544,8 +1534,8 @@ InternalLinkage = !ND->hasExternalFormalLinkage(); else { auto *NSD = dyn_cast(this); - InternalLinkage = (NSD && NSD->isAnonymousNamespace()) || - isInAnonymousNamespace(); + InternalLinkage = + (NSD && NSD->isAnonymousNamespace()) || isInAnonymousNamespace(); } return InternalLinkage ? M->Parent : nullptr; } @@ -1559,9 +1549,7 @@ llvm_unreachable("unknown module kind"); } -void NamedDecl::printName(raw_ostream &os) const { - os << Name; -} +void NamedDecl::printName(raw_ostream &os) const { os << Name; } std::string NamedDecl::getQualifiedNameAsString() const { std::string QualName; @@ -1575,7 +1563,7 @@ } void NamedDecl::printQualifiedName(raw_ostream &OS, - const PrintingPolicy &P) const { + PrintingPolicy const &P) const { if (getDeclContext()->isFunctionOrMethod()) { // We do not print '(anonymous)' for function parameters without name. printName(OS); @@ -1602,8 +1590,8 @@ } void NamedDecl::printNestedNameSpecifier(raw_ostream &OS, - const PrintingPolicy &P) const { - const DeclContext *Ctx = getDeclContext(); + PrintingPolicy const &P) const { + DeclContext const *Ctx = getDeclContext(); // For ObjC methods and properties, look through categories and use the // interface as context. @@ -1622,7 +1610,7 @@ if (Ctx->isFunctionOrMethod()) return; - using ContextsTy = SmallVector; + using ContextsTy = SmallVector; ContextsTy Contexts; // Collect named contexts. @@ -1639,7 +1627,7 @@ continue; // Skip non-named contexts such as linkage specifications and ExportDecls. - const NamedDecl *ND = dyn_cast(Ctx); + NamedDecl const *ND = dyn_cast(Ctx); if (!ND) continue; @@ -1648,27 +1636,26 @@ } for (unsigned I = Contexts.size(); I != 0; --I) { - const DeclContext *DC = Contexts[I - 1]; - if (const auto *Spec = dyn_cast(DC)) { + DeclContext const *DC = Contexts[I - 1]; + if (auto const *Spec = dyn_cast(DC)) { OS << Spec->getName(); - const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); + TemplateArgumentList const &TemplateArgs = Spec->getTemplateArgs(); printTemplateArgumentList( OS, TemplateArgs.asArray(), P, Spec->getSpecializedTemplate()->getTemplateParameters()); - } else if (const auto *ND = dyn_cast(DC)) { + } else if (auto const *ND = dyn_cast(DC)) { if (ND->isAnonymousNamespace()) { OS << (P.MSVCFormatting ? "`anonymous namespace\'" : "(anonymous namespace)"); - } - else + } else OS << *ND; - } else if (const auto *RD = dyn_cast(DC)) { + } else if (auto const *RD = dyn_cast(DC)) { if (!RD->getIdentifier()) OS << "(anonymous " << RD->getKindName() << ')'; else OS << *RD; - } else if (const auto *FD = dyn_cast(DC)) { - const FunctionProtoType *FT = nullptr; + } else if (auto const *FD = dyn_cast(DC)) { + FunctionProtoType const *FT = nullptr; if (FD->hasWrittenPrototype()) FT = dyn_cast(FD->getType()->castAs()); @@ -1688,7 +1675,7 @@ } } OS << ')'; - } else if (const auto *ED = dyn_cast(DC)) { + } else if (auto const *ED = dyn_cast(DC)) { // C++ [dcl.enum]p10: Each enum-name and each unscoped // enumerator is declared in the scope that immediately contains // the enum-specifier. Each scoped enumerator is declared in the @@ -1708,7 +1695,7 @@ } void NamedDecl::getNameForDiagnostic(raw_ostream &OS, - const PrintingPolicy &Policy, + PrintingPolicy const &Policy, bool Qualified) const { if (Qualified) printQualifiedName(OS, Policy); @@ -1716,14 +1703,14 @@ printName(OS); } -template static bool isRedeclarableImpl(Redeclarable *) { +template static bool isRedeclarableImpl(Redeclarable *) { return true; } static bool isRedeclarableImpl(...) { return false; } static bool isRedeclarable(Decl::Kind K) { switch (K) { -#define DECL(Type, Base) \ - case Decl::Type: \ +#define DECL(Type, Base) \ + case Decl::Type: \ return isRedeclarableImpl((Type##Decl *)nullptr); #define ABSTRACT_DECL(DECL) #include "clang/AST/DeclNodes.inc" @@ -1771,7 +1758,7 @@ ASTContext &Context = getASTContext(); return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) == Context.getCanonicalNestedNameSpecifier( - cast(OldD)->getQualifier()); + cast(OldD)->getQualifier()); } if (isRedeclarable(getKind())) { @@ -1807,9 +1794,7 @@ return false; } -bool NamedDecl::hasLinkage() const { - return getFormalLinkage() != NoLinkage; -} +bool NamedDecl::hasLinkage() const { return getFormalLinkage() != NoLinkage; } NamedDecl *NamedDecl::getUnderlyingDeclImpl() { NamedDecl *ND = this; @@ -1829,13 +1814,13 @@ if (!isCXXClassMember()) return false; - const NamedDecl *D = this; + NamedDecl const *D = this; if (isa(D)) D = cast(D)->getTargetDecl(); if (isa(D) || isa(D) || isa(D)) return true; - if (const auto *MD = dyn_cast_or_null(D->getAsFunction())) + if (auto const *MD = dyn_cast_or_null(D->getAsFunction())) return MD->isInstance(); return false; } @@ -1845,7 +1830,7 @@ //===----------------------------------------------------------------------===// template -static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { +static SourceLocation getTemplateOrInnerLocStart(DeclT const *decl) { if (decl->getNumTemplateParameterLists() > 0) return decl->getTemplateParameterList(0)->getTemplateLoc(); return decl->getInnerLocStart(); @@ -1853,13 +1838,15 @@ SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { TypeSourceInfo *TSI = getTypeSourceInfo(); - if (TSI) return TSI->getTypeLoc().getBeginLoc(); + if (TSI) + return TSI->getTypeLoc().getBeginLoc(); return SourceLocation(); } SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const { TypeSourceInfo *TSI = getTypeSourceInfo(); - if (TSI) return TSI->getTypeLoc().getEndLoc(); + if (TSI) + return TSI->getTypeLoc().getEndLoc(); return SourceLocation(); } @@ -1868,7 +1855,7 @@ // Make sure the extended decl info is allocated. if (!hasExtInfo()) { // Save (non-extended) type source info pointer. - auto *savedTInfo = DeclInfo.get(); + auto *savedTInfo = DeclInfo.get(); // Allocate external info struct. DeclInfo = new (getASTContext()) ExtInfo; // Restore savedTInfo into (extended) decl info. @@ -1887,7 +1874,7 @@ // Make sure the extended decl info is allocated. if (!hasExtInfo()) { // Save (non-extended) type source info pointer. - auto *savedTInfo = DeclInfo.get(); + auto *savedTInfo = DeclInfo.get(); // Allocate external info struct. DeclInfo = new (getASTContext()) ExtInfo; // Restore savedTInfo into (extended) decl info. @@ -1903,7 +1890,7 @@ // Make sure the extended decl info is allocated. if (!hasExtInfo()) { // Save (non-extended) type source info pointer. - auto *savedTInfo = DeclInfo.get(); + auto *savedTInfo = DeclInfo.get(); // Allocate external info struct. DeclInfo = new (getASTContext()) ExtInfo; // Restore savedTInfo into (extended) decl info. @@ -1921,7 +1908,7 @@ // having a postfix component. static bool typeIsPostfix(QualType QT) { while (true) { - const Type* T = QT.getTypePtr(); + Type const *T = QT.getTypePtr(); switch (T->getTypeClass()) { default: return false; @@ -1984,14 +1971,20 @@ // VarDecl Implementation //===----------------------------------------------------------------------===// -const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { +char const *VarDecl::getStorageClassSpecifierString(StorageClass SC) { switch (SC) { - case SC_None: break; - case SC_Auto: return "auto"; - case SC_Extern: return "extern"; - case SC_PrivateExtern: return "__private_extern__"; - case SC_Register: return "register"; - case SC_Static: return "static"; + case SC_None: + break; + case SC_Auto: + return "auto"; + case SC_Extern: + return "extern"; + case SC_PrivateExtern: + return "__private_extern__"; + case SC_Register: + return "register"; + case SC_Static: + return "static"; } llvm_unreachable("Invalid storage class"); @@ -2014,10 +2007,9 @@ // Everything else is implicitly initialized to false. } -VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation StartL, SourceLocation IdL, - IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, - StorageClass S) { +VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL, + SourceLocation IdL, IdentifierInfo *Id, QualType T, + TypeSourceInfo *TInfo, StorageClass S) { return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S); } @@ -2055,7 +2047,7 @@ } SourceRange VarDecl::getSourceRange() const { - if (const Expr *Init = getInit()) { + if (Expr const *Init = getInit()) { SourceLocation InitEnd = Init->getEndLoc(); // If Init is implicit, ignore its source range and fallback on // DeclaratorDecl::getSourceRange() to handle postfix elements. @@ -2065,7 +2057,7 @@ return DeclaratorDecl::getSourceRange(); } -template +template static LanguageLinkage getDeclLanguageLinkage(const T &D) { // C++ [dcl.link]p1: All function types, function names with external linkage, // and variable names with external linkage have a language linkage. @@ -2081,7 +2073,7 @@ // C++ [dcl.link]p4: A C language linkage is ignored in determining the // language linkage of the names of class members and the function type of // class member functions. - const DeclContext *DC = D.getDeclContext(); + DeclContext const *DC = D.getDeclContext(); if (DC->isRecord()) return CXXLanguageLinkage; @@ -2093,11 +2085,10 @@ return CXXLanguageLinkage; } -template -static bool isDeclExternC(const T &D) { +template static bool isDeclExternC(const T &D) { // Since the context is ignored for class members, they can only have C++ // language linkage or no language linkage. - const DeclContext *DC = D.getDeclContext(); + DeclContext const *DC = D.getDeclContext(); if (DC->isRecord()) { assert(D.getASTContext().getLangOpts().CPlusPlus); return false; @@ -2110,9 +2101,7 @@ return getDeclLanguageLinkage(*this); } -bool VarDecl::isExternC() const { - return isDeclExternC(*this); -} +bool VarDecl::isExternC() const { return isDeclExternC(*this); } bool VarDecl::isInExternCContext() const { return getLexicalDeclContext()->isExternCContext(); @@ -2133,8 +2122,8 @@ // A declaration is a definition unless [...] it contains the 'extern' // specifier or a linkage-specification and neither an initializer [...], // it declares a non-inline static data member in a class declaration [...], - // it declares a static data member outside a class definition and the variable - // was defined within the class with the constexpr specifier [...], + // it declares a static data member outside a class definition and the + // variable was defined within the class with the constexpr specifier [...], // C++1y [temp.expl.spec]p15: // An explicit specialization of a static data member or an explicit // specialization of a static data member template is a definition if the @@ -2173,7 +2162,7 @@ if (hasDefiningAttr()) return Definition; - if (const auto *SAA = getAttr()) + if (auto const *SAA = getAttr()) if (!SAA->isInherited()) return Definition; @@ -2243,7 +2232,7 @@ VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { DefinitionKind Kind = DeclarationOnly; - const VarDecl *First = getFirstDecl(); + VarDecl const *First = getFirstDecl(); for (auto I : First->redecls()) { Kind = std::max(Kind, I->isThisDeclarationADefinition(C)); if (Kind == Definition) @@ -2253,7 +2242,7 @@ return Kind; } -const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { +Expr const *VarDecl::getAnyInitializer(VarDecl const *&D) const { for (auto I : redecls()) { if (auto Expr = I->getInit()) { D = I; @@ -2328,8 +2317,8 @@ Init = I; } -bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const { - const LangOptions &Lang = C.getLangOpts(); +bool VarDecl::mightBeUsableInConstantExpressions(ASTContext const &C) const { + LangOptions const &Lang = C.getLangOpts(); // OpenCL permits const integral variables to be used in constant // expressions, like in C++98. @@ -2365,12 +2354,12 @@ return Lang.CPlusPlus11 && isConstexpr(); } -bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const { +bool VarDecl::isUsableInConstantExpressions(ASTContext const &Context) const { // C++2a [expr.const]p3: // A variable is usable in constant expressions after its initializing // declaration is encountered... - const VarDecl *DefVD = nullptr; - const Expr *Init = getAnyInitializer(DefVD); + VarDecl const *DefVD = nullptr; + Expr const *Init = getAnyInitializer(DefVD); if (!Init || Init->isValueDependent() || getType()->isDependentType()) return false; // ... if it is a constexpr variable, or it is of reference type or of @@ -2420,7 +2409,7 @@ bool IsConstantInitialization) const { EvaluatedStmt *Eval = ensureEvaluatedStmt(); - const auto *Init = cast(Eval->Value); + auto const *Init = cast(Eval->Value); assert(!Init->isValueDependent()); // We only produce notes indicating why an initializer is non-constant the @@ -2469,8 +2458,8 @@ return nullptr; } -bool VarDecl::hasICEInitializer(const ASTContext &Context) const { - const Expr *Init = getInit(); +bool VarDecl::hasICEInitializer(ASTContext const &Context) const { + Expr const *Init = getInit(); assert(Init && "no initializer"); EvaluatedStmt *Eval = ensureEvaluatedStmt(); @@ -2522,8 +2511,7 @@ return isa(getType()); } -template -static DeclT *getDefinitionOrSelf(DeclT *D) { +template static DeclT *getDefinitionOrSelf(DeclT *D) { assert(D); if (auto *Def = D->getDefinition()) return Def; @@ -2541,13 +2529,13 @@ bool VarDecl::hasDependentAlignment() const { QualType T = getType(); return T->isDependentType() || T->isUndeducedAutoType() || - llvm::any_of(specific_attrs(), [](const AlignedAttr *AA) { + llvm::any_of(specific_attrs(), [](AlignedAttr const *AA) { return AA->isAlignmentDependent(); }); } VarDecl *VarDecl::getTemplateInstantiationPattern() const { - const VarDecl *VD = this; + VarDecl const *VD = this; // If this is an instantiated member, walk back to the template from which // it was instantiated. @@ -2601,7 +2589,7 @@ if (VD == this) return nullptr; - return getDefinitionOrSelf(const_cast(VD)); + return getDefinitionOrSelf(const_cast(VD)); } VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { @@ -2612,7 +2600,7 @@ } TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { - if (const auto *Spec = dyn_cast(this)) + if (auto const *Spec = dyn_cast(this)) return Spec->getSpecializationKind(); if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) @@ -2626,14 +2614,14 @@ if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) return MSI->getTemplateSpecializationKind(); - if (const auto *Spec = dyn_cast(this)) + if (auto const *Spec = dyn_cast(this)) return Spec->getSpecializationKind(); return TSK_Undeclared; } SourceLocation VarDecl::getPointOfInstantiation() const { - if (const auto *Spec = dyn_cast(this)) + if (auto const *Spec = dyn_cast(this)) return Spec->getPointOfInstantiation(); if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) @@ -2643,7 +2631,8 @@ } VarTemplateDecl *VarDecl::getDescribedVarTemplate() const { - return getASTContext().getTemplateOrSpecializationInfo(this) + return getASTContext() + .getTemplateOrSpecializationInfo(this) .dyn_cast(); } @@ -2652,7 +2641,7 @@ } bool VarDecl::isKnownToBeDefined() const { - const auto &LangOpts = getASTContext().getLangOpts(); + auto const &LangOpts = getASTContext().getLangOpts(); // In CUDA mode without relocatable device code, variables of form 'extern // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared // memory pool. These are never undefined variables, even if they appear @@ -2668,14 +2657,14 @@ return hasDefinition(); } -bool VarDecl::isNoDestroy(const ASTContext &Ctx) const { +bool VarDecl::isNoDestroy(ASTContext const &Ctx) const { return hasGlobalStorage() && (hasAttr() || (!Ctx.getLangOpts().RegisterStaticDestructors && !hasAttr())); } QualType::DestructionKind -VarDecl::needsDestruction(const ASTContext &Ctx) const { +VarDecl::needsDestruction(ASTContext const &Ctx) const { if (EvaluatedStmt *Eval = getEvaluatedStmt()) if (Eval->HasConstantDestruction) return QualType::DK_none; @@ -2690,13 +2679,14 @@ if (isStaticDataMember()) // FIXME: Remove ? // return getASTContext().getInstantiatedFromStaticDataMember(this); - return getASTContext().getTemplateOrSpecializationInfo(this) + return getASTContext() + .getTemplateOrSpecializationInfo(this) .dyn_cast(); return nullptr; } -void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, - SourceLocation PointOfInstantiation) { +void VarDecl::setTemplateSpecializationKind( + TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation) { assert((isa(this) || getMemberSpecializationInfo()) && "not a variable or static data member template specialization"); @@ -2704,8 +2694,7 @@ if (VarTemplateSpecializationDecl *Spec = dyn_cast(this)) { Spec->setSpecializationKind(TSK); - if (TSK != TSK_ExplicitSpecialization && - PointOfInstantiation.isValid() && + if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && Spec->getPointOfInstantiation().isInvalid()) { Spec->setPointOfInstantiation(PointOfInstantiation); if (ASTMutationListener *L = getASTContext().getASTMutationListener()) @@ -2722,9 +2711,8 @@ } } -void -VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD, - TemplateSpecializationKind TSK) { +void VarDecl::setInstantiationOfStaticDataMember( + VarDecl *VD, TemplateSpecializationKind TSK) { assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() && "Previous template or instantiation?"); getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK); @@ -2735,18 +2723,18 @@ //===----------------------------------------------------------------------===// ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation StartLoc, - SourceLocation IdLoc, IdentifierInfo *Id, - QualType T, TypeSourceInfo *TInfo, - StorageClass S, Expr *DefArg) { - return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, - S, DefArg); + SourceLocation StartLoc, SourceLocation IdLoc, + IdentifierInfo *Id, QualType T, + TypeSourceInfo *TInfo, StorageClass S, + Expr *DefArg) { + return new (C, DC) + ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo, S, DefArg); } QualType ParmVarDecl::getOriginalType() const { TypeSourceInfo *TSI = getTypeSourceInfo(); QualType T = TSI ? TSI->getType() : getType(); - if (const auto *DT = dyn_cast(T)) + if (auto const *DT = dyn_cast(T)) return DT->getOriginalType(); return T; } @@ -2811,7 +2799,7 @@ return getUninstantiatedDefaultArg()->getSourceRange(); case DAK_Normal: - if (const Expr *E = getInit()) + if (Expr const *E = getInit()) return E->getSourceRange(); // Missing an actual expression, may be invalid. @@ -2854,7 +2842,7 @@ FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, - const DeclarationNameInfo &NameInfo, QualType T, + DeclarationNameInfo const &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass S, bool UsesFPIntrin, bool isInlineSpecified, ConstexprSpecKind ConstexprKind, @@ -2892,16 +2880,17 @@ setTrailingRequiresClause(TrailingRequiresClause); } -void FunctionDecl::getNameForDiagnostic( - raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { +void FunctionDecl::getNameForDiagnostic(raw_ostream &OS, + PrintingPolicy const &Policy, + bool Qualified) const { NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); - const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); + TemplateArgumentList const *TemplateArgs = getTemplateSpecializationArgs(); if (TemplateArgs) printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy); } bool FunctionDecl::isVariadic() const { - if (const auto *FT = getType()->getAs()) + if (auto const *FT = getType()->getAs()) return FT->isVariadic(); return false; } @@ -2932,7 +2921,7 @@ return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr; } -bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { +bool FunctionDecl::hasBody(FunctionDecl const *&Definition) const { for (auto I : redecls()) { if (I->doesThisDeclarationHaveABody()) { Definition = I; @@ -2962,15 +2951,15 @@ // Check for a friend function instantiated from a friend function // definition in a templated class. - if (const FunctionDecl *InstantiatedFrom = + if (FunctionDecl const *InstantiatedFrom = getInstantiatedFromMemberFunction()) return InstantiatedFrom->getFriendObjectKind() && InstantiatedFrom->isThisDeclarationADefinition(); // Check for a friend function template instantiated from a friend // function template definition in a templated class. - if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) { - if (const FunctionTemplateDecl *InstantiatedFrom = + if (FunctionTemplateDecl const *Template = getDescribedFunctionTemplate()) { + if (FunctionTemplateDecl const *InstantiatedFrom = Template->getInstantiatedFromMemberTemplate()) return InstantiatedFrom->getFriendObjectKind() && InstantiatedFrom->isThisDeclarationADefinition(); @@ -2979,9 +2968,9 @@ return false; } -bool FunctionDecl::isDefined(const FunctionDecl *&Definition, +bool FunctionDecl::isDefined(FunctionDecl const *&Definition, bool CheckForPendingFriendDefinition) const { - for (const FunctionDecl *FD : redecls()) { + for (FunctionDecl const *FD : redecls()) { if (FD->isThisDeclarationADefinition()) { Definition = FD; return true; @@ -3012,7 +3001,7 @@ return false; } -Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { +Stmt *FunctionDecl::getBody(FunctionDecl const *&Definition) const { if (!hasBody(Definition)) return nullptr; @@ -3038,22 +3027,21 @@ Parent->markedVirtualFunctionPure(); } -template -static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) { +template +static bool isNamed(NamedDecl const *ND, char const (&Str)[Len]) { IdentifierInfo *II = ND->getIdentifier(); return II && II->isStr(Str); } bool FunctionDecl::isMain() const { - const TranslationUnitDecl *tunit = - dyn_cast(getDeclContext()->getRedeclContext()); - return tunit && - !tunit->getASTContext().getLangOpts().Freestanding && + TranslationUnitDecl const *tunit = + dyn_cast(getDeclContext()->getRedeclContext()); + return tunit && !tunit->getASTContext().getLangOpts().Freestanding && isNamed(this, "main"); } bool FunctionDecl::isMSVCRTEntryPoint() const { - const TranslationUnitDecl *TUnit = + TranslationUnitDecl const *TUnit = dyn_cast(getDeclContext()->getRedeclContext()); if (!TUnit) return false; @@ -3089,13 +3077,13 @@ if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) return false; - const auto *proto = getType()->castAs(); + auto const *proto = getType()->castAs(); if (proto->getNumParams() != 2 || proto->isVariadic()) return false; ASTContext &Context = - cast(getDeclContext()->getRedeclContext()) - ->getASTContext(); + cast(getDeclContext()->getRedeclContext()) + ->getASTContext(); // The result type and first argument type are constant across all // these operators. The second argument must be exactly void*. @@ -3119,7 +3107,7 @@ if (!getDeclContext()->getRedeclContext()->isTranslationUnit()) return false; - const auto *FPT = getType()->castAs(); + auto const *FPT = getType()->castAs(); if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic()) return false; @@ -3149,7 +3137,8 @@ // In C++17, the next parameter can be a 'std::align_val_t' for aligned // new/delete. - if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) { + if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && + Ty->isAlignValT()) { Consume(); if (AlignmentParam) *AlignmentParam = Params; @@ -3175,7 +3164,7 @@ if (!getBuiltinID()) return false; - const FunctionDecl *Definition; + FunctionDecl const *Definition; return hasBody(Definition) && Definition->isInlineSpecified(); } @@ -3197,9 +3186,7 @@ return getDeclLanguageLinkage(*this); } -bool FunctionDecl::isExternC() const { - return isDeclExternC(*this); -} +bool FunctionDecl::isExternC() const { return isDeclExternC(*this); } bool FunctionDecl::isInExternCContext() const { if (hasAttr()) @@ -3212,16 +3199,15 @@ } bool FunctionDecl::isGlobal() const { - if (const auto *Method = dyn_cast(this)) + if (auto const *Method = dyn_cast(this)) return Method->isStatic(); if (getCanonicalDecl()->getStorageClass() == SC_Static) return false; - for (const DeclContext *DC = getDeclContext(); - DC->isNamespace(); + for (DeclContext const *DC = getDeclContext(); DC->isNamespace(); DC = DC->getParent()) { - if (const auto *Namespace = cast(DC)) { + if (auto const *Namespace = cast(DC)) { if (!Namespace->getDeclName()) return false; break; @@ -3242,7 +3228,6 @@ return false; } - MultiVersionKind FunctionDecl::getMultiVersionKind() const { if (hasAttr()) return MultiVersionKind::Target; @@ -3265,13 +3250,12 @@ return isMultiVersion() && hasAttr(); } -void -FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { +void FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { redeclarable_base::setPreviousDecl(PrevDecl); if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { - FunctionTemplateDecl *PrevFunTmpl - = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr; + FunctionTemplateDecl *PrevFunTmpl = + PrevDecl ? PrevDecl->getDescribedFunctionTemplate() : nullptr; assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); FunTmpl->setPreviousDecl(PrevFunTmpl); } @@ -3298,11 +3282,11 @@ unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const { unsigned BuiltinID = 0; - if (const auto *ABAA = getAttr()) { + if (auto const *ABAA = getAttr()) { BuiltinID = ABAA->getBuiltinName()->getBuiltinID(); - } else if (const auto *BAA = getAttr()) { + } else if (auto const *BAA = getAttr()) { BuiltinID = BAA->getBuiltinName()->getBuiltinID(); - } else if (const auto *A = getAttr()) { + } else if (auto const *A = getAttr()) { BuiltinID = A->getID(); } @@ -3356,7 +3340,7 @@ /// based on its FunctionType. This is the length of the ParamInfo array /// after it has been created. unsigned FunctionDecl::getNumParams() const { - const auto *FPT = getType()->getAs(); + auto const *FPT = getType()->getAs(); return FPT ? FPT->getNumParams() : 0; } @@ -3367,7 +3351,7 @@ // Zero params -> null pointer. if (!NewParamInfo.empty()) { - ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; + ParamInfo = new (C) ParmVarDecl *[NewParamInfo.size()]; std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); } } @@ -3409,12 +3393,12 @@ bool FunctionDecl::isMSExternInline() const { assert(isInlined() && "expected to get called on an inlined function!"); - const ASTContext &Context = getASTContext(); + ASTContext const &Context = getASTContext(); if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && !hasAttr()) return false; - for (const FunctionDecl *FD = getMostRecentDecl(); FD; + for (FunctionDecl const *FD = getMostRecentDecl(); FD; FD = FD->getPreviousDecl()) if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) return true; @@ -3422,11 +3406,11 @@ return false; } -static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) { +static bool redeclForcesDefMSVC(FunctionDecl const *Redecl) { if (Redecl->getStorageClass() != SC_Extern) return false; - for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD; + for (FunctionDecl const *FD = Redecl->getPreviousDecl(); FD; FD = FD->getPreviousDecl()) if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern) return false; @@ -3434,7 +3418,7 @@ return true; } -static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { +static bool RedeclForcesDefC99(FunctionDecl const *Redecl) { // Only consider file-scope declarations in this test. if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) return false; @@ -3463,7 +3447,7 @@ ASTContext &Context = getASTContext(); if (Context.getLangOpts().MSVCCompat) { - const FunctionDecl *Definition; + FunctionDecl const *Definition; if (hasBody(Definition) && Definition->isInlined() && redeclForcesDefMSVC(this)) return true; @@ -3481,7 +3465,7 @@ if (!isInlineSpecified() || getStorageClass() == SC_Extern) return false; - const FunctionDecl *Prev = this; + FunctionDecl const *Prev = this; bool FoundBody = false; while ((Prev = Prev->getPreviousDecl())) { FoundBody |= Prev->doesThisDeclarationHaveABody(); @@ -3489,8 +3473,7 @@ if (Prev->doesThisDeclarationHaveABody()) { // If it's not the case that both 'inline' and 'extern' are // specified on the definition, then it is always externally visible. - if (!Prev->isInlineSpecified() || - Prev->getStorageClass() != SC_Extern) + if (!Prev->isInlineSpecified() || Prev->getStorageClass() != SC_Extern) return false; } else if (Prev->isInlineSpecified() && Prev->getStorageClass() != SC_Extern) { @@ -3506,7 +3489,7 @@ // then the definition in that translation unit is an inline definition. if (isInlineSpecified() && getStorageClass() != SC_Extern) return false; - const FunctionDecl *Prev = this; + FunctionDecl const *Prev = this; bool FoundBody = false; while ((Prev = Prev->getPreviousDecl())) { FoundBody |= Prev->doesThisDeclarationHaveABody(); @@ -3517,7 +3500,7 @@ } FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const { - const TypeSourceInfo *TSI = getTypeSourceInfo(); + TypeSourceInfo const *TSI = getTypeSourceInfo(); return TSI ? TSI->getTypeLoc().IgnoreParens().getAs() : FunctionTypeLoc(); } @@ -3528,7 +3511,7 @@ return SourceRange(); // Skip self-referential return types. - const SourceManager &SM = getASTContext().getSourceManager(); + SourceManager const &SM = getASTContext().getSourceManager(); SourceRange RTRange = FTL.getReturnLoc().getSourceRange(); SourceLocation Boundary = getNameInfo().getBeginLoc(); if (RTRange.isInvalid() || Boundary.isInvalid() || @@ -3598,8 +3581,7 @@ // If any declaration is 'inline' but not 'extern', then this definition // is externally visible. for (auto Redecl : redecls()) { - if (Redecl->isInlineSpecified() && - Redecl->getStorageClass() != SC_Extern) + if (Redecl->isInlineSpecified() && Redecl->getStorageClass() != SC_Extern) return true; } @@ -3636,7 +3618,7 @@ /// getLiteralIdentifier - The literal suffix identifier this function /// represents, if any. -const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { +IdentifierInfo const *FunctionDecl::getLiteralIdentifier() const { if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) return getDeclName().getCXXLiteralIdentifier(); return nullptr; @@ -3651,8 +3633,8 @@ return TK_MemberSpecialization; if (TemplateOrSpecialization.is()) return TK_FunctionTemplateSpecialization; - if (TemplateOrSpecialization.is - ()) + if (TemplateOrSpecialization + .is()) return TK_DependentFunctionTemplateSpecialization; llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); @@ -3675,14 +3657,11 @@ return nullptr; } -void -FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, - FunctionDecl *FD, - TemplateSpecializationKind TSK) { +void FunctionDecl::setInstantiationOfMemberFunction( + ASTContext &C, FunctionDecl *FD, TemplateSpecializationKind TSK) { assert(TemplateOrSpecialization.isNull() && "Member function is already a specialization"); - MemberSpecializationInfo *Info - = new (C) MemberSpecializationInfo(FD, TSK); + MemberSpecializationInfo *Info = new (C) MemberSpecializationInfo(FD, TSK); TemplateOrSpecialization = Info; } @@ -3690,7 +3669,8 @@ return TemplateOrSpecialization.dyn_cast(); } -void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) { +void FunctionDecl::setDescribedFunctionTemplate( + FunctionTemplateDecl *Template) { assert(TemplateOrSpecialization.isNull() && "Member function is already a specialization"); TemplateOrSpecialization = Template; @@ -3716,7 +3696,7 @@ } // Find the actual template from which we will instantiate. - const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); + FunctionDecl const *PatternDecl = getTemplateInstantiationPattern(); bool HasPattern = false; if (PatternDecl) HasPattern = PatternDecl->hasBody(PatternDecl); @@ -3756,7 +3736,7 @@ // Check for a declaration of this function that was instantiated from a // friend definition. - const FunctionDecl *FD = nullptr; + FunctionDecl const *FD = nullptr; if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true)) FD = this; @@ -3788,9 +3768,9 @@ } FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { - if (FunctionTemplateSpecializationInfo *Info - = TemplateOrSpecialization - .dyn_cast()) { + if (FunctionTemplateSpecializationInfo *Info = + TemplateOrSpecialization + .dyn_cast()) { return Info->getTemplate(); } return nullptr; @@ -3802,34 +3782,32 @@ .dyn_cast(); } -const TemplateArgumentList * +TemplateArgumentList const * FunctionDecl::getTemplateSpecializationArgs() const { - if (FunctionTemplateSpecializationInfo *Info - = TemplateOrSpecialization - .dyn_cast()) { + if (FunctionTemplateSpecializationInfo *Info = + TemplateOrSpecialization + .dyn_cast()) { return Info->TemplateArguments; } return nullptr; } -const ASTTemplateArgumentListInfo * +ASTTemplateArgumentListInfo const * FunctionDecl::getTemplateSpecializationArgsAsWritten() const { - if (FunctionTemplateSpecializationInfo *Info - = TemplateOrSpecialization - .dyn_cast()) { + if (FunctionTemplateSpecializationInfo *Info = + TemplateOrSpecialization + .dyn_cast()) { return Info->TemplateArgumentsAsWritten; } return nullptr; } -void -FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, - FunctionTemplateDecl *Template, - const TemplateArgumentList *TemplateArgs, - void *InsertPos, - TemplateSpecializationKind TSK, - const TemplateArgumentListInfo *TemplateArgsAsWritten, - SourceLocation PointOfInstantiation) { +void FunctionDecl::setFunctionTemplateSpecialization( + ASTContext &C, FunctionTemplateDecl *Template, + TemplateArgumentList const *TemplateArgs, void *InsertPos, + TemplateSpecializationKind TSK, + TemplateArgumentListInfo const *TemplateArgsAsWritten, + SourceLocation PointOfInstantiation) { assert((TemplateOrSpecialization.isNull() || TemplateOrSpecialization.is()) && "Member function is already a specialization"); @@ -3847,10 +3825,9 @@ Template->addSpecialization(Info, InsertPos); } -void -FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, - const UnresolvedSetImpl &Templates, - const TemplateArgumentListInfo &TemplateArgs) { +void FunctionDecl::setDependentTemplateSpecialization( + ASTContext &Context, UnresolvedSetImpl const &Templates, + TemplateArgumentListInfo const &TemplateArgs) { assert(TemplateOrSpecialization.isNull()); DependentFunctionTemplateSpecializationInfo *Info = DependentFunctionTemplateSpecializationInfo::Create(Context, Templates, @@ -3866,8 +3843,8 @@ DependentFunctionTemplateSpecializationInfo * DependentFunctionTemplateSpecializationInfo::Create( - ASTContext &Context, const UnresolvedSetImpl &Ts, - const TemplateArgumentListInfo &TArgs) { + ASTContext &Context, UnresolvedSetImpl const &Ts, + TemplateArgumentListInfo const &TArgs) { void *Buffer = Context.Allocate( totalSizeToAlloc( TArgs.size(), Ts.size())); @@ -3875,9 +3852,9 @@ } DependentFunctionTemplateSpecializationInfo:: -DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, - const TemplateArgumentListInfo &TArgs) - : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { + DependentFunctionTemplateSpecializationInfo( + UnresolvedSetImpl const &Ts, TemplateArgumentListInfo const &TArgs) + : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { NumTemplates = Ts.size(); NumArgs = TArgs.size(); @@ -3939,25 +3916,23 @@ return TSK_Undeclared; } -void -FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, - SourceLocation PointOfInstantiation) { - if (FunctionTemplateSpecializationInfo *FTSInfo - = TemplateOrSpecialization.dyn_cast< - FunctionTemplateSpecializationInfo*>()) { +void FunctionDecl::setTemplateSpecializationKind( + TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation) { + if (FunctionTemplateSpecializationInfo *FTSInfo = + TemplateOrSpecialization + .dyn_cast()) { FTSInfo->setTemplateSpecializationKind(TSK); - if (TSK != TSK_ExplicitSpecialization && - PointOfInstantiation.isValid() && + if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && FTSInfo->getPointOfInstantiation().isInvalid()) { FTSInfo->setPointOfInstantiation(PointOfInstantiation); if (ASTMutationListener *L = getASTContext().getASTMutationListener()) L->InstantiationRequested(this); } - } else if (MemberSpecializationInfo *MSInfo - = TemplateOrSpecialization.dyn_cast()) { + } else if (MemberSpecializationInfo *MSInfo = + TemplateOrSpecialization + .dyn_cast()) { MSInfo->setTemplateSpecializationKind(TSK); - if (TSK != TSK_ExplicitSpecialization && - PointOfInstantiation.isValid() && + if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && MSInfo->getPointOfInstantiation().isInvalid()) { MSInfo->setPointOfInstantiation(PointOfInstantiation); if (ASTMutationListener *L = getASTContext().getASTMutationListener()) @@ -3968,9 +3943,9 @@ } SourceLocation FunctionDecl::getPointOfInstantiation() const { - if (FunctionTemplateSpecializationInfo *FTSInfo - = TemplateOrSpecialization.dyn_cast< - FunctionTemplateSpecializationInfo*>()) + if (FunctionTemplateSpecializationInfo *FTSInfo = + TemplateOrSpecialization + .dyn_cast()) return FTSInfo->getPointOfInstantiation(); if (MemberSpecializationInfo *MSInfo = TemplateOrSpecialization.dyn_cast()) @@ -3986,7 +3961,7 @@ // If this function was instantiated from a member function of a // class template, check whether that member function was defined out-of-line. if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { - const FunctionDecl *Definition; + FunctionDecl const *Definition; if (FD->hasBody(Definition)) return Definition->isOutOfLine(); } @@ -3994,7 +3969,7 @@ // If this function was instantiated from a function template, // check whether that function template was defined out-of-line. if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { - const FunctionDecl *Definition; + FunctionDecl const *Definition; if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) return Definition->isOutOfLine(); } @@ -4146,7 +4121,7 @@ // FieldDecl Implementation //===----------------------------------------------------------------------===// -FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, +FieldDecl *FieldDecl::Create(ASTContext const &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, @@ -4156,32 +4131,32 @@ } FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(), - SourceLocation(), nullptr, QualType(), nullptr, - nullptr, false, ICIS_NoInit); + return new (C, ID) + FieldDecl(Field, nullptr, SourceLocation(), SourceLocation(), nullptr, + QualType(), nullptr, nullptr, false, ICIS_NoInit); } bool FieldDecl::isAnonymousStructOrUnion() const { if (!isImplicit() || getDeclName()) return false; - if (const auto *Record = getType()->getAs()) + if (auto const *Record = getType()->getAs()) return Record->getDecl()->isAnonymousStructOrUnion(); return false; } -unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { +unsigned FieldDecl::getBitWidthValue(ASTContext const &Ctx) const { assert(isBitField() && "not a bitfield"); return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue(); } -bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const { +bool FieldDecl::isZeroLengthBitField(ASTContext const &Ctx) const { return isUnnamedBitfield() && !getBitWidth()->isValueDependent() && getBitWidthValue(Ctx) == 0; } -bool FieldDecl::isZeroSize(const ASTContext &Ctx) const { +bool FieldDecl::isZeroSize(ASTContext const &Ctx) const { if (isZeroLengthBitField(Ctx)) return true; @@ -4192,10 +4167,10 @@ return false; // -- is not of class type, or - const auto *RT = getType()->getAs(); + auto const *RT = getType()->getAs(); if (!RT) return false; - const RecordDecl *RD = RT->getDecl()->getDefinition(); + RecordDecl const *RD = RT->getDecl()->getDefinition(); if (!RD) { assert(isInvalidDecl() && "valid field has incomplete type"); return false; @@ -4203,7 +4178,7 @@ // -- [has] virtual member functions or virtual base classes, or // -- has subobjects of nonzero size or bit-fields of nonzero length - const auto *CXXRD = cast(RD); + auto const *CXXRD = cast(RD); if (!CXXRD->isEmpty()) return false; @@ -4215,14 +4190,15 @@ } unsigned FieldDecl::getFieldIndex() const { - const FieldDecl *Canonical = getCanonicalDecl(); + FieldDecl const *Canonical = getCanonicalDecl(); if (Canonical != this) return Canonical->getFieldIndex(); - if (CachedFieldIndex) return CachedFieldIndex - 1; + if (CachedFieldIndex) + return CachedFieldIndex - 1; unsigned Index = 0; - const RecordDecl *RD = getParent()->getDefinition(); + RecordDecl const *RD = getParent()->getDefinition(); assert(RD && "requested index for field of struct with no definition"); for (auto *Field : RD->fields()) { @@ -4235,7 +4211,7 @@ } SourceRange FieldDecl::getSourceRange() const { - const Expr *FinalExpr = getInClassInitializer(); + Expr const *FinalExpr = getInClassInitializer(); if (!FinalExpr) FinalExpr = getBitWidth(); if (FinalExpr) @@ -4243,7 +4219,7 @@ return DeclaratorDecl::getSourceRange(); } -void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) { +void FieldDecl::setCapturedVLAType(VariableArrayType const *VLAType) { assert((getParent()->isLambda() || getParent()->isCapturedRecord()) && "capturing type in non-lambda or captured record."); assert(InitStorage.getInt() == ISK_NoInit && @@ -4257,7 +4233,7 @@ // TagDecl Implementation //===----------------------------------------------------------------------===// -TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, +TagDecl::TagDecl(Kind DK, TagKind TK, ASTContext const &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, SourceLocation StartL) : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C), @@ -4287,7 +4263,7 @@ void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { TypedefNameDeclOrQualifier = TDD; - if (const Type *T = getTypeForDecl()) { + if (Type const *T = getTypeForDecl()) { (void)T; assert(T->isLinkageValid()); } @@ -4299,7 +4275,7 @@ if (auto *D = dyn_cast(this)) { struct CXXRecordDecl::DefinitionData *Data = - new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); + new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); for (auto I : redecls()) cast(I)->DefinitionData = Data; } @@ -4330,7 +4306,7 @@ } } - if (const auto *CXXRD = dyn_cast(this)) + if (auto const *CXXRD = dyn_cast(this)) return CXXRD->getDefinition(); for (auto R : redecls()) @@ -4353,8 +4329,7 @@ if (getExtInfo()->NumTemplParamLists == 0) { getASTContext().Deallocate(getExtInfo()); TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr; - } - else + } else getExtInfo()->QualifierLoc = QualifierLoc; } } @@ -4394,9 +4369,9 @@ EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, - IdentifierInfo *Id, - EnumDecl *PrevDecl, bool IsScoped, - bool IsScopedUsingClassTag, bool IsFixed) { + IdentifierInfo *Id, EnumDecl *PrevDecl, + bool IsScoped, bool IsScopedUsingClassTag, + bool IsFixed) { auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl, IsScoped, IsScopedUsingClassTag, IsFixed); Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules); @@ -4413,13 +4388,12 @@ } SourceRange EnumDecl::getIntegerTypeRange() const { - if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo()) + if (TypeSourceInfo const *TI = getIntegerTypeSourceInfo()) return TI->getTypeLoc().getSourceRange(); return SourceRange(); } -void EnumDecl::completeDefinition(QualType NewType, - QualType NewPromotionType, +void EnumDecl::completeDefinition(QualType NewType, QualType NewPromotionType, unsigned NumPositiveBits, unsigned NumNegativeBits) { assert(!isCompleteDefinition() && "Cannot redefine enums!"); @@ -4432,7 +4406,7 @@ } bool EnumDecl::isClosed() const { - if (const auto *A = getAttr()) + if (auto const *A = getAttr()) return A->getExtensibility() == EnumExtensibilityAttr::Closed; return true; } @@ -4452,13 +4426,12 @@ return TSK_Undeclared; } -void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, - SourceLocation PointOfInstantiation) { +void EnumDecl::setTemplateSpecializationKind( + TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation) { MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); assert(MSI && "Not an instantiated member enumeration?"); MSI->setTemplateSpecializationKind(TSK); - if (TSK != TSK_ExplicitSpecialization && - PointOfInstantiation.isValid() && + if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() && MSI->getPointOfInstantiation().isInvalid()) MSI->setPointOfInstantiation(PointOfInstantiation); } @@ -4506,7 +4479,7 @@ // RecordDecl Implementation //===----------------------------------------------------------------------===// -RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C, +RecordDecl::RecordDecl(Kind DK, TagKind TK, ASTContext const &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl) @@ -4527,18 +4500,18 @@ setArgPassingRestrictions(APK_CanPassInRegs); } -RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, +RecordDecl *RecordDecl::Create(ASTContext const &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, - IdentifierInfo *Id, RecordDecl* PrevDecl) { - RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC, - StartLoc, IdLoc, Id, PrevDecl); + IdentifierInfo *Id, RecordDecl *PrevDecl) { + RecordDecl *R = + new (C, DC) RecordDecl(Record, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl); R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); C.getTypeDeclType(R, PrevDecl); return R; } -RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { +RecordDecl *RecordDecl::CreateDeserialized(ASTContext const &C, unsigned ID) { RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(), SourceLocation(), nullptr, nullptr); @@ -4548,7 +4521,7 @@ bool RecordDecl::isInjectedClassName() const { return isImplicit() && getDeclName() && getDeclContext()->isRecord() && - cast(getDeclContext())->getDeclName() == getDeclName(); + cast(getDeclContext())->getDeclName() == getDeclName(); } bool RecordDecl::isLambda() const { @@ -4569,9 +4542,9 @@ if (isUnion()) return true; - if (const RecordDecl *Def = getDefinition()) { - for (const FieldDecl *FD : Def->fields()) { - const RecordType *RT = FD->getType()->getAs(); + if (RecordDecl const *Def = getDefinition()) { + for (FieldDecl const *FD : Def->fields()) { + RecordType const *RT = FD->getType()->getAs(); if (RT && RT->getDecl()->isOrContainsUnion()) return true; } @@ -4604,7 +4577,7 @@ /// isMsStruct - Get whether or not this record uses ms_struct layout. /// This which can be turned on with an attribute, pragma, or the /// -mms-bitfields command-line option. -bool RecordDecl::isMsStruct(const ASTContext &C) const { +bool RecordDecl::isMsStruct(ASTContext const &C) const { return hasAttr() || C.getLangOpts().MSBitfields == 1; } @@ -4615,15 +4588,18 @@ // Notify that we have a RecordDecl doing some initialization. ExternalASTSource::Deserializing TheFields(Source); - SmallVector Decls; + SmallVector Decls; setHasLoadedFieldsFromExternalStorage(true); - Source->FindExternalLexicalDecls(this, [](Decl::Kind K) { - return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); - }, Decls); + Source->FindExternalLexicalDecls( + this, + [](Decl::Kind K) { + return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); + }, + Decls); #ifndef NDEBUG // Check that all decls we got were FieldDecls. - for (unsigned i=0, e=Decls.size(); i != e; ++i) + for (unsigned i = 0, e = Decls.size(); i != e; ++i) assert(isa(Decls[i]) || isa(Decls[i])); #endif @@ -4636,32 +4612,33 @@ bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const { ASTContext &Context = getASTContext(); - const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask & + const SanitizerMask EnabledAsanMask = + Context.getLangOpts().Sanitize.Mask & (SanitizerKind::Address | SanitizerKind::KernelAddress); if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding) return false; - const auto &NoSanitizeList = Context.getNoSanitizeList(); - const auto *CXXRD = dyn_cast(this); + auto const &NoSanitizeList = Context.getNoSanitizeList(); + auto const *CXXRD = dyn_cast(this); // We may be able to relax some of these requirements. int ReasonToReject = -1; if (!CXXRD || CXXRD->isExternCContext()) - ReasonToReject = 0; // is not C++. + ReasonToReject = 0; // is not C++. else if (CXXRD->hasAttr()) - ReasonToReject = 1; // is packed. + ReasonToReject = 1; // is packed. else if (CXXRD->isUnion()) - ReasonToReject = 2; // is a union. + ReasonToReject = 2; // is a union. else if (CXXRD->isTriviallyCopyable()) - ReasonToReject = 3; // is trivially copyable. + ReasonToReject = 3; // is trivially copyable. else if (CXXRD->hasTrivialDestructor()) - ReasonToReject = 4; // has trivial destructor. + ReasonToReject = 4; // has trivial destructor. else if (CXXRD->isStandardLayout()) - ReasonToReject = 5; // is standard layout. + ReasonToReject = 5; // is standard layout. else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(), "field-padding")) - ReasonToReject = 6; // is in an excluded file. + ReasonToReject = 6; // is in an excluded file. else if (NoSanitizeList.containsType( EnabledAsanMask, getQualifiedNameAsString(), "field-padding")) - ReasonToReject = 7; // The type is excluded. + ReasonToReject = 7; // The type is excluded. if (EmitRemark) { if (ReasonToReject >= 0) @@ -4678,13 +4655,13 @@ return ReasonToReject < 0; } -const FieldDecl *RecordDecl::findFirstNamedDataMember() const { - for (const auto *I : fields()) { +FieldDecl const *RecordDecl::findFirstNamedDataMember() const { + for (auto const *I : fields()) { if (I->getIdentifier()) return I; - if (const auto *RT = I->getType()->getAs()) - if (const FieldDecl *NamedDataMember = + if (auto const *RT = I->getType()->getAs()) + if (FieldDecl const *NamedDataMember = RT->getDecl()->findFirstNamedDataMember()) return NamedDataMember; } @@ -4713,7 +4690,7 @@ // Zero params -> null pointer. if (!NewParamInfo.empty()) { NumParams = NewParamInfo.size(); - ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; + ParamInfo = new (getASTContext()) ParmVarDecl *[NewParamInfo.size()]; std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); } } @@ -4731,8 +4708,8 @@ this->Captures = Captures.copy(Context).data(); } -bool BlockDecl::capturesVariable(const VarDecl *variable) const { - for (const auto &I : captures()) +bool BlockDecl::capturesVariable(VarDecl const *variable) const { + for (auto const &I : captures()) // Only auto vars can be captured, so no redeclaration worries. if (I.getVariable() == variable) return true; @@ -4756,7 +4733,7 @@ void PragmaCommentDecl::anchor() {} -PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C, +PragmaCommentDecl *PragmaCommentDecl::Create(ASTContext const &C, TranslationUnitDecl *DC, SourceLocation CommentLoc, PragmaMSCommentKind CommentKind, @@ -4779,7 +4756,7 @@ void PragmaDetectMismatchDecl::anchor() {} PragmaDetectMismatchDecl * -PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC, +PragmaDetectMismatchDecl::Create(ASTContext const &C, TranslationUnitDecl *DC, SourceLocation Loc, StringRef Name, StringRef Value) { size_t ValueStart = Name.size() + 1; @@ -4803,7 +4780,7 @@ void ExternCContextDecl::anchor() {} -ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C, +ExternCContextDecl *ExternCContextDecl::Create(ASTContext const &C, TranslationUnitDecl *DC) { return new (C, DC) ExternCContextDecl(DC); } @@ -4823,12 +4800,12 @@ } LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, - SourceLocation()); + return new (C, ID) + LabelDecl(nullptr, SourceLocation(), nullptr, nullptr, SourceLocation()); } void LabelDecl::setMSAsmLabel(StringRef Name) { -char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; + char *Buffer = new (getASTContext(), 1) char[Name.size() + 1]; memcpy(Buffer, Name.data(), Name.size()); Buffer[Name.size()] = '\0'; MSAsmName = Buffer; @@ -4863,7 +4840,7 @@ FunctionDecl * FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, - const DeclarationNameInfo &NameInfo, QualType T, + DeclarationNameInfo const &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInlineSpecified, bool hasWrittenPrototype, ConstexprSpecKind ConstexprKind, @@ -4912,14 +4889,14 @@ void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); } EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, - SourceLocation L, - IdentifierInfo *Id, QualType T, - Expr *E, const llvm::APSInt &V) { + SourceLocation L, IdentifierInfo *Id, + QualType T, Expr *E, + llvm::APSInt const &V) { return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V); } -EnumConstantDecl * -EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { +EnumConstantDecl *EnumConstantDecl::CreateDeserialized(ASTContext &C, + unsigned ID) { return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr, QualType(), nullptr, llvm::APSInt()); } @@ -5049,8 +5026,8 @@ FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), - SourceLocation()); + return new (C, ID) + FileScopeAsmDecl(nullptr, nullptr, SourceLocation(), SourceLocation()); } void EmptyDecl::anchor() {} @@ -5124,7 +5101,7 @@ if (!isImportComplete()) return None; - const auto *StoredLocs = getTrailingObjects(); + auto const *StoredLocs = getTrailingObjects(); return llvm::makeArrayRef(StoredLocs, getNumModuleIdentifiers(getImportedModule())); } Index: clang/lib/AST/DeclBase.cpp =================================================================== --- clang/lib/AST/DeclBase.cpp +++ clang/lib/AST/DeclBase.cpp @@ -70,14 +70,14 @@ #define ABSTRACT_DECL(DECL) #include "clang/AST/DeclNodes.inc" -void *Decl::operator new(std::size_t Size, const ASTContext &Context, +void *Decl::operator new(std::size_t Size, ASTContext const &Context, unsigned ID, std::size_t Extra) { // Allocate an extra 8 bytes worth of storage, which ensures that the // resulting pointer will still be 8-byte aligned. static_assert(sizeof(unsigned) * 2 >= alignof(Decl), "Decl won't be misaligned"); void *Start = Context.Allocate(Size + Extra + 8); - void *Result = (char*)Start + 8; + void *Result = (char *)Start + 8; unsigned *PrefixPtr = (unsigned *)Result - 2; @@ -90,7 +90,7 @@ return Result; } -void *Decl::operator new(std::size_t Size, const ASTContext &Ctx, +void *Decl::operator new(std::size_t Size, ASTContext const &Ctx, DeclContext *Parent, std::size_t Extra) { assert(!Parent || &Parent->getParentASTContext() == &Ctx); // With local visibility enabled, we track the owning module even for local @@ -106,7 +106,7 @@ Buffer += ExtraAlign; auto *ParentModule = Parent ? cast(Parent)->getOwningModule() : nullptr; - return new (Buffer) Module*(ParentModule) + 1; + return new (Buffer) Module *(ParentModule) + 1; } return ::operator new(Size + Extra, Ctx); } @@ -120,10 +120,13 @@ return getASTContext().getLangOpts().trackLocalOwningModule(); } -const char *Decl::getDeclKindName() const { +char const *Decl::getDeclKindName() const { switch (DeclKind) { - default: llvm_unreachable("Declaration not in DeclNodes.inc!"); -#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED; + default: + llvm_unreachable("Declaration not in DeclNodes.inc!"); +#define DECL(DERIVED, BASE) \ + case DERIVED: \ + return #DERIVED; #define ABSTRACT_DECL(DECL) #include "clang/AST/DeclNodes.inc" } @@ -152,9 +155,11 @@ } } -const char *DeclContext::getDeclKindName() const { +char const *DeclContext::getDeclKindName() const { switch (getDeclKind()) { -#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED; +#define DECL(DERIVED, BASE) \ + case Decl::DERIVED: \ + return #DERIVED; #define ABSTRACT_DECL(DECL) #include "clang/AST/DeclNodes.inc" } @@ -162,9 +167,7 @@ } bool Decl::StatisticsEnabled = false; -void Decl::EnableStatistics() { - StatisticsEnabled = true; -} +void Decl::EnableStatistics() { StatisticsEnabled = true; } void Decl::PrintStats() { llvm::errs() << "\n*** Decl Stats:\n"; @@ -176,13 +179,12 @@ llvm::errs() << " " << totalDecls << " decls total.\n"; int totalBytes = 0; -#define DECL(DERIVED, BASE) \ - if (n##DERIVED##s > 0) { \ - totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \ - llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \ - << sizeof(DERIVED##Decl) << " each (" \ - << n##DERIVED##s * sizeof(DERIVED##Decl) \ - << " bytes)\n"; \ +#define DECL(DERIVED, BASE) \ + if (n##DERIVED##s > 0) { \ + totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \ + llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \ + << sizeof(DERIVED##Decl) << " each (" \ + << n##DERIVED##s * sizeof(DERIVED##Decl) << " bytes)\n"; \ } #define ABSTRACT_DECL(DECL) #include "clang/AST/DeclNodes.inc" @@ -192,24 +194,27 @@ void Decl::add(Kind k) { switch (k) { -#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break; +#define DECL(DERIVED, BASE) \ + case DERIVED: \ + ++n##DERIVED##s; \ + break; #define ABSTRACT_DECL(DECL) #include "clang/AST/DeclNodes.inc" } } bool Decl::isTemplateParameterPack() const { - if (const auto *TTP = dyn_cast(this)) + if (auto const *TTP = dyn_cast(this)) return TTP->isParameterPack(); - if (const auto *NTTP = dyn_cast(this)) + if (auto const *NTTP = dyn_cast(this)) return NTTP->isParameterPack(); - if (const auto *TTP = dyn_cast(this)) + if (auto const *TTP = dyn_cast(this)) return TTP->isParameterPack(); return false; } bool Decl::isParameterPack() const { - if (const auto *Var = dyn_cast(this)) + if (auto const *Var = dyn_cast(this)) return Var->isParameterPack(); return isTemplateParameterPack(); @@ -218,14 +223,12 @@ FunctionDecl *Decl::getAsFunction() { if (auto *FD = dyn_cast(this)) return FD; - if (const auto *FTD = dyn_cast(this)) + if (auto const *FTD = dyn_cast(this)) return FTD->getTemplatedDecl(); return nullptr; } -bool Decl::isTemplateDecl() const { - return isa(this); -} +bool Decl::isTemplateDecl() const { return isa(this); } TemplateDecl *Decl::getDescribedTemplate() const { if (auto *FD = dyn_cast(this)) @@ -240,7 +243,7 @@ return nullptr; } -const TemplateParameterList *Decl::getDescribedTemplateParams() const { +TemplateParameterList const *Decl::getDescribedTemplateParams() const { if (auto *TD = getDescribedTemplate()) return TD->getTemplateParameters(); if (auto *CTPSD = dyn_cast(this)) @@ -278,13 +281,13 @@ if (Decl *Context = RD->getLambdaContextDecl()) return Context->getTemplateDepth(); - const DeclContext *DC = + DeclContext const *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext(); return cast(DC)->getTemplateDepth(); } -const DeclContext *Decl::getParentFunctionOrMethod() const { - for (const DeclContext *DC = getDeclContext(); +DeclContext const *Decl::getParentFunctionOrMethod() const { + for (DeclContext const *DC = getDeclContext(); DC && !DC->isTranslationUnit() && !DC->isNamespace(); DC = DC->getParent()) if (DC->isFunctionOrMethod()) @@ -309,7 +312,7 @@ OS << Message; - if (const auto *DN = dyn_cast_or_null(TheDecl)) { + if (auto const *DN = dyn_cast_or_null(TheDecl)) { OS << " '"; DN->printQualifiedName(OS); OS << '\''; @@ -324,9 +327,7 @@ // Out-of-line virtual method providing a home for Decl. Decl::~Decl() = default; -void Decl::setDeclContext(DeclContext *DC) { - DeclCtx = DC; -} +void Decl::setDeclContext(DeclContext *DC) { DeclCtx = DC; } void Decl::setLexicalDeclContext(DeclContext *DC) { if (DC == getLexicalDeclContext()) @@ -365,7 +366,7 @@ } bool Decl::isInLocalScopeForInstantiation() const { - const DeclContext *LDC = getLexicalDeclContext(); + DeclContext const *LDC = getLexicalDeclContext(); if (!LDC->isDependentContext()) return false; while (true) { @@ -373,7 +374,7 @@ return true; if (!isa(LDC)) return false; - if (const auto *CRD = dyn_cast(LDC)) + if (auto const *CRD = dyn_cast(LDC)) if (CRD->isLambda()) return true; LDC = LDC->getLexicalParent(); @@ -382,8 +383,8 @@ } bool Decl::isInAnonymousNamespace() const { - for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) { - if (const auto *ND = dyn_cast(DC)) + for (DeclContext const *DC = getDeclContext(); DC; DC = DC->getParent()) { + if (auto const *ND = dyn_cast(DC)) if (ND->isAnonymousNamespace()) return true; } @@ -392,7 +393,7 @@ } bool Decl::isInStdNamespace() const { - const DeclContext *DC = getDeclContext(); + DeclContext const *DC = getDeclContext(); return DC && DC->isStdNamespace(); } @@ -417,7 +418,7 @@ /// Helper to get the language options from the ASTContext. /// Defined out of line to avoid depending on ASTContext.h. -const LangOptions &Decl::getLangOpts() const { +LangOptions const &Decl::getLangOpts() const { return getASTContext().getLangOpts(); } @@ -430,7 +431,7 @@ return 0; unsigned Align = 0; - const AttrVec &V = getAttrs(); + AttrVec const &V = getAttrs(); ASTContext &Ctx = getASTContext(); specific_attr_iterator I(V.begin()), E(V.end()); for (; I != E; ++I) { @@ -441,7 +442,7 @@ } bool Decl::isUsed(bool CheckUsedAttr) const { - const Decl *CanonD = getCanonicalDecl(); + Decl const *CanonD = getCanonicalDecl(); if (CanonD->Used) return true; @@ -470,7 +471,7 @@ return true; // Check redeclarations. - for (const auto *I : redecls()) + for (auto const *I : redecls()) if (I->Referenced) return true; @@ -478,7 +479,7 @@ } ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const { - const Decl *Definition = nullptr; + Decl const *Definition = nullptr; if (auto *ID = dyn_cast(this)) { Definition = ID->getDefinition(); } else if (auto *PD = dyn_cast(this)) { @@ -503,7 +504,7 @@ hasAttr(); } -const Attr *Decl::getDefiningAttr() const { +Attr const *Decl::getDefiningAttr() const { if (auto *AA = getAttr()) return AA; if (auto *IFA = getAttr()) @@ -513,8 +514,8 @@ return nullptr; } -static StringRef getRealizedPlatform(const AvailabilityAttr *A, - const ASTContext &Context) { +static StringRef getRealizedPlatform(AvailabilityAttr const *A, + ASTContext const &Context) { // Check if this is an App Extension "platform", and if so chop off // the suffix for matching with the actual platform. StringRef RealizedPlatform = A->getPlatform()->getName(); @@ -536,7 +537,7 @@ /// FIXME: Make these strings localizable, since they end up in /// diagnostics. static AvailabilityResult CheckAvailability(ASTContext &Context, - const AvailabilityAttr *A, + AvailabilityAttr const *A, std::string *Message, VersionTuple EnclosingVersion) { if (EnclosingVersion.empty()) @@ -552,8 +553,8 @@ if (getRealizedPlatform(A, Context) != TargetPlatform) return AR_Available; - StringRef PrettyPlatformName - = AvailabilityAttr::getPrettyPlatformName(ActualPlatform); + StringRef PrettyPlatformName = + AvailabilityAttr::getPrettyPlatformName(ActualPlatform); if (PrettyPlatformName.empty()) PrettyPlatformName = ActualPlatform; @@ -569,22 +570,20 @@ if (Message) { Message->clear(); llvm::raw_string_ostream Out(*Message); - Out << "not available on " << PrettyPlatformName - << HintMessage; + Out << "not available on " << PrettyPlatformName << HintMessage; } return AR_Unavailable; } // Make sure that this declaration has already been introduced. - if (!A->getIntroduced().empty() && - EnclosingVersion < A->getIntroduced()) { + if (!A->getIntroduced().empty() && EnclosingVersion < A->getIntroduced()) { if (Message) { Message->clear(); llvm::raw_string_ostream Out(*Message); VersionTuple VTI(A->getIntroduced()); - Out << "introduced in " << PrettyPlatformName << ' ' - << VTI << HintMessage; + Out << "introduced in " << PrettyPlatformName << ' ' << VTI + << HintMessage; } return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced; @@ -596,8 +595,7 @@ Message->clear(); llvm::raw_string_ostream Out(*Message); VersionTuple VTO(A->getObsoleted()); - Out << "obsoleted in " << PrettyPlatformName << ' ' - << VTO << HintMessage; + Out << "obsoleted in " << PrettyPlatformName << ' ' << VTO << HintMessage; } return AR_Unavailable; @@ -609,8 +607,8 @@ Message->clear(); llvm::raw_string_ostream Out(*Message); VersionTuple VTD(A->getDeprecated()); - Out << "first deprecated in " << PrettyPlatformName << ' ' - << VTD << HintMessage; + Out << "first deprecated in " << PrettyPlatformName << ' ' << VTD + << HintMessage; } return AR_Deprecated; @@ -629,8 +627,8 @@ AvailabilityResult Result = AR_Available; std::string ResultMessage; - for (const auto *A : attrs()) { - if (const auto *Deprecated = dyn_cast(A)) { + for (auto const *A : attrs()) { + if (auto const *Deprecated = dyn_cast(A)) { if (Result >= AR_Deprecated) continue; @@ -641,13 +639,13 @@ continue; } - if (const auto *Unavailable = dyn_cast(A)) { + if (auto const *Unavailable = dyn_cast(A)) { if (Message) *Message = std::string(Unavailable->getMessage()); return AR_Unavailable; } - if (const auto *Availability = dyn_cast(A)) { + if (auto const *Availability = dyn_cast(A)) { AvailabilityResult AR = CheckAvailability(getASTContext(), Availability, Message, EnclosingVersion); @@ -672,10 +670,10 @@ } VersionTuple Decl::getVersionIntroduced() const { - const ASTContext &Context = getASTContext(); + ASTContext const &Context = getASTContext(); StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); - for (const auto *A : attrs()) { - if (const auto *Availability = dyn_cast(A)) { + for (auto const *A : attrs()) { + if (auto const *Availability = dyn_cast(A)) { if (getRealizedPlatform(Availability, Context) != TargetPlatform) continue; if (!Availability->getIntroduced().empty()) @@ -689,7 +687,7 @@ IsDefinition = false; // Variables, if they aren't definitions. - if (const auto *Var = dyn_cast(this)) { + if (auto const *Var = dyn_cast(this)) { if (Var->isThisDeclarationADefinition()) { IsDefinition = true; return false; @@ -697,17 +695,16 @@ return true; } // Functions, if they aren't definitions. - if (const auto *FD = dyn_cast(this)) { + if (auto const *FD = dyn_cast(this)) { if (FD->hasBody()) { IsDefinition = true; return false; } return true; - } // Objective-C classes, if this is the non-fragile runtime. if (isa(this) && - getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) { + getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) { return true; } // Nothing else. @@ -719,11 +716,11 @@ if (!canBeWeakImported(IsDefinition)) return false; - for (const auto *A : getMostRecentDecl()->attrs()) { + for (auto const *A : getMostRecentDecl()->attrs()) { if (isa(A)) return true; - if (const auto *Availability = dyn_cast(A)) { + if (auto const *Availability = dyn_cast(A)) { if (CheckAvailability(getASTContext(), Availability, nullptr, VersionTuple()) == AR_NotYetIntroduced) return true; @@ -735,137 +732,137 @@ unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { switch (DeclKind) { - case Function: - case CXXDeductionGuide: - case CXXMethod: - case CXXConstructor: - case ConstructorUsingShadow: - case CXXDestructor: - case CXXConversion: - case EnumConstant: - case Var: - case ImplicitParam: - case ParmVar: - case ObjCMethod: - case ObjCProperty: - case MSProperty: - return IDNS_Ordinary; - case Label: - return IDNS_Label; - case IndirectField: - return IDNS_Ordinary | IDNS_Member; - - case Binding: - case NonTypeTemplateParm: - case VarTemplate: - case Concept: - // These (C++-only) declarations are found by redeclaration lookup for - // tag types, so we include them in the tag namespace. - return IDNS_Ordinary | IDNS_Tag; - - case ObjCCompatibleAlias: - case ObjCInterface: - return IDNS_Ordinary | IDNS_Type; - - case Typedef: - case TypeAlias: - case TemplateTypeParm: - case ObjCTypeParam: - return IDNS_Ordinary | IDNS_Type; - - case UnresolvedUsingTypename: - return IDNS_Ordinary | IDNS_Type | IDNS_Using; - - case UsingShadow: - return 0; // we'll actually overwrite this later - - case UnresolvedUsingValue: - return IDNS_Ordinary | IDNS_Using; - - case Using: - case UsingPack: - case UsingEnum: - return IDNS_Using; - - case ObjCProtocol: - return IDNS_ObjCProtocol; - - case Field: - case ObjCAtDefsField: - case ObjCIvar: - return IDNS_Member; - - case Record: - case CXXRecord: - case Enum: - return IDNS_Tag | IDNS_Type; - - case Namespace: - case NamespaceAlias: - return IDNS_Namespace; - - case FunctionTemplate: - return IDNS_Ordinary; - - case ClassTemplate: - case TemplateTemplateParm: - case TypeAliasTemplate: - return IDNS_Ordinary | IDNS_Tag | IDNS_Type; - - case UnresolvedUsingIfExists: - return IDNS_Type | IDNS_Ordinary; - - case OMPDeclareReduction: - return IDNS_OMPReduction; - - case OMPDeclareMapper: - return IDNS_OMPMapper; - - // Never have names. - case Friend: - case FriendTemplate: - case AccessSpec: - case LinkageSpec: - case Export: - case FileScopeAsm: - case StaticAssert: - case ObjCPropertyImpl: - case PragmaComment: - case PragmaDetectMismatch: - case Block: - case Captured: - case TranslationUnit: - case ExternCContext: - case Decomposition: - case MSGuid: - case TemplateParamObject: - - case UsingDirective: - case BuiltinTemplate: - case ClassTemplateSpecialization: - case ClassTemplatePartialSpecialization: - case ClassScopeFunctionSpecialization: - case VarTemplateSpecialization: - case VarTemplatePartialSpecialization: - case ObjCImplementation: - case ObjCCategory: - case ObjCCategoryImpl: - case Import: - case OMPThreadPrivate: - case OMPAllocate: - case OMPRequires: - case OMPCapturedExpr: - case Empty: - case LifetimeExtendedTemporary: - case RequiresExprBody: - // Never looked up by name. - return 0; + case Function: + case CXXDeductionGuide: + case CXXMethod: + case CXXConstructor: + case ConstructorUsingShadow: + case CXXDestructor: + case CXXConversion: + case EnumConstant: + case Var: + case ImplicitParam: + case ParmVar: + case ObjCMethod: + case ObjCProperty: + case MSProperty: + return IDNS_Ordinary; + case Label: + return IDNS_Label; + case IndirectField: + return IDNS_Ordinary | IDNS_Member; + + case Binding: + case NonTypeTemplateParm: + case VarTemplate: + case Concept: + // These (C++-only) declarations are found by redeclaration lookup for + // tag types, so we include them in the tag namespace. + return IDNS_Ordinary | IDNS_Tag; + + case ObjCCompatibleAlias: + case ObjCInterface: + return IDNS_Ordinary | IDNS_Type; + + case Typedef: + case TypeAlias: + case TemplateTypeParm: + case ObjCTypeParam: + return IDNS_Ordinary | IDNS_Type; + + case UnresolvedUsingTypename: + return IDNS_Ordinary | IDNS_Type | IDNS_Using; + + case UsingShadow: + return 0; // we'll actually overwrite this later + + case UnresolvedUsingValue: + return IDNS_Ordinary | IDNS_Using; + + case Using: + case UsingPack: + case UsingEnum: + return IDNS_Using; + + case ObjCProtocol: + return IDNS_ObjCProtocol; + + case Field: + case ObjCAtDefsField: + case ObjCIvar: + return IDNS_Member; + + case Record: + case CXXRecord: + case Enum: + return IDNS_Tag | IDNS_Type; + + case Namespace: + case NamespaceAlias: + return IDNS_Namespace; + + case FunctionTemplate: + return IDNS_Ordinary; + + case ClassTemplate: + case TemplateTemplateParm: + case TypeAliasTemplate: + return IDNS_Ordinary | IDNS_Tag | IDNS_Type; + + case UnresolvedUsingIfExists: + return IDNS_Type | IDNS_Ordinary; + + case OMPDeclareReduction: + return IDNS_OMPReduction; + + case OMPDeclareMapper: + return IDNS_OMPMapper; + + // Never have names. + case Friend: + case FriendTemplate: + case AccessSpec: + case LinkageSpec: + case Export: + case FileScopeAsm: + case StaticAssert: + case ObjCPropertyImpl: + case PragmaComment: + case PragmaDetectMismatch: + case Block: + case Captured: + case TranslationUnit: + case ExternCContext: + case Decomposition: + case MSGuid: + case TemplateParamObject: + + case UsingDirective: + case BuiltinTemplate: + case ClassTemplateSpecialization: + case ClassTemplatePartialSpecialization: + case ClassScopeFunctionSpecialization: + case VarTemplateSpecialization: + case VarTemplatePartialSpecialization: + case ObjCImplementation: + case ObjCCategory: + case ObjCCategoryImpl: + case Import: + case OMPThreadPrivate: + case OMPAllocate: + case OMPRequires: + case OMPCapturedExpr: + case Empty: + case LifetimeExtendedTemporary: + case RequiresExprBody: + // Never looked up by name. + return 0; } llvm_unreachable("Invalid DeclKind!"); } -void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) { +void Decl::setAttrsImpl(AttrVec const &attrs, ASTContext &Ctx) { assert(!HasAttrs && "Decl already contains attrs."); AttrVec &AttrBlank = Ctx.getDeclAttrs(this); @@ -876,7 +873,8 @@ } void Decl::dropAttrs() { - if (!HasAttrs) return; + if (!HasAttrs) + return; HasAttrs = false; getASTContext().eraseDeclAttrs(this); @@ -905,54 +903,54 @@ Attrs.insert(I, A); } -const AttrVec &Decl::getAttrs() const { +AttrVec const &Decl::getAttrs() const { assert(HasAttrs && "No attrs to get!"); return getASTContext().getDeclAttrs(this); } -Decl *Decl::castFromDeclContext (const DeclContext *D) { +Decl *Decl::castFromDeclContext(DeclContext const *D) { Decl::Kind DK = D->getDeclKind(); - switch(DK) { + switch (DK) { #define DECL(NAME, BASE) -#define DECL_CONTEXT(NAME) \ - case Decl::NAME: \ - return static_cast(const_cast(D)); +#define DECL_CONTEXT(NAME) \ + case Decl::NAME: \ + return static_cast(const_cast(D)); #define DECL_CONTEXT_BASE(NAME) #include "clang/AST/DeclNodes.inc" - default: + default: #define DECL(NAME, BASE) -#define DECL_CONTEXT_BASE(NAME) \ - if (DK >= first##NAME && DK <= last##NAME) \ - return static_cast(const_cast(D)); +#define DECL_CONTEXT_BASE(NAME) \ + if (DK >= first##NAME && DK <= last##NAME) \ + return static_cast(const_cast(D)); #include "clang/AST/DeclNodes.inc" - llvm_unreachable("a decl that inherits DeclContext isn't handled"); + llvm_unreachable("a decl that inherits DeclContext isn't handled"); } } -DeclContext *Decl::castToDeclContext(const Decl *D) { +DeclContext *Decl::castToDeclContext(Decl const *D) { Decl::Kind DK = D->getKind(); - switch(DK) { + switch (DK) { #define DECL(NAME, BASE) -#define DECL_CONTEXT(NAME) \ - case Decl::NAME: \ - return static_cast(const_cast(D)); +#define DECL_CONTEXT(NAME) \ + case Decl::NAME: \ + return static_cast(const_cast(D)); #define DECL_CONTEXT_BASE(NAME) #include "clang/AST/DeclNodes.inc" - default: + default: #define DECL(NAME, BASE) -#define DECL_CONTEXT_BASE(NAME) \ - if (DK >= first##NAME && DK <= last##NAME) \ - return static_cast(const_cast(D)); +#define DECL_CONTEXT_BASE(NAME) \ + if (DK >= first##NAME && DK <= last##NAME) \ + return static_cast(const_cast(D)); #include "clang/AST/DeclNodes.inc" - llvm_unreachable("a decl that inherits DeclContext isn't handled"); + llvm_unreachable("a decl that inherits DeclContext isn't handled"); } } SourceLocation Decl::getBodyRBrace() const { // Special handling of FunctionDecl to avoid de-serializing the body from PCH. // FunctionDecl stores EndRangeLoc for this purpose. - if (const auto *FD = dyn_cast(this)) { - const FunctionDecl *Definition; + if (auto const *FD = dyn_cast(this)) { + FunctionDecl const *Definition; if (FD->hasBody(Definition)) return Definition->getSourceRange().getEnd(); return {}; @@ -995,18 +993,18 @@ return true; } -static Decl::Kind getKind(const Decl *D) { return D->getKind(); } -static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); } +static Decl::Kind getKind(Decl const *D) { return D->getKind(); } +static Decl::Kind getKind(DeclContext const *DC) { return DC->getDeclKind(); } int64_t Decl::getID() const { return getASTContext().getAllocator().identifyKnownAlignedObject(this); } -const FunctionType *Decl::getFunctionType(bool BlocksToo) const { +FunctionType const *Decl::getFunctionType(bool BlocksToo) const { QualType Ty; - if (const auto *D = dyn_cast(this)) + if (auto const *D = dyn_cast(this)) Ty = D->getType(); - else if (const auto *D = dyn_cast(this)) + else if (auto const *D = dyn_cast(this)) Ty = D->getUnderlyingType(); else return nullptr; @@ -1026,8 +1024,7 @@ template static Decl *getNonClosureContext(T *D) { if (getKind(D) == Decl::CXXMethod) { auto *MD = cast(D); - if (MD->getOverloadedOperator() == OO_Call && - MD->getParent()->isLambda()) + if (MD->getOverloadedOperator() == OO_Call && MD->getParent()->isLambda()) return getNonClosureContext(MD->getParent()->getParent()); return MD; } @@ -1042,9 +1039,7 @@ return nullptr; } -Decl *Decl::getNonClosureContext() { - return ::getNonClosureContext(this); -} +Decl *Decl::getNonClosureContext() { return ::getNonClosureContext(this); } Decl *DeclContext::getNonClosureAncestor() { return ::getNonClosureContext(this); @@ -1064,21 +1059,20 @@ setUseQualifiedLookup(false); } -bool DeclContext::classof(const Decl *D) { +bool DeclContext::classof(Decl const *D) { switch (D->getKind()) { #define DECL(NAME, BASE) #define DECL_CONTEXT(NAME) case Decl::NAME: #define DECL_CONTEXT_BASE(NAME) #include "clang/AST/DeclNodes.inc" - return true; - default: + return true; + default: #define DECL(NAME, BASE) -#define DECL_CONTEXT_BASE(NAME) \ - if (D->getKind() >= Decl::first##NAME && \ - D->getKind() <= Decl::last##NAME) \ - return true; +#define DECL_CONTEXT_BASE(NAME) \ + if (D->getKind() >= Decl::first##NAME && D->getKind() <= Decl::last##NAME) \ + return true; #include "clang/AST/DeclNodes.inc" - return false; + return false; } } @@ -1106,8 +1100,8 @@ return getParent(); } -const BlockDecl *DeclContext::getInnermostBlockDecl() const { - const DeclContext *Ctx = this; +BlockDecl const *DeclContext::getInnermostBlockDecl() const { + DeclContext const *Ctx = this; do { if (Ctx->isClosure()) @@ -1119,15 +1113,14 @@ } bool DeclContext::isInlineNamespace() const { - return isNamespace() && - cast(this)->isInline(); + return isNamespace() && cast(this)->isInline(); } bool DeclContext::isStdNamespace() const { if (!isNamespace()) return false; - const auto *ND = cast(this); + auto const *ND = cast(this); if (ND->isInline()) { return ND->getParent()->isStdNamespace(); } @@ -1135,7 +1128,7 @@ if (!getParent()->getRedeclContext()->isTranslationUnit()) return false; - const IdentifierInfo *II = ND->getIdentifier(); + IdentifierInfo const *II = ND->getIdentifier(); return II && II->isStr("std"); } @@ -1146,7 +1139,7 @@ if (isa(this)) return true; - if (const auto *Record = dyn_cast(this)) { + if (auto const *Record = dyn_cast(this)) { if (Record->getDescribedClassTemplate()) return true; @@ -1154,7 +1147,7 @@ return true; } - if (const auto *Function = dyn_cast(this)) { + if (auto const *Function = dyn_cast(this)) { if (Function->getDescribedFunctionTemplate()) return true; @@ -1178,7 +1171,7 @@ return getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export; } -static bool isLinkageSpecContext(const DeclContext *DC, +static bool isLinkageSpecContext(DeclContext const *DC, LinkageSpecDecl::LanguageIDs ID) { while (DC->getDeclKind() != Decl::TranslationUnit) { if (DC->getDeclKind() == Decl::LinkageSpec) @@ -1192,8 +1185,8 @@ return isLinkageSpecContext(this, LinkageSpecDecl::lang_c); } -const LinkageSpecDecl *DeclContext::getExternCContext() const { - const DeclContext *DC = this; +LinkageSpecDecl const *DeclContext::getExternCContext() const { + DeclContext const *DC = this; while (DC->getDeclKind() != Decl::TranslationUnit) { if (DC->getDeclKind() == Decl::LinkageSpec && cast(DC)->getLanguage() == LinkageSpecDecl::lang_c) @@ -1207,7 +1200,7 @@ return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx); } -bool DeclContext::Encloses(const DeclContext *DC) const { +bool DeclContext::Encloses(DeclContext const *DC) const { if (getPrimaryContext() != this) return getPrimaryContext()->Encloses(DC); @@ -1276,7 +1269,7 @@ if (TagDecl *Def = Tag->getDefinition()) return Def; - if (const auto *TagTy = dyn_cast(Tag->getTypeForDecl())) { + if (auto const *TagTy = dyn_cast(Tag->getTypeForDecl())) { // Note, TagType::getDecl returns the (partial) definition one exists. TagDecl *PossiblePartialDef = TagTy->getDecl(); if (PossiblePartialDef->isBeingDefined()) @@ -1289,8 +1282,7 @@ } assert(getDeclKind() >= Decl::firstFunction && - getDeclKind() <= Decl::lastFunction && - "Unknown DeclContext kind"); + getDeclKind() <= Decl::lastFunction && "Unknown DeclContext kind"); return this; } } @@ -1317,8 +1309,7 @@ } std::pair -DeclContext::BuildDeclChain(ArrayRef Decls, - bool FieldsAlreadyLoaded) { +DeclContext::BuildDeclChain(ArrayRef Decls, bool FieldsAlreadyLoaded) { // Build up a chain of declarations via the Decl::NextInContextAndBits field. Decl *FirstNewDecl = nullptr; Decl *PrevDecl = nullptr; @@ -1351,8 +1342,7 @@ /// Load the declarations within this lexical storage from an /// external source. /// \return \c true if any declarations were added. -bool -DeclContext::LoadLexicalDeclsFromExternalStorage() const { +bool DeclContext::LoadLexicalDeclsFromExternalStorage() const { ExternalASTSource *Source = getParentASTContext().getExternalSource(); assert(hasExternalLexicalStorage() && Source && "No external storage?"); @@ -1360,7 +1350,7 @@ ExternalASTSource::Deserializing ADeclContext(Source); // Load the external declarations, if any. - SmallVector Decls; + SmallVector Decls; setHasExternalLexicalStorage(false); Source->FindExternalLexicalDecls(this, Decls); @@ -1370,7 +1360,7 @@ // We may have already loaded just the fields of this record, in which case // we need to ignore them. bool FieldsAlreadyLoaded = false; - if (const auto *RD = dyn_cast(this)) + if (auto const *RD = dyn_cast(this)) FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage(); // Splice the newly-read declarations into the beginning of the list @@ -1386,7 +1376,7 @@ } DeclContext::lookup_result -ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, +ExternalASTSource::SetNoExternalVisibleDeclsForName(DeclContext const *DC, DeclarationName Name) { ASTContext &Context = DC->getParentASTContext(); StoredDeclsMap *Map; @@ -1400,10 +1390,8 @@ return DeclContext::lookup_result(); } -DeclContext::lookup_result -ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, - DeclarationName Name, - ArrayRef Decls) { +DeclContext::lookup_result ExternalASTSource::SetExternalVisibleDeclsForName( + DeclContext const *DC, DeclarationName Name, ArrayRef Decls) { ASTContext &Context = DC->getParentASTContext(); StoredDeclsMap *Map; if (!(Map = DC->LookupPtr)) @@ -1495,8 +1483,10 @@ for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) { assert(I && "decl not found in linked list"); if (I->NextInContextAndBits.getPointer() == D) { - I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer()); - if (D == LastDecl) LastDecl = I; + I->NextInContextAndBits.setPointer( + D->NextInContextAndBits.getPointer()); + if (D == LastDecl) + LastDecl = I; break; } } @@ -1560,16 +1550,18 @@ addHiddenDecl(D); if (auto *ND = dyn_cast(D)) - ND->getDeclContext()->getPrimaryContext()-> - makeDeclVisibleInContextWithFlags(ND, false, true); + ND->getDeclContext() + ->getPrimaryContext() + ->makeDeclVisibleInContextWithFlags(ND, false, true); } void DeclContext::addDeclInternal(Decl *D) { addHiddenDecl(D); if (auto *ND = dyn_cast(D)) - ND->getDeclContext()->getPrimaryContext()-> - makeDeclVisibleInContextWithFlags(ND, true, true); + ND->getDeclContext() + ->getPrimaryContext() + ->makeDeclVisibleInContextWithFlags(ND, true, true); } /// buildLookup - Build the lookup data structure with all of the @@ -1582,8 +1574,7 @@ StoredDeclsMap *DeclContext::buildLookup() { assert(this == getPrimaryContext() && "buildLookup called on non-primary DC"); - if (!hasLazyLocalLexicalLookups() && - !hasLazyExternalLexicalLookups()) + if (!hasLazyLocalLexicalLookups() && !hasLazyExternalLexicalLookups()) return LookupPtr; SmallVector Contexts; @@ -1594,8 +1585,8 @@ for (auto *DC : Contexts) { if (DC->hasExternalLexicalStorage()) { bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage(); - setHasLazyLocalLexicalLookups( - hasLazyLocalLexicalLookups() | LoadedDecls ); + setHasLazyLocalLexicalLookups(hasLazyLocalLexicalLookups() | + LoadedDecls); } } @@ -1641,13 +1632,11 @@ } } -DeclContext::lookup_result -DeclContext::lookup(DeclarationName Name) const { - assert(getDeclKind() != Decl::LinkageSpec && - getDeclKind() != Decl::Export && +DeclContext::lookup_result DeclContext::lookup(DeclarationName Name) const { + assert(getDeclKind() != Decl::LinkageSpec && getDeclKind() != Decl::Export && "should not perform lookups into transparent contexts"); - const DeclContext *PrimaryContext = getPrimaryContext(); + DeclContext const *PrimaryContext = getPrimaryContext(); if (PrimaryContext != this) return PrimaryContext->lookup(Name); @@ -1666,10 +1655,9 @@ StoredDeclsMap *Map = LookupPtr; - if (hasLazyLocalLexicalLookups() || - hasLazyExternalLexicalLookups()) + if (hasLazyLocalLexicalLookups() || hasLazyExternalLexicalLookups()) // FIXME: Make buildLookup const? - Map = const_cast(this)->buildLookup(); + Map = const_cast(this)->buildLookup(); if (!Map) Map = CreateStoredDeclsMap(getParentASTContext()); @@ -1692,9 +1680,8 @@ } StoredDeclsMap *Map = LookupPtr; - if (hasLazyLocalLexicalLookups() || - hasLazyExternalLexicalLookups()) - Map = const_cast(this)->buildLookup(); + if (hasLazyLocalLexicalLookups() || hasLazyExternalLexicalLookups()) + Map = const_cast(this)->buildLookup(); if (!Map) return {}; @@ -1706,10 +1693,8 @@ return I->second.getLookupResult(); } -DeclContext::lookup_result -DeclContext::noload_lookup(DeclarationName Name) { - assert(getDeclKind() != Decl::LinkageSpec && - getDeclKind() != Decl::Export && +DeclContext::lookup_result DeclContext::noload_lookup(DeclarationName Name) { + assert(getDeclKind() != Decl::LinkageSpec && getDeclKind() != Decl::Export && "should not perform lookups into transparent contexts"); DeclContext *PrimaryContext = getPrimaryContext(); @@ -1722,8 +1707,7 @@ return {}; StoredDeclsMap::iterator I = Map->find(Name); - return I != Map->end() ? I->second.getLookupResult() - : lookup_result(); + return I != Map->end() ? I->second.getLookupResult() : lookup_result(); } // If we have any lazy lexical declarations not in our lookup map, add them @@ -1758,8 +1742,7 @@ if (StoredDeclsMap *Map = LookupPtr) { StoredDeclsMap::iterator Pos = Map->find(Name); if (Pos != Map->end()) { - Results.insert(Results.end(), - Pos->second.getLookupResult().begin(), + Results.insert(Results.end(), Pos->second.getLookupResult().begin(), Pos->second.getLookupResult().end()); return; } @@ -1814,7 +1797,7 @@ return OutermostRD; } -bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { +bool DeclContext::InEnclosingNamespaceSetOf(DeclContext const *O) const { // For non-file contexts, this is equivalent to Equals. if (!isFileContext()) return O->Equals(this); @@ -1823,7 +1806,7 @@ if (O->Equals(this)) return true; - const auto *NS = dyn_cast(O); + auto const *NS = dyn_cast(O); if (!NS || !NS->isInline()) break; O = NS->getParent(); @@ -1846,8 +1829,8 @@ if (!isLookupContext()) { if (isTransparentContext()) - getParent()->getPrimaryContext() - ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); + getParent()->getPrimaryContext()->makeDeclVisibleInContextWithFlags( + D, Internal, Recoverable); return; } @@ -1879,8 +1862,8 @@ // If we are a transparent context or inline namespace, insert into our // parent context, too. This operation is recursive. if (isTransparentContext() || isInlineNamespace()) - getParent()->getPrimaryContext()-> - makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); + getParent()->getPrimaryContext()->makeDeclVisibleInContextWithFlags( + D, Internal, Recoverable); auto *DCAsDecl = cast(this); // Notify that a decl was made visible unless we are a Tag being defined. @@ -1952,7 +1935,7 @@ else M = new StoredDeclsMap(); M->Previous = C.LastSDM; - C.LastSDM = llvm::PointerIntPair(M, Dependent); + C.LastSDM = llvm::PointerIntPair(M, Dependent); LookupPtr = M; return M; } @@ -1967,10 +1950,10 @@ void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { while (Map) { // Advance the iteration before we invalidate memory. - llvm::PointerIntPair Next = Map->Previous; + llvm::PointerIntPair Next = Map->Previous; if (Dependent) - delete static_cast(Map); + delete static_cast(Map); else delete Map; @@ -1979,11 +1962,11 @@ } } -DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, - DeclContext *Parent, - const PartialDiagnostic &PDiag) { - assert(Parent->isDependentContext() - && "cannot iterate dependent diagnostics of non-dependent context"); +DependentDiagnostic * +DependentDiagnostic::Create(ASTContext &C, DeclContext *Parent, + PartialDiagnostic const &PDiag) { + assert(Parent->isDependentContext() && + "cannot iterate dependent diagnostics of non-dependent context"); Parent = Parent->getPrimaryContext(); if (!Parent->LookupPtr) Parent->CreateStoredDeclsMap(C); Index: clang/lib/AST/DeclCXX.cpp =================================================================== --- clang/lib/AST/DeclCXX.cpp +++ clang/lib/AST/DeclCXX.cpp @@ -81,8 +81,7 @@ HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false), HasOnlyCMembers(true), HasInClassInitializer(false), HasUninitializedReferenceMember(false), HasUninitializedFields(false), - HasInheritedConstructor(false), - HasInheritedDefaultConstructor(false), + HasInheritedConstructor(false), HasInheritedDefaultConstructor(false), HasInheritedAssignment(false), NeedOverloadResolutionForCopyConstructor(false), NeedOverloadResolutionForMoveConstructor(false), @@ -121,21 +120,20 @@ return VBases.get(Definition->getASTContext().getExternalSource()); } -CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, +CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, ASTContext const &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl) : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl), - DefinitionData(PrevDecl ? PrevDecl->DefinitionData - : nullptr) {} + DefinitionData(PrevDecl ? PrevDecl->DefinitionData : nullptr) {} -CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK, +CXXRecordDecl *CXXRecordDecl::Create(ASTContext const &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl, bool DelayTypeCreation) { - auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id, - PrevDecl); + auto *R = new (C, DC) + CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl); R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); // FIXME: DelayTypeCreation seems like such a hack @@ -145,27 +143,26 @@ } CXXRecordDecl * -CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC, +CXXRecordDecl::CreateLambda(ASTContext const &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, bool Dependent, bool IsGeneric, LambdaCaptureDefault CaptureDefault) { - auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TTK_Class, C, DC, Loc, Loc, - nullptr, nullptr); + auto *R = new (C, DC) + CXXRecordDecl(CXXRecord, TTK_Class, C, DC, Loc, Loc, nullptr, nullptr); R->setBeingDefined(true); - R->DefinitionData = - new (C) struct LambdaDefinitionData(R, Info, Dependent, IsGeneric, - CaptureDefault); + R->DefinitionData = new (C) struct LambdaDefinitionData( + R, Info, Dependent, IsGeneric, CaptureDefault); R->setMayHaveOutOfDateDef(false); R->setImplicit(true); C.getTypeDeclType(R, /*PrevDecl=*/nullptr); return R; } -CXXRecordDecl * -CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { - auto *R = new (C, ID) CXXRecordDecl( - CXXRecord, TTK_Struct, C, nullptr, SourceLocation(), SourceLocation(), - nullptr, nullptr); +CXXRecordDecl *CXXRecordDecl::CreateDeserialized(ASTContext const &C, + unsigned ID) { + auto *R = new (C, ID) + CXXRecordDecl(CXXRecord, TTK_Struct, C, nullptr, SourceLocation(), + SourceLocation(), nullptr, nullptr); R->setMayHaveOutOfDateDef(false); return R; } @@ -173,13 +170,13 @@ /// Determine whether a class has a repeated base class. This is intended for /// use when determining if a class is standard-layout, so makes no attempt to /// handle virtual bases. -static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) { - llvm::SmallPtrSet SeenBaseTypes; - SmallVector WorkList = {StartRD}; +static bool hasRepeatedBaseClass(CXXRecordDecl const *StartRD) { + llvm::SmallPtrSet SeenBaseTypes; + SmallVector WorkList = {StartRD}; while (!WorkList.empty()) { - const CXXRecordDecl *RD = WorkList.pop_back_val(); - for (const CXXBaseSpecifier &BaseSpec : RD->bases()) { - if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) { + CXXRecordDecl const *RD = WorkList.pop_back_val(); + for (CXXBaseSpecifier const &BaseSpec : RD->bases()) { + if (CXXRecordDecl const *B = BaseSpec.getType()->getAsCXXRecordDecl()) { if (!SeenBaseTypes.insert(B).second) return true; WorkList.push_back(B); @@ -189,9 +186,8 @@ return false; } -void -CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, - unsigned NumBases) { +void CXXRecordDecl::setBases(CXXBaseSpecifier const *const *Bases, + unsigned NumBases) { ASTContext &C = getASTContext(); if (!data().Bases.isOffset() && data().NumBases > 0) @@ -213,14 +209,14 @@ llvm::SmallPtrSet SeenVBaseTypes; // The virtual bases of this class. - SmallVector VBases; + SmallVector VBases; - data().Bases = new(C) CXXBaseSpecifier [NumBases]; + data().Bases = new (C) CXXBaseSpecifier[NumBases]; data().NumBases = NumBases; for (unsigned i = 0; i < NumBases; ++i) { data().getBases()[i] = *Bases[i]; // Keep track of inherited vbases for this base class. - const CXXBaseSpecifier *Base = Bases[i]; + CXXBaseSpecifier const *Base = Bases[i]; QualType BaseType = Base->getType(); // Skip dependent types; we can't do any checking on them now. if (BaseType->isDependentType()) @@ -293,7 +289,7 @@ data().HasNonLiteralTypeFieldsOrBases = true; // Now go through all virtual bases of this base and add them. - for (const auto &VBase : BaseClassDecl->vbases()) { + for (auto const &VBase : BaseClassDecl->vbases()) { // Add this base if it's not already in the list. if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) { VBases.push_back(&VBase); @@ -328,8 +324,8 @@ data().Aggregate = false; // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: - // A [default constructor, copy/move constructor, or copy/move assignment - // operator for a class X] is trivial [...] if: + // A [default constructor, copy/move constructor, or copy/move + // assignment operator for a class X] is trivial [...] if: // -- class X has [...] no virtual base classes data().HasTrivialSpecialMembers &= SMF_Destructor; data().HasTrivialSpecialMembersForCall &= SMF_Destructor; @@ -566,22 +562,27 @@ if (!isDependentContext()) return false; - return !forallBases([](const CXXRecordDecl *) { return true; }); + return !forallBases([](CXXRecordDecl const *) { return true; }); } bool CXXRecordDecl::isTriviallyCopyable() const { // C++0x [class]p5: // A trivially copyable class is a class that: // -- has no non-trivial copy constructors, - if (hasNonTrivialCopyConstructor()) return false; + if (hasNonTrivialCopyConstructor()) + return false; // -- has no non-trivial move constructors, - if (hasNonTrivialMoveConstructor()) return false; + if (hasNonTrivialMoveConstructor()) + return false; // -- has no non-trivial copy assignment operators, - if (hasNonTrivialCopyAssignment()) return false; + if (hasNonTrivialCopyAssignment()) + return false; // -- has no non-trivial move assignment operators, and - if (hasNonTrivialMoveAssignment()) return false; + if (hasNonTrivialMoveAssignment()) + return false; // -- has a trivial destructor. - if (!hasTrivialDestructor()) return false; + if (!hasTrivialDestructor()) + return false; return true; } @@ -593,16 +594,16 @@ } bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType( - ASTContext &Ctx, const CXXRecordDecl *XFirst) { + ASTContext &Ctx, CXXRecordDecl const *XFirst) { if (!getNumBases()) return false; - llvm::SmallPtrSet Bases; - llvm::SmallPtrSet M; - SmallVector WorkList; + llvm::SmallPtrSet Bases; + llvm::SmallPtrSet M; + SmallVector WorkList; // Visit a type that we have determined is an element of M(S). - auto Visit = [&](const CXXRecordDecl *RD) -> bool { + auto Visit = [&](CXXRecordDecl const *RD) -> bool { RD = RD->getCanonicalDecl(); // C++2a [class]p8: @@ -639,7 +640,7 @@ return true; while (!WorkList.empty()) { - const CXXRecordDecl *X = WorkList.pop_back_val(); + CXXRecordDecl const *X = WorkList.pop_back_val(); // FIXME: We don't check the bases of X. That matches the standard, but // that sure looks like a wording bug. @@ -691,11 +692,9 @@ } void CXXRecordDecl::addedMember(Decl *D) { - if (!D->isImplicit() && - !isa(D) && - !isa(D) && + if (!D->isImplicit() && !isa(D) && !isa(D) && (!isa(D) || cast(D)->getTagKind() == TTK_Class || - cast(D)->getTagKind() == TTK_Interface)) + cast(D)->getTagKind() == TTK_Interface)) data().HasOnlyCMembers = false; // Ignore friends and invalid declarations. @@ -714,7 +713,7 @@ DUnderlying = UnderlyingFunTmpl->getTemplatedDecl(); } - if (const auto *Method = dyn_cast(D)) { + if (auto const *Method = dyn_cast(D)) { if (Method->isVirtual()) { // C++ [dcl.init.aggr]p1: // An aggregate is an array or a class with [...] no virtual functions. @@ -758,7 +757,7 @@ unsigned SMKind = 0; // Handle constructors. - if (const auto *Constructor = dyn_cast(D)) { + if (auto const *Constructor = dyn_cast(D)) { if (Constructor->isInheritingConstructor()) { // Ignore constructor shadow declarations. They are lazily created and // so shouldn't affect any properties of the class. @@ -811,7 +810,7 @@ } // Handle constructors, including those inherited from base classes. - if (const auto *Constructor = dyn_cast(DUnderlying)) { + if (auto const *Constructor = dyn_cast(DUnderlying)) { // Record if we see any constexpr constructors which are neither copy // nor move constructors. // C++1z [basic.types]p10: @@ -825,7 +824,7 @@ } // Handle destructors. - if (const auto *DD = dyn_cast(D)) { + if (auto const *DD = dyn_cast(D)) { SMKind |= SMF_Destructor; if (DD->isUserProvided()) @@ -846,11 +845,11 @@ } // Handle member functions. - if (const auto *Method = dyn_cast(D)) { + if (auto const *Method = dyn_cast(D)) { if (Method->isCopyAssignmentOperator()) { SMKind |= SMF_CopyAssignment; - const auto *ParamTy = + auto const *ParamTy = Method->getParamDecl(0)->getType()->getAs(); if (!ParamTy || ParamTy->getPointeeType().isConstQualified()) data().HasDeclaredCopyAssignmentWithConstParam = true; @@ -939,7 +938,7 @@ } // Handle non-static data members. - if (const auto *Field = dyn_cast(D)) { + if (auto const *Field = dyn_cast(D)) { ASTContext &Context = getASTContext(); // C++2a [class]p7: @@ -997,10 +996,17 @@ // [...] // -- has the same access control for all non-static data members, switch (D->getAccess()) { - case AS_private: data().HasPrivateFields = true; break; - case AS_protected: data().HasProtectedFields = true; break; - case AS_public: data().HasPublicFields = true; break; - case AS_none: llvm_unreachable("Invalid access specifier"); + case AS_private: + data().HasPrivateFields = true; + break; + case AS_protected: + data().HasProtectedFields = true; + break; + case AS_public: + data().HasPublicFields = true; + break; + case AS_none: + llvm_unreachable("Invalid access specifier"); }; if ((data().HasPrivateFields + data().HasProtectedFields + data().HasPublicFields) > 1) { @@ -1029,8 +1035,9 @@ // standard-layout class, and has no non-static data members of type // non-POD struct, non-POD union (or array of such types). // - // Automatic Reference Counting: the presence of a member of Objective-C pointer type - // that does not explicitly have no lifetime makes the class a non-POD. + // Automatic Reference Counting: the presence of a member of Objective-C + // pointer type that does not explicitly have no lifetime makes the class a + // non-POD. QualType T = Context.getBaseElementType(Field->getType()); if (T->isObjCRetainableType() || T.isObjCGCStrong()) { if (T.hasNonTrivialObjCLifetime()) { @@ -1038,8 +1045,8 @@ // If a class has a non-static data member of Objective-C pointer // type (or array thereof), it is a non-POD type and its // default constructor (if any), copy constructor, move constructor, - // copy assignment operator, move assignment operator, and destructor are - // non-trivial. + // copy assignment operator, move assignment operator, and destructor + // are non-trivial. setHasObjectMember(true); struct DefinitionData &Data = data(); Data.PlainOldData = false; @@ -1086,7 +1093,8 @@ data().IsCXX11StandardLayout = false; // C++1z [class.copy.ctor]p10: - // A defaulted copy constructor for a class X is defined as deleted if X has: + // A defaulted copy constructor for a class X is defined as deleted if X + // has: // -- a non-static data member of rvalue reference type if (T->isRValueReferenceType()) data().DefaultedCopyConstructorIsDeleted = true; @@ -1141,7 +1149,7 @@ // those because they are always unnamed. bool IsZeroSize = Field->isZeroSize(Context); - if (const auto *RecordTy = T->getAs()) { + if (auto const *RecordTy = T->getAs()) { auto *FieldRec = cast(RecordTy->getDecl()); if (FieldRec->getDefinition()) { addedClassSubobject(FieldRec); @@ -1275,7 +1283,7 @@ if (data().IsCXX11StandardLayout && IsFirstField) { // FIXME: We should check all base classes here, not just direct // base classes. - for (const auto &BI : bases()) { + for (auto const &BI : bases()) { if (Context.hasSameUnqualifiedType(BI.getType(), T)) { data().IsCXX11StandardLayout = false; break; @@ -1332,8 +1340,7 @@ // C++11 [class.union]p8, DR1460: // a non-static data member of an anonymous union that is a member of // X is also a variant member of X. - if (FieldRec->hasVariantMembers() && - Field->isAnonymousStructOrUnion()) + if (FieldRec->hasVariantMembers() && Field->isAnonymousStructOrUnion()) data().HasVariantMembers = true; } } else { @@ -1371,14 +1378,14 @@ // Handle using declarations of conversion functions. if (auto *Shadow = dyn_cast(D)) { - if (Shadow->getDeclName().getNameKind() - == DeclarationName::CXXConversionFunctionName) { + if (Shadow->getDeclName().getNameKind() == + DeclarationName::CXXConversionFunctionName) { ASTContext &Ctx = getASTContext(); data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess()); } } - if (const auto *Using = dyn_cast(D)) { + if (auto const *Using = dyn_cast(D)) { if (Using->getDeclName().getNameKind() == DeclarationName::CXXConstructorName) { data().HasInheritedConstructor = true; @@ -1398,7 +1405,7 @@ // The kind of special member this declaration is, if any. unsigned SMKind = 0; - if (const auto *Constructor = dyn_cast(D)) { + if (auto const *Constructor = dyn_cast(D)) { if (Constructor->isDefaultConstructor()) { SMKind |= SMF_DefaultConstructor; if (Constructor->isConstexpr()) @@ -1452,7 +1459,7 @@ void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) { unsigned SMKind = 0; - if (const auto *Constructor = dyn_cast(D)) { + if (auto const *Constructor = dyn_cast(D)) { if (Constructor->isCopyConstructor()) SMKind = SMF_CopyConstructor; else if (Constructor->isMoveConstructor()) @@ -1477,12 +1484,13 @@ } bool CXXRecordDecl::isGenericLambda() const { - if (!isLambda()) return false; + if (!isLambda()) + return false; return getLambdaData().IsGenericLambda; } #ifndef NDEBUG -static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) { +static bool allLookupResultsAreTheSame(DeclContext::lookup_result const &R) { for (auto *D : R) if (!declaresSameEntity(D, R.front())) return false; @@ -1490,10 +1498,11 @@ } #endif -static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) { - if (!RD.isLambda()) return nullptr; +static NamedDecl *getLambdaCallOperatorHelper(CXXRecordDecl const &RD) { + if (!RD.isLambda()) + return nullptr; DeclarationName Name = - RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); + RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); DeclContext::lookup_result Calls = RD.lookup(Name); assert(!Calls.empty() && "Missing lambda call operator!"); @@ -1502,9 +1511,9 @@ return Calls.front(); } -FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const { +FunctionTemplateDecl *CXXRecordDecl::getDependentLambdaCallOperator() const { NamedDecl *CallOp = getLambdaCallOperatorHelper(*this); - return dyn_cast_or_null(CallOp); + return dyn_cast_or_null(CallOp); } CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const { @@ -1513,20 +1522,20 @@ if (CallOp == nullptr) return nullptr; - if (const auto *CallOpTmpl = dyn_cast(CallOp)) + if (auto const *CallOpTmpl = dyn_cast(CallOp)) return cast(CallOpTmpl->getTemplatedDecl()); return cast(CallOp); } -CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const { +CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker() const { CXXMethodDecl *CallOp = getLambdaCallOperator(); CallingConv CC = CallOp->getType()->castAs()->getCallConv(); return getLambdaStaticInvoker(CC); } static DeclContext::lookup_result -getLambdaStaticInvokers(const CXXRecordDecl &RD) { +getLambdaStaticInvokers(CXXRecordDecl const &RD) { assert(RD.isLambda() && "Must be a lambda"); DeclarationName Name = &RD.getASTContext().Idents.get(getLambdaStaticInvokerName()); @@ -1534,7 +1543,7 @@ } static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) { - if (const auto *InvokerTemplate = dyn_cast(ND)) + if (auto const *InvokerTemplate = dyn_cast(ND)) return cast(InvokerTemplate->getTemplatedDecl()); return cast(ND); } @@ -1545,7 +1554,7 @@ DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this); for (NamedDecl *ND : Invoker) { - const auto *FTy = + auto const *FTy = cast(ND->getAsFunction())->getType()->castAs(); if (FTy->getCallConv() == CC) return getInvokerAsMethod(ND); @@ -1555,14 +1564,14 @@ } void CXXRecordDecl::getCaptureFields( - llvm::DenseMap &Captures, - FieldDecl *&ThisCapture) const { + llvm::DenseMap &Captures, + FieldDecl *&ThisCapture) const { Captures.clear(); ThisCapture = nullptr; LambdaDefinitionData &Lambda = getLambdaData(); RecordDecl::field_iterator Field = field_begin(); - for (const LambdaCapture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures; + for (LambdaCapture const *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures; C != CEnd; ++C, ++Field) { if (C->capturesThis()) ThisCapture = *Field; @@ -1574,7 +1583,8 @@ TemplateParameterList * CXXRecordDecl::getGenericLambdaTemplateParameterList() const { - if (!isGenericLambda()) return nullptr; + if (!isGenericLambda()) + return nullptr; CXXMethodDecl *CallOp = getLambdaCallOperator(); if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate()) return Tmpl->getTemplateParameters(); @@ -1587,12 +1597,13 @@ if (!List) return {}; - assert(std::is_partitioned(List->begin(), List->end(), - [](const NamedDecl *D) { return !D->isImplicit(); }) - && "Explicit template params should be ordered before implicit ones"); + assert(std::is_partitioned( + List->begin(), List->end(), + [](NamedDecl const *D) { return !D->isImplicit(); }) && + "Explicit template params should be ordered before implicit ones"); - const auto ExplicitEnd = llvm::partition_point( - *List, [](const NamedDecl *D) { return !D->isImplicit(); }); + auto const ExplicitEnd = llvm::partition_point( + *List, [](NamedDecl const *D) { return !D->isImplicit(); }); return llvm::makeArrayRef(List->begin(), ExplicitEnd); } @@ -1636,15 +1647,15 @@ /// \param HiddenVBaseCs the set of conversions which were hidden in a /// virtual base along some inheritance path static void CollectVisibleConversions( - ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual, + ASTContext &Context, CXXRecordDecl const *Record, bool InVirtual, AccessSpecifier Access, - const llvm::SmallPtrSet &ParentHiddenTypes, + llvm::SmallPtrSet const &ParentHiddenTypes, ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput, llvm::SmallPtrSet &HiddenVBaseCs) { // The set of types which have conversions in this class or its // subclasses. As an optimization, we don't copy the derived set // unless it might change. - const llvm::SmallPtrSet *HiddenTypes = &ParentHiddenTypes; + llvm::SmallPtrSet const *HiddenTypes = &ParentHiddenTypes; llvm::SmallPtrSet HiddenTypesBuffer; // Collect the direct conversions and figure out which conversions @@ -1668,8 +1679,8 @@ // If this conversion isn't hidden, add it to the appropriate output. else if (!Hidden) { - AccessSpecifier IAccess - = CXXRecordDecl::MergeAccess(Access, I.getAccess()); + AccessSpecifier IAccess = + CXXRecordDecl::MergeAccess(Access, I.getAccess()); if (InVirtual) VOutput.addDecl(I.getDecl(), IAccess); @@ -1680,12 +1691,13 @@ } // Collect information recursively from any base classes. - for (const auto &I : Record->bases()) { - const auto *RT = I.getType()->getAs(); - if (!RT) continue; + for (auto const &I : Record->bases()) { + auto const *RT = I.getType()->getAs(); + if (!RT) + continue; - AccessSpecifier BaseAccess - = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier()); + AccessSpecifier BaseAccess = + CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier()); bool BaseInVirtual = InVirtual || I.isVirtual(); auto *Base = cast(RT->getDecl()); @@ -1699,7 +1711,7 @@ /// This would be extremely straightforward if it weren't for virtual /// bases. It might be worth special-casing that, really. static void CollectVisibleConversions(ASTContext &Context, - const CXXRecordDecl *Record, + CXXRecordDecl const *Record, ASTUnresolvedSet &Output) { // The collection of all conversions in virtual bases that we've // found. These will be added to the output as long as they don't @@ -1708,7 +1720,7 @@ // The set of conversions in virtual bases that we've determined to // be hidden. - llvm::SmallPtrSet HiddenVBaseCs; + llvm::SmallPtrSet HiddenVBaseCs; // The set of types hidden by classes derived from this one. llvm::SmallPtrSet HiddenTypes; @@ -1722,9 +1734,10 @@ HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl())); // Recursively collect conversions from base classes. - for (const auto &I : Record->bases()) { - const auto *RT = I.getType()->getAs(); - if (!RT) continue; + for (auto const &I : Record->bases()) { + auto const *RT = I.getType()->getAs(); + if (!RT) + continue; CollectVisibleConversions(Context, cast(RT->getDecl()), I.isVirtual(), I.getAccessSpecifier(), @@ -1732,8 +1745,8 @@ } // Add any unhidden conversions provided by virtual bases. - for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end(); - I != E; ++I) { + for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end(); I != E; + ++I) { if (!HiddenVBaseCs.count(cast(I.getDecl()->getCanonicalDecl()))) Output.addDecl(Context, I.getDecl(), I.getAccess()); } @@ -1760,7 +1773,7 @@ return llvm::make_range(Set->begin(), Set->end()); } -void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) { +void CXXRecordDecl::removeConversion(NamedDecl const *ConvDecl) { // This operation is O(N) but extremely rare. Sema only uses it to // remove UsingShadowDecls in a class that were followed by a direct // declaration, e.g.: @@ -1796,14 +1809,13 @@ return TemplateOrInstantiation.dyn_cast(); } -void -CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD, - TemplateSpecializationKind TSK) { +void CXXRecordDecl::setInstantiationOfMemberClass( + CXXRecordDecl *RD, TemplateSpecializationKind TSK) { assert(TemplateOrInstantiation.isNull() && "Previous template or instantiation?"); assert(!isa(this)); - TemplateOrInstantiation - = new (getASTContext()) MemberSpecializationInfo(RD, TSK); + TemplateOrInstantiation = + new (getASTContext()) MemberSpecializationInfo(RD, TSK); } ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const { @@ -1814,8 +1826,9 @@ TemplateOrInstantiation = Template; } -TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{ - if (const auto *Spec = dyn_cast(this)) +TemplateSpecializationKind +CXXRecordDecl::getTemplateSpecializationKind() const { + if (auto const *Spec = dyn_cast(this)) return Spec->getSpecializationKind(); if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) @@ -1824,8 +1837,8 @@ return TSK_Undeclared; } -void -CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) { +void CXXRecordDecl::setTemplateSpecializationKind( + TemplateSpecializationKind TSK) { if (auto *Spec = dyn_cast(this)) { Spec->setSpecializationKind(TSK); return; @@ -1839,9 +1852,9 @@ llvm_unreachable("Not a class template or member class specialization"); } -const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const { +CXXRecordDecl const *CXXRecordDecl::getTemplateInstantiationPattern() const { auto GetDefinitionOrSelf = - [](const CXXRecordDecl *D) -> const CXXRecordDecl * { + [](CXXRecordDecl const *D) -> CXXRecordDecl const * { if (auto *Def = D->getDefinition()) return Def; return D; @@ -1872,7 +1885,7 @@ if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { - const CXXRecordDecl *RD = this; + CXXRecordDecl const *RD = this; while (auto *NewRD = RD->getInstantiatedFromMemberClass()) RD = NewRD; return GetDefinitionOrSelf(RD); @@ -1888,16 +1901,15 @@ ASTContext &Context = getASTContext(); QualType ClassType = Context.getTypeDeclType(this); - DeclarationName Name - = Context.DeclarationNames.getCXXDestructorName( - Context.getCanonicalType(ClassType)); + DeclarationName Name = Context.DeclarationNames.getCXXDestructorName( + Context.getCanonicalType(ClassType)); DeclContext::lookup_result R = lookup(Name); return R.empty() ? nullptr : dyn_cast(R.front()); } -static bool isDeclContextInNamespace(const DeclContext *DC) { +static bool isDeclContextInNamespace(DeclContext const *DC) { while (!DC->isTranslationUnit()) { if (DC->isNamespace()) return true; @@ -1921,12 +1933,12 @@ return false; // No interface-like type can have a method with a definition. - for (const auto *const Method : methods()) + for (auto const *const Method : methods()) if (Method->isDefined() && !Method->isImplicit()) return false; // Check "Special" types. - const auto *Uuid = getAttr(); + auto const *Uuid = getAttr(); // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an // extern C++ block directly in the TU. These are only valid if in one // of these two situations. @@ -1948,18 +1960,16 @@ if (getNumBases() != 1) return false; - const auto BaseSpec = *bases_begin(); + auto const BaseSpec = *bases_begin(); if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public) return false; - const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl(); + auto const *Base = BaseSpec.getType()->getAsCXXRecordDecl(); if (Base->isInterface() || !Base->isInterfaceLike()) return false; return true; } -void CXXRecordDecl::completeDefinition() { - completeDefinition(nullptr); -} +void CXXRecordDecl::completeDefinition() { completeDefinition(nullptr); } void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { RecordDecl::completeDefinition(); @@ -1975,10 +1985,10 @@ bool Done = false; for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), - MEnd = FinalOverriders->end(); + MEnd = FinalOverriders->end(); M != MEnd && !Done; ++M) { for (OverridingMethods::iterator SO = M->second.begin(), - SOEnd = M->second.end(); + SOEnd = M->second.end(); SO != SOEnd && !Done; ++SO) { assert(SO->second.size() > 0 && "All virtual functions have overriding virtual functions"); @@ -1997,8 +2007,8 @@ } // Set access bits correctly on the directly-declared conversions. - for (conversion_iterator I = conversion_begin(), E = conversion_end(); - I != E; ++I) + for (conversion_iterator I = conversion_begin(), E = conversion_end(); I != E; + ++I) I.setAccess((*I)->getAccess()); } @@ -2007,8 +2017,8 @@ isDependentContext()) return false; - for (const auto &B : bases()) { - const auto *BaseDecl = + for (auto const &B : bases()) { + auto const *BaseDecl = cast(B.getType()->castAs()->getDecl()); if (BaseDecl->isAbstract()) return true; @@ -2023,7 +2033,7 @@ return false; if (Def->hasAttr()) return true; - if (const auto *Dtor = Def->getDestructor()) + if (auto const *Dtor = Def->getDestructor()) if (Dtor->hasAttr()) return true; return false; @@ -2062,7 +2072,7 @@ CXXDeductionGuideDecl * CXXDeductionGuideDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, - const DeclarationNameInfo &NameInfo, QualType T, + DeclarationNameInfo const &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor) { return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T, @@ -2076,8 +2086,9 @@ QualType(), nullptr, SourceLocation(), nullptr); } -RequiresExprBodyDecl *RequiresExprBodyDecl::Create( - ASTContext &C, DeclContext *DC, SourceLocation StartLoc) { +RequiresExprBodyDecl *RequiresExprBodyDecl::Create(ASTContext &C, + DeclContext *DC, + SourceLocation StartLoc) { return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc); } @@ -2089,7 +2100,7 @@ void CXXMethodDecl::anchor() {} bool CXXMethodDecl::isStatic() const { - const CXXMethodDecl *MD = getCanonicalDecl(); + CXXMethodDecl const *MD = getCanonicalDecl(); if (MD->getStorageClass() == SC_Static) return true; @@ -2098,9 +2109,9 @@ return isStaticOverloadedOperator(OOK); } -static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD, - const CXXMethodDecl *BaseMD) { - for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) { +static bool recursivelyOverrides(CXXMethodDecl const *DerivedMD, + CXXMethodDecl const *BaseMD) { + for (CXXMethodDecl const *MD : DerivedMD->overridden_methods()) { if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl()) return true; if (recursivelyOverrides(MD, BaseMD)) @@ -2110,7 +2121,7 @@ } CXXMethodDecl * -CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, +CXXMethodDecl::getCorrespondingMethodDeclaredInClass(CXXRecordDecl const *RD, bool MayBeBase) { if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl()) return this; @@ -2141,12 +2152,12 @@ } CXXMethodDecl * -CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD, +CXXMethodDecl::getCorrespondingMethodInClass(CXXRecordDecl const *RD, bool MayBeBase) { if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase)) return MD; - llvm::SmallVector FinalOverriders; + llvm::SmallVector FinalOverriders; auto AddFinalOverrider = [&](CXXMethodDecl *D) { // If this function is overridden by a candidate final overrider, it is not // a final overrider. @@ -2166,11 +2177,11 @@ FinalOverriders.push_back(D); }; - for (const auto &I : RD->bases()) { - const RecordType *RT = I.getType()->getAs(); + for (auto const &I : RD->bases()) { + RecordType const *RT = I.getType()->getAs(); if (!RT) continue; - const auto *Base = cast(RT->getDecl()); + auto const *Base = cast(RT->getDecl()); if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base)) AddFinalOverrider(D); } @@ -2180,7 +2191,7 @@ CXXMethodDecl * CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, - const DeclarationNameInfo &NameInfo, QualType T, + DeclarationNameInfo const &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, @@ -2197,7 +2208,7 @@ ConstexprSpecKind::Unspecified, SourceLocation(), nullptr); } -CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base, +CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(Expr const *Base, bool IsAppleKext) { assert(isVirtual() && "this method is expected to be virtual"); @@ -2222,7 +2233,7 @@ return this; // If we don't even know what we would call, we can't devirtualize. - const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); + CXXRecordDecl const *BestDynamicDecl = Base->getBestDynamicClassType(); if (!BestDynamicDecl) return nullptr; @@ -2251,8 +2262,8 @@ if (BestDynamicDecl->isEffectivelyFinal()) return DevirtualizedMethod; - if (const auto *DRE = dyn_cast(Base)) { - if (const auto *VD = dyn_cast(DRE->getDecl())) + if (auto const *DRE = dyn_cast(Base)) { + if (auto const *VD = dyn_cast(DRE->getDecl())) if (VD->getType()->isRecordType()) // This is a record decl. We know the type and can devirtualize it. return DevirtualizedMethod; @@ -2263,8 +2274,8 @@ // We can devirtualize calls on an object accessed by a class member access // expression, since by C++11 [basic.life]p6 we know that it can't refer to // a derived class object constructed in the same location. - if (const auto *ME = dyn_cast(Base)) { - const ValueDecl *VD = ME->getMemberDecl(); + if (auto const *ME = dyn_cast(Base)) { + ValueDecl const *VD = ME->getMemberDecl(); return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr; } @@ -2283,7 +2294,7 @@ } bool CXXMethodDecl::isUsualDeallocationFunction( - SmallVectorImpl &PreventedBy) const { + SmallVectorImpl &PreventedBy) const { assert(PreventedBy.empty() && "PreventedBy is expected to be empty"); if (getOverloadedOperator() != OO_Delete && getOverloadedOperator() != OO_Array_Delete) @@ -2340,16 +2351,15 @@ // FIXME(EricWF): Destrying Delete should be a language option. How do we // handle when destroying delete is used prior to C++17? if (Context.getLangOpts().CPlusPlus17 || - Context.getLangOpts().AlignedAllocation || - isDestroyingOperatorDelete()) + Context.getLangOpts().AlignedAllocation || isDestroyingOperatorDelete()) return true; // This function is a usual deallocation function if there are no // single-parameter deallocation functions of the same kind. DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName()); bool Result = true; - for (const auto *D : R) { - if (const auto *FD = dyn_cast(D)) { + for (auto const *D : R) { + if (auto const *FD = dyn_cast(D)) { if (FD->getNumParams() == 1) { PreventedBy.push_back(FD); Result = false; @@ -2366,17 +2376,17 @@ // type X, X&, const X&, volatile X& or const volatile X&. if (/*operator=*/getOverloadedOperator() != OO_Equal || /*non-static*/ isStatic() || - /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() || + /*non-template*/ getPrimaryTemplate() || getDescribedFunctionTemplate() || getNumParams() != 1) return false; QualType ParamType = getParamDecl(0)->getType(); - if (const auto *Ref = ParamType->getAs()) + if (auto const *Ref = ParamType->getAs()) ParamType = Ref->getPointeeType(); ASTContext &Context = getASTContext(); - QualType ClassType - = Context.getCanonicalType(Context.getTypeDeclType(getParent())); + QualType ClassType = + Context.getCanonicalType(Context.getTypeDeclType(getParent())); return Context.hasSameUnqualifiedType(ClassType, ParamType); } @@ -2396,12 +2406,12 @@ ParamType = ParamType->getPointeeType(); ASTContext &Context = getASTContext(); - QualType ClassType - = Context.getCanonicalType(Context.getTypeDeclType(getParent())); + QualType ClassType = + Context.getCanonicalType(Context.getTypeDeclType(getParent())); return Context.hasSameUnqualifiedType(ClassType, ParamType); } -void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) { +void CXXMethodDecl::addOverriddenMethod(CXXMethodDecl const *MD) { assert(MD->isCanonicalDecl() && "Method is not canonical!"); assert(!MD->getParent()->isDependentContext() && "Can't add an overridden method to a class template!"); @@ -2411,17 +2421,20 @@ } CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const { - if (isa(this)) return nullptr; + if (isa(this)) + return nullptr; return getASTContext().overridden_methods_begin(this); } CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const { - if (isa(this)) return nullptr; + if (isa(this)) + return nullptr; return getASTContext().overridden_methods_end(this); } unsigned CXXMethodDecl::size_overridden_methods() const { - if (isa(this)) return 0; + if (isa(this)) + return 0; return getASTContext().overridden_methods_size(this); } @@ -2432,21 +2445,21 @@ return getASTContext().overridden_methods(this); } -static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT, - const CXXRecordDecl *Decl) { +static QualType getThisObjectType(ASTContext &C, FunctionProtoType const *FPT, + CXXRecordDecl const *Decl) { QualType ClassTy = C.getTypeDeclType(Decl); return C.getQualifiedType(ClassTy, FPT->getMethodQuals()); } -QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT, - const CXXRecordDecl *Decl) { +QualType CXXMethodDecl::getThisType(FunctionProtoType const *FPT, + CXXRecordDecl const *Decl) { ASTContext &C = Decl->getASTContext(); QualType ObjectTy = ::getThisObjectType(C, FPT, Decl); return C.getPointerType(ObjectTy); } -QualType CXXMethodDecl::getThisObjectType(const FunctionProtoType *FPT, - const CXXRecordDecl *Decl) { +QualType CXXMethodDecl::getThisObjectType(FunctionProtoType const *FPT, + CXXRecordDecl const *Decl) { ASTContext &C = Decl->getASTContext(); return ::getThisObjectType(C, FPT, Decl); } @@ -2472,17 +2485,17 @@ bool CXXMethodDecl::hasInlineBody() const { // If this function is a template instantiation, look at the template from // which it was instantiated. - const FunctionDecl *CheckFn = getTemplateInstantiationPattern(); + FunctionDecl const *CheckFn = getTemplateInstantiationPattern(); if (!CheckFn) CheckFn = this; - const FunctionDecl *fn; + FunctionDecl const *fn; return CheckFn->isDefined(fn) && !fn->isOutOfLine() && (fn->doesThisDeclarationHaveABody() || fn->willHaveBody()); } bool CXXMethodDecl::isLambdaStaticInvoker() const { - const CXXRecordDecl *P = getParent(); + CXXRecordDecl const *P = getParent(); return P->isLambda() && getDeclName().isIdentifier() && getName() == getLambdaStaticInvokerName(); } @@ -2514,27 +2527,26 @@ IsWritten(false), SourceOrder(0) {} CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, - TypeSourceInfo *TInfo, - SourceLocation L, Expr *Init, - SourceLocation R) + TypeSourceInfo *TInfo, SourceLocation L, + Expr *Init, SourceLocation R) : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {} -int64_t CXXCtorInitializer::getID(const ASTContext &Context) const { - return Context.getAllocator() - .identifyKnownAlignedObject(this); +int64_t CXXCtorInitializer::getID(ASTContext const &Context) const { + return Context.getAllocator().identifyKnownAlignedObject( + this); } TypeLoc CXXCtorInitializer::getBaseClassLoc() const { if (isBaseInitializer()) - return Initializee.get()->getTypeLoc(); + return Initializee.get()->getTypeLoc(); else return {}; } -const Type *CXXCtorInitializer::getBaseClass() const { +Type const *CXXCtorInitializer::getBaseClass() const { if (isBaseInitializer()) - return Initializee.get()->getType().getTypePtr(); + return Initializee.get()->getType().getTypePtr(); else return nullptr; } @@ -2546,7 +2558,7 @@ if (isAnyMemberInitializer()) return getMemberLocation(); - if (const auto *TSInfo = Initializee.get()) + if (auto const *TSInfo = Initializee.get()) return TSInfo->getTypeLoc().getLocalSourceRange().getBegin(); return {}; @@ -2565,7 +2577,7 @@ CXXConstructorDecl::CXXConstructorDecl( ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, - const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, + DeclarationNameInfo const &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited, Expr *TrailingRequiresClause) @@ -2605,12 +2617,12 @@ CXXConstructorDecl *CXXConstructorDecl::Create( ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, - const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, + DeclarationNameInfo const &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited, Expr *TrailingRequiresClause) { - assert(NameInfo.getName().getNameKind() - == DeclarationName::CXXConstructorName && + assert(NameInfo.getName().getNameKind() == + DeclarationName::CXXConstructorName && "Name must refer to a constructor"); unsigned Extra = additionalSizeToAlloc( @@ -2627,7 +2639,7 @@ CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const { assert(isDelegatingConstructor() && "Not a delegating constructor!"); Expr *E = (*init_begin())->getInit()->IgnoreImplicit(); - if (const auto *Construct = dyn_cast(E)) + if (auto const *Construct = dyn_cast(E)) return Construct->getConstructor(); return nullptr; @@ -2641,8 +2653,7 @@ return getMinRequiredArguments() == 0; } -bool -CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const { +bool CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const { return isCopyOrMoveConstructor(TypeQuals) && getParamDecl(0)->getType()->isLValueReferenceType(); } @@ -2668,20 +2679,20 @@ getDescribedFunctionTemplate() != nullptr) return false; - const ParmVarDecl *Param = getParamDecl(0); + ParmVarDecl const *Param = getParamDecl(0); // Do we have a reference type? - const auto *ParamRefType = Param->getType()->getAs(); + auto const *ParamRefType = Param->getType()->getAs(); if (!ParamRefType) return false; // Is it a reference to our class type? ASTContext &Context = getASTContext(); - CanQualType PointeeType - = Context.getCanonicalType(ParamRefType->getPointeeType()); - CanQualType ClassTy - = Context.getCanonicalType(Context.getTagDeclType(getParent())); + CanQualType PointeeType = + Context.getCanonicalType(ParamRefType->getPointeeType()); + CanQualType ClassTy = + Context.getCanonicalType(Context.getTagDeclType(getParent())); if (PointeeType.getUnqualifiedType() != ClassTy) return false; @@ -2714,14 +2725,14 @@ if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr) return false; - const ParmVarDecl *Param = getParamDecl(0); + ParmVarDecl const *Param = getParamDecl(0); ASTContext &Context = getASTContext(); CanQualType ParamType = Context.getCanonicalType(Param->getType()); // Is it the same as our class type? - CanQualType ClassTy - = Context.getCanonicalType(Context.getTagDeclType(getParent())); + CanQualType ClassTy = + Context.getCanonicalType(Context.getTagDeclType(getParent())); if (ParamType.getUnqualifiedType() != ClassTy) return false; @@ -2730,8 +2741,8 @@ void CXXDestructorDecl::anchor() {} -CXXDestructorDecl * -CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) { +CXXDestructorDecl *CXXDestructorDecl::CreateDeserialized(ASTContext &C, + unsigned ID) { return new (C, ID) CXXDestructorDecl( C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, false, false, false, ConstexprSpecKind::Unspecified, nullptr); @@ -2739,11 +2750,11 @@ CXXDestructorDecl *CXXDestructorDecl::Create( ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, - const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, + DeclarationNameInfo const &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause) { - assert(NameInfo.getName().getNameKind() - == DeclarationName::CXXDestructorName && + assert(NameInfo.getName().getNameKind() == + DeclarationName::CXXDestructorName && "Name must refer to a destructor"); return new (C, RD) CXXDestructorDecl( C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, @@ -2762,8 +2773,8 @@ void CXXConversionDecl::anchor() {} -CXXConversionDecl * -CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { +CXXConversionDecl *CXXConversionDecl::CreateDeserialized(ASTContext &C, + unsigned ID) { return new (C, ID) CXXConversionDecl( C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified, @@ -2772,12 +2783,12 @@ CXXConversionDecl *CXXConversionDecl::Create( ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, - const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, + DeclarationNameInfo const &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause) { - assert(NameInfo.getName().getNameKind() - == DeclarationName::CXXConversionFunctionName && + assert(NameInfo.getName().getNameKind() == + DeclarationName::CXXConversionFunctionName && "Name must refer to a conversion function"); return new (C, RD) CXXConversionDecl( C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES, @@ -2800,12 +2811,10 @@ void LinkageSpecDecl::anchor() {} -LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, - DeclContext *DC, +LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, - LanguageIDs Lang, - bool HasBraces) { + LanguageIDs Lang, bool HasBraces) { return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces); } @@ -2817,13 +2826,10 @@ void UsingDirectiveDecl::anchor() {} -UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation L, - SourceLocation NamespaceLoc, - NestedNameSpecifierLoc QualifierLoc, - SourceLocation IdentLoc, - NamedDecl *Used, - DeclContext *CommonAncestor) { +UsingDirectiveDecl *UsingDirectiveDecl::Create( + ASTContext &C, DeclContext *DC, SourceLocation L, + SourceLocation NamespaceLoc, NestedNameSpecifierLoc QualifierLoc, + SourceLocation IdentLoc, NamedDecl *Used, DeclContext *CommonAncestor) { if (auto *NS = dyn_cast_or_null(Used)) Used = NS->getOriginalNamespace(); return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc, @@ -2832,10 +2838,9 @@ UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(), - SourceLocation(), - NestedNameSpecifierLoc(), - SourceLocation(), nullptr, nullptr); + return new (C, ID) UsingDirectiveDecl( + nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(), + SourceLocation(), nullptr, nullptr); } NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() { @@ -2860,8 +2865,8 @@ bool Inline, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, NamespaceDecl *PrevDecl) { - return new (C, DC) NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, - PrevDecl); + return new (C, DC) + NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl); } NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) { @@ -2876,7 +2881,7 @@ return AnonOrFirstNamespaceAndInline.getPointer(); } -const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const { +NamespaceDecl const *NamespaceDecl::getOriginalNamespace() const { if (isFirstDecl()) return this; @@ -2911,13 +2916,12 @@ return getMostRecentDecl(); } -NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation UsingLoc, - SourceLocation AliasLoc, - IdentifierInfo *Alias, - NestedNameSpecifierLoc QualifierLoc, - SourceLocation IdentLoc, - NamedDecl *Namespace) { +NamespaceAliasDecl * +NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, + SourceLocation UsingLoc, SourceLocation AliasLoc, + IdentifierInfo *Alias, + NestedNameSpecifierLoc QualifierLoc, + SourceLocation IdentLoc, NamedDecl *Namespace) { // FIXME: Preserve the aliased namespace as written. if (auto *NS = dyn_cast_or_null(Namespace)) Namespace = NS->getOriginalNamespace(); @@ -2925,19 +2929,18 @@ QualifierLoc, IdentLoc, Namespace); } -NamespaceAliasDecl * -NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(), - SourceLocation(), nullptr, - NestedNameSpecifierLoc(), - SourceLocation(), nullptr); +NamespaceAliasDecl *NamespaceAliasDecl::CreateDeserialized(ASTContext &C, + unsigned ID) { + return new (C, ID) NamespaceAliasDecl( + C, nullptr, SourceLocation(), SourceLocation(), nullptr, + NestedNameSpecifierLoc(), SourceLocation(), nullptr); } void LifetimeExtendedTemporaryDecl::anchor() {} /// Retrieve the storage duration for the materialized temporary. StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const { - const ValueDecl *ExtendingDecl = getExtendingDecl(); + ValueDecl const *ExtendingDecl = getExtendingDecl(); if (!ExtendingDecl) return SD_FullExpression; // FIXME: This is not necessarily correct for a temporary materialized @@ -2979,14 +2982,14 @@ : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()), redeclarable_base(C) {} -UsingShadowDecl * -UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) { +UsingShadowDecl *UsingShadowDecl::CreateDeserialized(ASTContext &C, + unsigned ID) { return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell()); } BaseUsingDecl *UsingShadowDecl::getIntroducer() const { - const UsingShadowDecl *Shadow = this; - while (const auto *NextShadow = + UsingShadowDecl const *Shadow = this; + while (auto const *NextShadow = dyn_cast(Shadow->UsingOrNextShadow)) Shadow = NextShadow; return cast(Shadow->UsingOrNextShadow); @@ -2998,8 +3001,8 @@ ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, UsingDecl *Using, NamedDecl *Target, bool IsVirtual) { - return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target, - IsVirtual); + return new (C, DC) + ConstructorUsingShadowDecl(C, DC, Loc, Using, Target, IsVirtual); } ConstructorUsingShadowDecl * @@ -3032,7 +3035,7 @@ if (FirstUsingShadow.getPointer() == S) { FirstUsingShadow.setPointer( - dyn_cast(S->UsingOrNextShadow)); + dyn_cast(S->UsingOrNextShadow)); S->UsingOrNextShadow = this; return; } @@ -3048,20 +3051,20 @@ UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL, NestedNameSpecifierLoc QualifierLoc, - const DeclarationNameInfo &NameInfo, + DeclarationNameInfo const &NameInfo, bool HasTypename) { return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename); } UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) UsingDecl(nullptr, SourceLocation(), - NestedNameSpecifierLoc(), DeclarationNameInfo(), - false); + return new (C, ID) + UsingDecl(nullptr, SourceLocation(), NestedNameSpecifierLoc(), + DeclarationNameInfo(), false); } SourceRange UsingDecl::getSourceRange() const { - SourceLocation Begin = isAccessDeclaration() - ? getQualifierLoc().getBeginLoc() : UsingLocation; + SourceLocation Begin = + isAccessDeclaration() ? getQualifierLoc().getBeginLoc() : UsingLocation; return SourceRange(Begin, getNameInfo().getEndLoc()); } @@ -3098,48 +3101,40 @@ Result->NumExpansions = NumExpansions; auto *Trail = Result->getTrailingObjects(); for (unsigned I = 0; I != NumExpansions; ++I) - new (Trail + I) NamedDecl*(nullptr); + new (Trail + I) NamedDecl *(nullptr); return Result; } void UnresolvedUsingValueDecl::anchor() {} -UnresolvedUsingValueDecl * -UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation UsingLoc, - NestedNameSpecifierLoc QualifierLoc, - const DeclarationNameInfo &NameInfo, - SourceLocation EllipsisLoc) { - return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc, - QualifierLoc, NameInfo, - EllipsisLoc); +UnresolvedUsingValueDecl *UnresolvedUsingValueDecl::Create( + ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, + NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo const &NameInfo, + SourceLocation EllipsisLoc) { + return new (C, DC) UnresolvedUsingValueDecl( + DC, C.DependentTy, UsingLoc, QualifierLoc, NameInfo, EllipsisLoc); } UnresolvedUsingValueDecl * UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(), - SourceLocation(), - NestedNameSpecifierLoc(), - DeclarationNameInfo(), - SourceLocation()); + return new (C, ID) UnresolvedUsingValueDecl( + nullptr, QualType(), SourceLocation(), NestedNameSpecifierLoc(), + DeclarationNameInfo(), SourceLocation()); } SourceRange UnresolvedUsingValueDecl::getSourceRange() const { - SourceLocation Begin = isAccessDeclaration() - ? getQualifierLoc().getBeginLoc() : UsingLocation; + SourceLocation Begin = + isAccessDeclaration() ? getQualifierLoc().getBeginLoc() : UsingLocation; return SourceRange(Begin, getNameInfo().getEndLoc()); } void UnresolvedUsingTypenameDecl::anchor() {} -UnresolvedUsingTypenameDecl * -UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation UsingLoc, - SourceLocation TypenameLoc, - NestedNameSpecifierLoc QualifierLoc, - SourceLocation TargetNameLoc, - DeclarationName TargetName, - SourceLocation EllipsisLoc) { +UnresolvedUsingTypenameDecl *UnresolvedUsingTypenameDecl::Create( + ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, + SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, + SourceLocation TargetNameLoc, DeclarationName TargetName, + SourceLocation EllipsisLoc) { return new (C, DC) UnresolvedUsingTypenameDecl( DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc, TargetName.getAsIdentifierInfo(), EllipsisLoc); @@ -3237,14 +3232,14 @@ Result->NumBindings = NumBindings; auto *Trail = Result->getTrailingObjects(); for (unsigned I = 0; I != NumBindings; ++I) - new (Trail + I) BindingDecl*(nullptr); + new (Trail + I) BindingDecl *(nullptr); return Result; } void DecompositionDecl::printName(llvm::raw_ostream &os) const { os << '['; bool Comma = false; - for (const auto *B : bindings()) { + for (auto const *B : bindings()) { if (Comma) os << ", "; B->printName(os); @@ -3264,11 +3259,10 @@ return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter); } -MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C, - unsigned ID) { - return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(), - DeclarationName(), QualType(), nullptr, - SourceLocation(), nullptr, nullptr); +MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { + return new (C, ID) + MSPropertyDecl(nullptr, SourceLocation(), DeclarationName(), QualType(), + nullptr, SourceLocation(), nullptr, nullptr); } void MSGuidDecl::anchor() {} @@ -3277,7 +3271,7 @@ : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T), PartVal(P), APVal() {} -MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) { +MSGuidDecl *MSGuidDecl::Create(ASTContext const &C, QualType T, Parts P) { DeclContext *DC = C.getTranslationUnitDecl(); return new (C, DC) MSGuidDecl(DC, T, P); } @@ -3306,8 +3300,7 @@ auto IsInt = [&Ctx](unsigned N) { return [&Ctx, N](QualType T) { - return T->isUnsignedIntegerOrEnumerationType() && - Ctx.getIntWidth(T) == N; + return T->isUnsignedIntegerOrEnumerationType() && Ctx.getIntWidth(T) == N; }; }; @@ -3331,7 +3324,8 @@ return false; auto MatcherIt = Fields.begin(); for (const FieldDecl *FD : RD->fields()) { - if (FD->isUnnamedBitfield()) continue; + if (FD->isUnnamedBitfield()) + continue; if (FD->isBitField() || MatcherIt == Fields.end() || !(*MatcherIt)(FD->getType())) return false; @@ -3367,21 +3361,21 @@ return APVal; } -static const char *getAccessName(AccessSpecifier AS) { +static char const *getAccessName(AccessSpecifier AS) { switch (AS) { - case AS_none: - llvm_unreachable("Invalid access specifier!"); - case AS_public: - return "public"; - case AS_private: - return "private"; - case AS_protected: - return "protected"; + case AS_none: + llvm_unreachable("Invalid access specifier!"); + case AS_public: + return "public"; + case AS_private: + return "private"; + case AS_protected: + return "protected"; } llvm_unreachable("Invalid access specifier!"); } -const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB, +StreamingDiagnostic const &clang::operator<<(StreamingDiagnostic const &DB, AccessSpecifier AS) { return DB << getAccessName(AS); } Index: clang/lib/AST/DeclFriend.cpp =================================================================== --- clang/lib/AST/DeclFriend.cpp +++ clang/lib/AST/DeclFriend.cpp @@ -12,10 +12,10 @@ //===----------------------------------------------------------------------===// #include "clang/AST/DeclFriend.h" +#include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclBase.h" #include "clang/AST/DeclCXX.h" -#include "clang/AST/ASTContext.h" #include "clang/AST/DeclTemplate.h" #include "clang/Basic/LLVM.h" #include "llvm/Support/Casting.h" @@ -28,21 +28,18 @@ FriendDecl *FriendDecl::getNextFriendSlowCase() { return cast_or_null( - NextFriend.get(getASTContext().getExternalSource())); + NextFriend.get(getASTContext().getExternalSource())); } -FriendDecl *FriendDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation L, - FriendUnion Friend, - SourceLocation FriendL, - ArrayRef FriendTypeTPLists) { +FriendDecl * +FriendDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, + FriendUnion Friend, SourceLocation FriendL, + ArrayRef FriendTypeTPLists) { #ifndef NDEBUG if (Friend.is()) { - const auto *D = Friend.get(); - assert(isa(D) || - isa(D) || - isa(D) || - isa(D)); + auto const *D = Friend.get(); + assert(isa(D) || isa(D) || + isa(D) || isa(D)); // As a temporary hack, we permit template instantiation to point // to the original declaration when instantiating members. @@ -56,8 +53,8 @@ std::size_t Extra = FriendDecl::additionalSizeToAlloc( FriendTypeTPLists.size()); - auto *FD = new (C, DC, Extra) FriendDecl(DC, L, Friend, FriendL, - FriendTypeTPLists); + auto *FD = + new (C, DC, Extra) FriendDecl(DC, L, Friend, FriendL, FriendTypeTPLists); cast(DC)->pushFriendDecl(FD); return FD; } Index: clang/lib/AST/DeclGroup.cpp =================================================================== --- clang/lib/AST/DeclGroup.cpp +++ clang/lib/AST/DeclGroup.cpp @@ -17,15 +17,15 @@ using namespace clang; -DeclGroup* DeclGroup::Create(ASTContext &C, Decl **Decls, unsigned NumDecls) { +DeclGroup *DeclGroup::Create(ASTContext &C, Decl **Decls, unsigned NumDecls) { assert(NumDecls > 1 && "Invalid DeclGroup"); unsigned Size = totalSizeToAlloc(NumDecls); void *Mem = C.Allocate(Size, alignof(DeclGroup)); new (Mem) DeclGroup(NumDecls, Decls); - return static_cast(Mem); + return static_cast(Mem); } -DeclGroup::DeclGroup(unsigned numdecls, Decl** decls) : NumDecls(numdecls) { +DeclGroup::DeclGroup(unsigned numdecls, Decl **decls) : NumDecls(numdecls) { assert(numdecls > 0); assert(decls); std::uninitialized_copy(decls, decls + numdecls, Index: clang/lib/AST/DeclObjC.cpp =================================================================== --- clang/lib/AST/DeclObjC.cpp +++ clang/lib/AST/DeclObjC.cpp @@ -42,17 +42,18 @@ // ObjCListBase //===----------------------------------------------------------------------===// -void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) { +void ObjCListBase::set(void *const *InList, unsigned Elts, ASTContext &Ctx) { List = nullptr; - if (Elts == 0) return; // Setting to an empty list is a noop. + if (Elts == 0) + return; // Setting to an empty list is a noop. - List = new (Ctx) void*[Elts]; + List = new (Ctx) void *[Elts]; NumElts = Elts; - memcpy(List, InList, sizeof(void*)*Elts); + memcpy(List, InList, sizeof(void *) * Elts); } -void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, - const SourceLocation *Locs, ASTContext &Ctx) { +void ObjCProtocolList::set(ObjCProtocolDecl *const *InList, unsigned Elts, + SourceLocation const *Locs, ASTContext &Ctx) { if (Elts == 0) return; @@ -76,11 +77,10 @@ /// getIvarDecl - This method looks up an ivar in this ContextDecl. /// -ObjCIvarDecl * -ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const { +ObjCIvarDecl *ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const { lookup_result R = lookup(Id); - for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end(); - Ivar != IvarEnd; ++Ivar) { + for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end(); Ivar != IvarEnd; + ++Ivar) { if (auto *ivar = dyn_cast(*Ivar)) return ivar; } @@ -88,13 +88,12 @@ } // Get the local instance/class method declared in this interface. -ObjCMethodDecl * -ObjCContainerDecl::getMethod(Selector Sel, bool isInstance, - bool AllowHidden) const { +ObjCMethodDecl *ObjCContainerDecl::getMethod(Selector Sel, bool isInstance, + bool AllowHidden) const { // If this context is a hidden protocol definition, don't find any // methods there. - if (const auto *Proto = dyn_cast(this)) { - if (const ObjCProtocolDecl *Def = Proto->getDefinition()) + if (auto const *Proto = dyn_cast(this)) { + if (ObjCProtocolDecl const *Def = Proto->getDefinition()) if (!Def->isUnconditionallyVisible() && !AllowHidden) return nullptr; } @@ -107,8 +106,8 @@ // + (float) class_method; // @end lookup_result R = lookup(Sel); - for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); - Meth != MethEnd; ++Meth) { + for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); Meth != MethEnd; + ++Meth) { auto *MD = dyn_cast(*Meth); if (MD && MD->isInstanceMethod() == isInstance) return MD; @@ -122,20 +121,20 @@ /// property. This is because, user must provide a setter method for the /// category's 'readwrite' property. bool ObjCContainerDecl::HasUserDeclaredSetterMethod( - const ObjCPropertyDecl *Property) const { + ObjCPropertyDecl const *Property) const { Selector Sel = Property->getSetterName(); lookup_result R = lookup(Sel); - for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); - Meth != MethEnd; ++Meth) { + for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); Meth != MethEnd; + ++Meth) { auto *MD = dyn_cast(*Meth); if (MD && MD->isInstanceMethod() && !MD->isImplicit()) return true; } - if (const auto *ID = dyn_cast(this)) { + if (auto const *ID = dyn_cast(this)) { // Also look into categories, including class extensions, looking // for a user declared instance method. - for (const auto *Cat : ID->visible_categories()) { + for (auto const *Cat : ID->visible_categories()) { if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel)) if (!MD->isImplicit()) return true; @@ -145,7 +144,7 @@ // declaration of this property. If one found, presumably a setter will // be provided (properties declared in categories will not get // auto-synthesized). - for (const auto *P : Cat->properties()) + for (auto const *P : Cat->properties()) if (P->getIdentifier() == Property->getIdentifier()) { if (P->getPropertyAttributes() & ObjCPropertyAttribute::kind_readwrite) @@ -155,7 +154,7 @@ } // Also look into protocols, for a user declared instance method. - for (const auto *Proto : ID->all_referenced_protocols()) + for (auto const *Proto : ID->all_referenced_protocols()) if (Proto->HasUserDeclaredSetterMethod(Property)) return true; @@ -167,21 +166,21 @@ OSC = OSC->getSuperClass(); } } - if (const auto *PD = dyn_cast(this)) - for (const auto *PI : PD->protocols()) + if (auto const *PD = dyn_cast(this)) + for (auto const *PI : PD->protocols()) if (PI->HasUserDeclaredSetterMethod(Property)) return true; return false; } ObjCPropertyDecl * -ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC, - const IdentifierInfo *propertyID, +ObjCPropertyDecl::findPropertyDecl(DeclContext const *DC, + IdentifierInfo const *propertyID, ObjCPropertyQueryKind queryKind) { // If this context is a hidden protocol definition, don't find any // property. - if (const auto *Proto = dyn_cast(DC)) { - if (const ObjCProtocolDecl *Def = Proto->getDefinition()) + if (auto const *Proto = dyn_cast(DC)) { + if (ObjCProtocolDecl const *Def = Proto->getDefinition()) if (!Def->isUnconditionallyVisible()) return nullptr; } @@ -189,17 +188,15 @@ // If context is class, then lookup property in its visible extensions. // This comes before property is looked up in primary class. if (auto *IDecl = dyn_cast(DC)) { - for (const auto *Ext : IDecl->visible_extensions()) - if (ObjCPropertyDecl *PD = ObjCPropertyDecl::findPropertyDecl(Ext, - propertyID, - queryKind)) + for (auto const *Ext : IDecl->visible_extensions()) + if (ObjCPropertyDecl *PD = + ObjCPropertyDecl::findPropertyDecl(Ext, propertyID, queryKind)) return PD; } DeclContext::lookup_result R = DC->lookup(propertyID); ObjCPropertyDecl *classProp = nullptr; - for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; - ++I) + for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) if (auto *PD = dyn_cast(*I)) { // If queryKind is unknown, we return the instance property if one // exists; otherwise we return the class property. @@ -235,71 +232,69 @@ /// FindPropertyDeclaration - Finds declaration of the property given its name /// in 'PropertyId' and returns it. It returns 0, if not found. ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration( - const IdentifierInfo *PropertyId, - ObjCPropertyQueryKind QueryKind) const { + IdentifierInfo const *PropertyId, ObjCPropertyQueryKind QueryKind) const { // Don't find properties within hidden protocol definitions. - if (const auto *Proto = dyn_cast(this)) { - if (const ObjCProtocolDecl *Def = Proto->getDefinition()) + if (auto const *Proto = dyn_cast(this)) { + if (ObjCProtocolDecl const *Def = Proto->getDefinition()) if (!Def->isUnconditionallyVisible()) return nullptr; } // Search the extensions of a class first; they override what's in // the class itself. - if (const auto *ClassDecl = dyn_cast(this)) { - for (const auto *Ext : ClassDecl->visible_extensions()) { + if (auto const *ClassDecl = dyn_cast(this)) { + for (auto const *Ext : ClassDecl->visible_extensions()) { if (auto *P = Ext->FindPropertyDeclaration(PropertyId, QueryKind)) return P; } } - if (ObjCPropertyDecl *PD = - ObjCPropertyDecl::findPropertyDecl(cast(this), PropertyId, - QueryKind)) + if (ObjCPropertyDecl *PD = ObjCPropertyDecl::findPropertyDecl( + cast(this), PropertyId, QueryKind)) return PD; switch (getKind()) { - default: - break; - case Decl::ObjCProtocol: { - const auto *PID = cast(this); - for (const auto *I : PID->protocols()) - if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, - QueryKind)) + default: + break; + case Decl::ObjCProtocol: { + auto const *PID = cast(this); + for (auto const *I : PID->protocols()) + if (ObjCPropertyDecl *P = + I->FindPropertyDeclaration(PropertyId, QueryKind)) + return P; + break; + } + case Decl::ObjCInterface: { + auto const *OID = cast(this); + // Look through categories (but not extensions; they were handled above). + for (auto const *Cat : OID->visible_categories()) { + if (!Cat->IsClassExtension()) + if (ObjCPropertyDecl *P = + Cat->FindPropertyDeclaration(PropertyId, QueryKind)) return P; - break; } - case Decl::ObjCInterface: { - const auto *OID = cast(this); - // Look through categories (but not extensions; they were handled above). - for (const auto *Cat : OID->visible_categories()) { - if (!Cat->IsClassExtension()) - if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration( - PropertyId, QueryKind)) - return P; - } - // Look through protocols. - for (const auto *I : OID->all_referenced_protocols()) - if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, - QueryKind)) - return P; + // Look through protocols. + for (auto const *I : OID->all_referenced_protocols()) + if (ObjCPropertyDecl *P = + I->FindPropertyDeclaration(PropertyId, QueryKind)) + return P; - // Finally, check the super class. - if (const ObjCInterfaceDecl *superClass = OID->getSuperClass()) - return superClass->FindPropertyDeclaration(PropertyId, QueryKind); - break; - } - case Decl::ObjCCategory: { - const auto *OCD = cast(this); - // Look through protocols. - if (!OCD->IsClassExtension()) - for (const auto *I : OCD->protocols()) - if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, - QueryKind)) - return P; - break; - } + // Finally, check the super class. + if (ObjCInterfaceDecl const *superClass = OID->getSuperClass()) + return superClass->FindPropertyDeclaration(PropertyId, QueryKind); + break; + } + case Decl::ObjCCategory: { + auto const *OCD = cast(this); + // Look through protocols. + if (!OCD->IsClassExtension()) + for (auto const *I : OCD->protocols()) + if (ObjCPropertyDecl *P = + I->FindPropertyDeclaration(PropertyId, QueryKind)) + return P; + break; + } } return nullptr; } @@ -312,13 +307,13 @@ return written; // If there is a definition, return its type parameter list. - if (const ObjCInterfaceDecl *def = getDefinition()) + if (ObjCInterfaceDecl const *def = getDefinition()) return def->getTypeParamListAsWritten(); // Otherwise, look at previous declarations to determine whether any // of them has a type parameter list, skipping over those // declarations that do not. - for (const ObjCInterfaceDecl *decl = getMostRecentDecl(); decl; + for (ObjCInterfaceDecl const *decl = getMostRecentDecl(); decl; decl = decl->getPreviousDecl()) { if (ObjCTypeParamList *written = decl->getTypeParamListAsWritten()) return written; @@ -344,7 +339,7 @@ if (data().ExternallyCompleted) LoadExternalDefinition(); - if (const ObjCObjectType *superType = getSuperClassType()) { + if (ObjCObjectType const *superType = getSuperClassType()) { if (ObjCInterfaceDecl *superDecl = superType->getInterface()) { if (ObjCInterfaceDecl *superDef = superDecl->getDefinition()) return superDef; @@ -366,10 +361,8 @@ /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property /// with name 'PropertyId' in the primary class; including those in protocols /// (direct or indirect) used by the primary class. -ObjCPropertyDecl * -ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass( - IdentifierInfo *PropertyId, - ObjCPropertyQueryKind QueryKind) const { +ObjCPropertyDecl *ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass( + IdentifierInfo *PropertyId, ObjCPropertyQueryKind QueryKind) const { // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; @@ -377,34 +370,32 @@ if (data().ExternallyCompleted) LoadExternalDefinition(); - if (ObjCPropertyDecl *PD = - ObjCPropertyDecl::findPropertyDecl(cast(this), PropertyId, - QueryKind)) + if (ObjCPropertyDecl *PD = ObjCPropertyDecl::findPropertyDecl( + cast(this), PropertyId, QueryKind)) return PD; // Look through protocols. - for (const auto *I : all_referenced_protocols()) - if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, - QueryKind)) + for (auto const *I : all_referenced_protocols()) + if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, QueryKind)) return P; return nullptr; } -void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap &PM, - PropertyDeclOrder &PO) const { +void ObjCInterfaceDecl::collectPropertiesToImplement( + PropertyMap &PM, PropertyDeclOrder &PO) const { for (auto *Prop : properties()) { PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; PO.push_back(Prop); } - for (const auto *Ext : known_extensions()) { - const ObjCCategoryDecl *ClassExt = Ext; + for (auto const *Ext : known_extensions()) { + ObjCCategoryDecl const *ClassExt = Ext; for (auto *Prop : ClassExt->properties()) { PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; PO.push_back(Prop); } } - for (const auto *PI : all_referenced_protocols()) + for (auto const *PI : all_referenced_protocols()) PI->collectPropertiesToImplement(PM, PO); // Note, the properties declared only in class extensions are still copied // into the main @interface's property list, and therefore we don't @@ -412,7 +403,7 @@ } bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const { - const ObjCInterfaceDecl *Class = this; + ObjCInterfaceDecl const *Class = this; while (Class) { if (Class->hasAttr()) return true; @@ -421,8 +412,8 @@ return false; } -const ObjCInterfaceDecl *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const { - const ObjCInterfaceDecl *Class = this; +ObjCInterfaceDecl const *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const { + ObjCInterfaceDecl const *Class = this; while (Class) { if (Class->hasAttr()) return Class; @@ -432,8 +423,7 @@ } void ObjCInterfaceDecl::mergeClassExtensionProtocolList( - ObjCProtocolDecl *const* ExtList, unsigned ExtNum, - ASTContext &C) { + ObjCProtocolDecl *const *ExtList, unsigned ExtNum, ASTContext &C) { if (data().ExternallyCompleted) LoadExternalDefinition(); @@ -469,12 +459,13 @@ ProtocolRefs.append(all_referenced_protocol_begin(), all_referenced_protocol_end()); - data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C); + data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(), + C); } -const ObjCInterfaceDecl * +ObjCInterfaceDecl const * ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const { - const ObjCInterfaceDecl *IFace = this; + ObjCInterfaceDecl const *IFace = this; while (IFace) { if (IFace->hasDesignatedInitializers()) return IFace; @@ -485,19 +476,19 @@ return nullptr; } -static bool isIntroducingInitializers(const ObjCInterfaceDecl *D) { - for (const auto *MD : D->instance_methods()) { +static bool isIntroducingInitializers(ObjCInterfaceDecl const *D) { + for (auto const *MD : D->instance_methods()) { if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) return true; } - for (const auto *Ext : D->visible_extensions()) { - for (const auto *MD : Ext->instance_methods()) { + for (auto const *Ext : D->visible_extensions()) { + for (auto const *MD : Ext->instance_methods()) { if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) return true; } } - if (const auto *ImplD = D->getImplementation()) { - for (const auto *MD : ImplD->instance_methods()) { + if (auto const *ImplD = D->getImplementation()) { + for (auto const *MD : ImplD->instance_methods()) { if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) return true; } @@ -520,47 +511,47 @@ } else { if (auto SuperD = getSuperClass()) { data().InheritedDesignatedInitializers = - SuperD->declaresOrInheritsDesignatedInitializers() ? - DefinitionData::IDI_Inherited : - DefinitionData::IDI_NotInherited; + SuperD->declaresOrInheritsDesignatedInitializers() + ? DefinitionData::IDI_Inherited + : DefinitionData::IDI_NotInherited; } else { data().InheritedDesignatedInitializers = - DefinitionData::IDI_NotInherited; + DefinitionData::IDI_NotInherited; } } - assert(data().InheritedDesignatedInitializers - != DefinitionData::IDI_Unknown); + assert(data().InheritedDesignatedInitializers != + DefinitionData::IDI_Unknown); return data().InheritedDesignatedInitializers == - DefinitionData::IDI_Inherited; + DefinitionData::IDI_Inherited; } llvm_unreachable("unexpected InheritedDesignatedInitializers value"); } void ObjCInterfaceDecl::getDesignatedInitializers( - llvm::SmallVectorImpl &Methods) const { + llvm::SmallVectorImpl &Methods) const { // Check for a complete definition and recover if not so. if (!isThisDeclarationADefinition()) return; if (data().ExternallyCompleted) LoadExternalDefinition(); - const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers(); + ObjCInterfaceDecl const *IFace = findInterfaceWithDesignatedInitializers(); if (!IFace) return; - for (const auto *MD : IFace->instance_methods()) + for (auto const *MD : IFace->instance_methods()) if (MD->isThisDeclarationADesignatedInitializer()) Methods.push_back(MD); - for (const auto *Ext : IFace->visible_extensions()) { - for (const auto *MD : Ext->instance_methods()) + for (auto const *Ext : IFace->visible_extensions()) { + for (auto const *MD : Ext->instance_methods()) if (MD->isThisDeclarationADesignatedInitializer()) Methods.push_back(MD); } } -bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel, - const ObjCMethodDecl **InitMethod) const { +bool ObjCInterfaceDecl::isDesignatedInitializer( + Selector Sel, ObjCMethodDecl const **InitMethod) const { bool HasCompleteDef = isThisDeclarationADefinition(); // During deserialization the data record for the ObjCInterfaceDecl could // be made invariant by reusing the canonical decl. Take this into account @@ -576,19 +567,19 @@ if (data().ExternallyCompleted) LoadExternalDefinition(); - const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers(); + ObjCInterfaceDecl const *IFace = findInterfaceWithDesignatedInitializers(); if (!IFace) return false; - if (const ObjCMethodDecl *MD = IFace->getInstanceMethod(Sel)) { + if (ObjCMethodDecl const *MD = IFace->getInstanceMethod(Sel)) { if (MD->isThisDeclarationADesignatedInitializer()) { if (InitMethod) *InitMethod = MD; return true; } } - for (const auto *Ext : IFace->visible_extensions()) { - if (const ObjCMethodDecl *MD = Ext->getInstanceMethod(Sel)) { + for (auto const *Ext : IFace->visible_extensions()) { + if (ObjCMethodDecl const *MD = Ext->getInstanceMethod(Sel)) { if (MD->isThisDeclarationADesignatedInitializer()) { if (InitMethod) *InitMethod = MD; @@ -619,8 +610,9 @@ } } -ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID, - ObjCInterfaceDecl *&clsDeclared) { +ObjCIvarDecl * +ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID, + ObjCInterfaceDecl *&clsDeclared) { // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; @@ -628,14 +620,14 @@ if (data().ExternallyCompleted) LoadExternalDefinition(); - ObjCInterfaceDecl* ClassDecl = this; + ObjCInterfaceDecl *ClassDecl = this; while (ClassDecl != nullptr) { if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) { clsDeclared = ClassDecl; return I; } - for (const auto *Ext : ClassDecl->visible_extensions()) { + for (auto const *Ext : ClassDecl->visible_extensions()) { if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) { clsDeclared = ClassDecl; return I; @@ -648,10 +640,10 @@ } /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super -/// class whose name is passed as argument. If it is not one of the super classes -/// the it returns NULL. -ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass( - const IdentifierInfo*ICName) { +/// class whose name is passed as argument. If it is not one of the super +/// classes the it returns NULL. +ObjCInterfaceDecl * +ObjCInterfaceDecl::lookupInheritedClass(IdentifierInfo const *ICName) { // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; @@ -659,7 +651,7 @@ if (data().ExternallyCompleted) LoadExternalDefinition(); - ObjCInterfaceDecl* ClassDecl = this; + ObjCInterfaceDecl *ClassDecl = this; while (ClassDecl != nullptr) { if (ClassDecl->getIdentifier() == ICName) return ClassDecl; @@ -681,17 +673,15 @@ /// the class, its categories, and its super classes (using a linear search). /// When argument category "C" is specified, any implicit method found /// in this category is ignored. -ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, - bool isInstance, - bool shallowCategoryLookup, - bool followSuper, - const ObjCCategoryDecl *C) const -{ +ObjCMethodDecl * +ObjCInterfaceDecl::lookupMethod(Selector Sel, bool isInstance, + bool shallowCategoryLookup, bool followSuper, + ObjCCategoryDecl const *C) const { // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; - const ObjCInterfaceDecl* ClassDecl = this; + ObjCInterfaceDecl const *ClassDecl = this; ObjCMethodDecl *MethodDecl = nullptr; if (data().ExternallyCompleted) @@ -703,29 +693,28 @@ return MethodDecl; // 2. Didn't find one yet - now look through categories. - for (const auto *Cat : ClassDecl->visible_categories()) + for (auto const *Cat : ClassDecl->visible_categories()) if ((MethodDecl = Cat->getMethod(Sel, isInstance))) if (C != Cat || !MethodDecl->isImplicit()) return MethodDecl; // 3. Didn't find one yet - look through primary class's protocols. - for (const auto *I : ClassDecl->protocols()) + for (auto const *I : ClassDecl->protocols()) if ((MethodDecl = I->lookupMethod(Sel, isInstance))) return MethodDecl; // 4. Didn't find one yet - now look through categories' protocols if (!shallowCategoryLookup) - for (const auto *Cat : ClassDecl->visible_categories()) { + for (auto const *Cat : ClassDecl->visible_categories()) { // Didn't find one yet - look through protocols. - const ObjCList &Protocols = - Cat->getReferencedProtocols(); + ObjCList const &Protocols = + Cat->getReferencedProtocols(); for (auto *Protocol : Protocols) if ((MethodDecl = Protocol->lookupMethod(Sel, isInstance))) if (C != Cat || !MethodDecl->isImplicit()) return MethodDecl; } - if (!followSuper) return nullptr; @@ -738,9 +727,8 @@ // Will search "local" class/category implementations for a method decl. // If failed, then we search in class's root for an instance method. // Returns 0 if no method is found. -ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod( - const Selector &Sel, - bool Instance) const { +ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(Selector const &Sel, + bool Instance) const { // FIXME: Should make sure no callers ever do this. if (!hasDefinition()) return nullptr; @@ -832,25 +820,25 @@ bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const { return getMethodFamily() == OMF_init && - hasAttr(); + hasAttr(); } -bool ObjCMethodDecl::definedInNSObject(const ASTContext &Ctx) const { - if (const auto *PD = dyn_cast(getDeclContext())) +bool ObjCMethodDecl::definedInNSObject(ASTContext const &Ctx) const { + if (auto const *PD = dyn_cast(getDeclContext())) return PD->getIdentifier() == Ctx.getNSObjectName(); - if (const auto *ID = dyn_cast(getDeclContext())) + if (auto const *ID = dyn_cast(getDeclContext())) return ID->getIdentifier() == Ctx.getNSObjectName(); return false; } bool ObjCMethodDecl::isDesignatedInitializerForTheInterface( - const ObjCMethodDecl **InitMethod) const { + ObjCMethodDecl const **InitMethod) const { if (getMethodFamily() != OMF_init) return false; - const DeclContext *DC = getDeclContext(); + DeclContext const *DC = getDeclContext(); if (isa(DC)) return false; - if (const ObjCInterfaceDecl *ID = getClassInterface()) + if (ObjCInterfaceDecl const *ID = getClassInterface()) return ID->isDesignatedInitializer(getSelector(), InitMethod); return false; } @@ -859,7 +847,7 @@ return Body.get(getASTContext().getExternalSource()); } -void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) { +void ObjCMethodDecl::setAsRedeclaration(ObjCMethodDecl const *PrevMethod) { assert(PrevMethod); getASTContext().setObjCMethodRedeclaration(PrevMethod, this); setIsRedeclaration(true); @@ -867,7 +855,7 @@ } void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C, - ArrayRef Params, + ArrayRef Params, ArrayRef SelLocs) { ParamsAndSelLocs = nullptr; NumParams = Params.size(); @@ -885,21 +873,21 @@ } void ObjCMethodDecl::getSelectorLocs( - SmallVectorImpl &SelLocs) const { + SmallVectorImpl &SelLocs) const { for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i) SelLocs.push_back(getSelectorLoc(i)); } void ObjCMethodDecl::setMethodParams(ASTContext &C, - ArrayRef Params, + ArrayRef Params, ArrayRef SelLocs) { assert((!SelLocs.empty() || isImplicit()) && "No selector locs for non-implicit method"); if (isImplicit()) return setParamsAndSelLocs(C, Params, llvm::None); - setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs, Params, - DeclEndLoc)); + setSelLocsKind( + hasStandardSelectorLocs(getSelector(), SelLocs, Params, DeclEndLoc)); if (getSelLocsKind() != SelLoc_NonStandard) return setParamsAndSelLocs(C, Params, llvm::None); @@ -913,7 +901,7 @@ ASTContext &Ctx = getASTContext(); ObjCMethodDecl *Redecl = nullptr; if (hasRedeclaration()) - Redecl = const_cast(Ctx.getObjCMethodRedeclaration(this)); + Redecl = const_cast(Ctx.getObjCMethodRedeclaration(this)); if (Redecl) return Redecl; @@ -960,7 +948,7 @@ ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() { auto *CtxD = cast(getDeclContext()); - const auto &Sel = getSelector(); + auto const &Sel = getSelector(); if (auto *ImplD = dyn_cast(CtxD)) { if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) { @@ -1005,16 +993,28 @@ return family; // Check for an explicit attribute. - if (const ObjCMethodFamilyAttr *attr = getAttr()) { + if (ObjCMethodFamilyAttr const *attr = getAttr()) { // The unfortunate necessity of mapping between enums here is due // to the attributes framework. switch (attr->getFamily()) { - case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break; - case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break; - case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break; - case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break; - case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break; - case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break; + case ObjCMethodFamilyAttr::OMF_None: + family = OMF_None; + break; + case ObjCMethodFamilyAttr::OMF_alloc: + family = OMF_alloc; + break; + case ObjCMethodFamilyAttr::OMF_copy: + family = OMF_copy; + break; + case ObjCMethodFamilyAttr::OMF_init: + family = OMF_init; + break; + case ObjCMethodFamilyAttr::OMF_mutableCopy: + family = OMF_mutableCopy; + break; + case ObjCMethodFamilyAttr::OMF_new: + family = OMF_new; + break; } ObjCMethodDeclBits.Family = family; return family; @@ -1022,7 +1022,8 @@ family = getSelector().getMethodFamily(); switch (family) { - case OMF_None: break; + case OMF_None: + break; // init only has a conventional meaning for an instance method, and // it has to return an object. @@ -1083,7 +1084,6 @@ } } break; - } // Cache the result. @@ -1092,7 +1092,7 @@ } QualType ObjCMethodDecl::getSelfType(ASTContext &Context, - const ObjCInterfaceDecl *OID, + ObjCInterfaceDecl const *OID, bool &selfIsPseudoStrong, bool &selfIsConsumed) const { QualType selfTy; @@ -1125,8 +1125,7 @@ selfTy = selfTy.withConst(); selfIsPseudoStrong = true; } - } - else { + } else { assert(isClassMethod()); // 'self' is always const in class methods. selfTy = selfTy.withConst(); @@ -1137,10 +1136,10 @@ } void ObjCMethodDecl::createImplicitParams(ASTContext &Context, - const ObjCInterfaceDecl *OID) { + ObjCInterfaceDecl const *OID) { bool selfIsPseudoStrong, selfIsConsumed; QualType selfTy = - getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed); + getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed); auto *Self = ImplicitParamDecl::Create(Context, this, SourceLocation(), &Context.Idents.get("self"), selfTy, ImplicitParamDecl::ObjCSelf); @@ -1178,7 +1177,7 @@ } SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const { - const auto *TSI = getReturnTypeSourceInfo(); + auto const *TSI = getReturnTypeSourceInfo(); if (TSI) return TSI->getTypeLoc().getSourceRange(); return SourceRange(); @@ -1186,36 +1185,35 @@ QualType ObjCMethodDecl::getSendResultType() const { ASTContext &Ctx = getASTContext(); - return getReturnType().getNonLValueExprType(Ctx) - .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result); + return getReturnType().getNonLValueExprType(Ctx).substObjCTypeArgs( + Ctx, {}, ObjCSubstitutionContext::Result); } QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const { // FIXME: Handle related result types here. - return getReturnType().getNonLValueExprType(getASTContext()) - .substObjCMemberType(receiverType, getDeclContext(), - ObjCSubstitutionContext::Result); + return getReturnType() + .getNonLValueExprType(getASTContext()) + .substObjCMemberType(receiverType, getDeclContext(), + ObjCSubstitutionContext::Result); } -static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container, - const ObjCMethodDecl *Method, - SmallVectorImpl &Methods, - bool MovedToSuper) { +static void CollectOverriddenMethodsRecurse( + ObjCContainerDecl const *Container, ObjCMethodDecl const *Method, + SmallVectorImpl &Methods, bool MovedToSuper) { if (!Container) return; // In categories look for overridden methods from protocols. A method from // category is not "overridden" since it is considered as the "same" method // (same USR) as the one from the interface. - if (const auto *Category = dyn_cast(Container)) { + if (auto const *Category = dyn_cast(Container)) { // Check whether we have a matching method at this category but only if we // are at the super class level. if (MovedToSuper) - if (ObjCMethodDecl * - Overridden = Container->getMethod(Method->getSelector(), - Method->isInstanceMethod(), - /*AllowHidden=*/true)) + if (ObjCMethodDecl *Overridden = Container->getMethod( + Method->getSelector(), Method->isInstanceMethod(), + /*AllowHidden=*/true)) if (Method != Overridden) { // We found an override at this category; there is no need to look // into its protocols. @@ -1223,16 +1221,15 @@ return; } - for (const auto *P : Category->protocols()) + for (auto const *P : Category->protocols()) CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); return; } // Check whether we have a matching method at this level. - if (const ObjCMethodDecl * - Overridden = Container->getMethod(Method->getSelector(), - Method->isInstanceMethod(), - /*AllowHidden=*/true)) + if (ObjCMethodDecl const *Overridden = Container->getMethod( + Method->getSelector(), Method->isInstanceMethod(), + /*AllowHidden=*/true)) if (Method != Overridden) { // We found an override at this level; there is no need to look // into other protocols or categories. @@ -1240,75 +1237,77 @@ return; } - if (const auto *Protocol = dyn_cast(Container)){ - for (const auto *P : Protocol->protocols()) + if (auto const *Protocol = dyn_cast(Container)) { + for (auto const *P : Protocol->protocols()) CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); } - if (const auto *Interface = dyn_cast(Container)) { - for (const auto *P : Interface->protocols()) + if (auto const *Interface = dyn_cast(Container)) { + for (auto const *P : Interface->protocols()) CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); - for (const auto *Cat : Interface->known_categories()) + for (auto const *Cat : Interface->known_categories()) CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper); - if (const ObjCInterfaceDecl *Super = Interface->getSuperClass()) + if (ObjCInterfaceDecl const *Super = Interface->getSuperClass()) return CollectOverriddenMethodsRecurse(Super, Method, Methods, /*MovedToSuper=*/true); } } -static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container, - const ObjCMethodDecl *Method, - SmallVectorImpl &Methods) { +inline static void +CollectOverriddenMethods(ObjCContainerDecl const *Container, + ObjCMethodDecl const *Method, + SmallVectorImpl &Methods) { CollectOverriddenMethodsRecurse(Container, Method, Methods, /*MovedToSuper=*/false); } -static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method, - SmallVectorImpl &overridden) { +static void collectOverriddenMethodsSlow( + ObjCMethodDecl const *Method, + SmallVectorImpl &overridden) { assert(Method->isOverriding()); - if (const auto *ProtD = + if (auto const *ProtD = dyn_cast(Method->getDeclContext())) { CollectOverriddenMethods(ProtD, Method, overridden); - } else if (const auto *IMD = + } else if (auto const *IMD = dyn_cast(Method->getDeclContext())) { - const ObjCInterfaceDecl *ID = IMD->getClassInterface(); + ObjCInterfaceDecl const *ID = IMD->getClassInterface(); if (!ID) return; // Start searching for overridden methods using the method from the // interface as starting point. - if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), - Method->isInstanceMethod(), - /*AllowHidden=*/true)) + if (ObjCMethodDecl const *IFaceMeth = + ID->getMethod(Method->getSelector(), Method->isInstanceMethod(), + /*AllowHidden=*/true)) Method = IFaceMeth; CollectOverriddenMethods(ID, Method, overridden); - } else if (const auto *CatD = + } else if (auto const *CatD = dyn_cast(Method->getDeclContext())) { - const ObjCInterfaceDecl *ID = CatD->getClassInterface(); + ObjCInterfaceDecl const *ID = CatD->getClassInterface(); if (!ID) return; // Start searching for overridden methods using the method from the // interface as starting point. - if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), - Method->isInstanceMethod(), - /*AllowHidden=*/true)) + if (ObjCMethodDecl const *IFaceMeth = + ID->getMethod(Method->getSelector(), Method->isInstanceMethod(), + /*AllowHidden=*/true)) Method = IFaceMeth; CollectOverriddenMethods(ID, Method, overridden); } else { CollectOverriddenMethods( - dyn_cast_or_null(Method->getDeclContext()), - Method, overridden); + dyn_cast_or_null(Method->getDeclContext()), Method, + overridden); } } void ObjCMethodDecl::getOverriddenMethods( - SmallVectorImpl &Overridden) const { - const ObjCMethodDecl *Method = this; + SmallVectorImpl &Overridden) const { + ObjCMethodDecl const *Method = this; if (Method->isRedeclaration()) { Method = cast(Method->getDeclContext()) @@ -1323,7 +1322,7 @@ } } -const ObjCPropertyDecl * +ObjCPropertyDecl const * ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const { Selector Sel = getSelector(); unsigned NumArgs = Sel.getNumArgs(); @@ -1331,7 +1330,7 @@ return nullptr; if (isPropertyAccessor()) { - const auto *Container = cast(getParent()); + auto const *Container = cast(getParent()); // For accessor stubs, go back to the interface. if (auto *ImplDecl = dyn_cast(Container)) if (isSynthesizedAccessorStub()) @@ -1343,18 +1342,16 @@ /// Local function that attempts to find a matching property within the /// given Objective-C container. auto findMatchingProperty = - [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * { + [&](ObjCContainerDecl const *Container) -> ObjCPropertyDecl const * { if (IsInstance) { for (const auto *I : Container->instance_properties()) { - Selector NextSel = IsGetter ? I->getGetterName() - : I->getSetterName(); + Selector NextSel = IsGetter ? I->getGetterName() : I->getSetterName(); if (NextSel == Sel) return I; } } else { for (const auto *I : Container->class_properties()) { - Selector NextSel = IsGetter ? I->getGetterName() - : I->getSetterName(); + Selector NextSel = IsGetter ? I->getGetterName() : I->getSetterName(); if (NextSel == Sel) return I; } @@ -1364,14 +1361,14 @@ }; // Look in the container we were given. - if (const auto *Found = findMatchingProperty(Container)) + if (auto const *Found = findMatchingProperty(Container)) return Found; // If we're in a category or extension, look in the main class. - const ObjCInterfaceDecl *ClassDecl = nullptr; - if (const auto *Category = dyn_cast(Container)) { + ObjCInterfaceDecl const *ClassDecl = nullptr; + if (auto const *Category = dyn_cast(Container)) { ClassDecl = Category->getClassInterface(); - if (const auto *Found = findMatchingProperty(ClassDecl)) + if (auto const *Found = findMatchingProperty(ClassDecl)) return Found; } else { // Determine whether the container is a class. @@ -1380,19 +1377,19 @@ assert(ClassDecl && "Failed to find main class"); // If we have a class, check its visible extensions. - for (const auto *Ext : ClassDecl->visible_extensions()) { + for (auto const *Ext : ClassDecl->visible_extensions()) { if (Ext == Container) continue; - if (const auto *Found = findMatchingProperty(Ext)) + if (auto const *Found = findMatchingProperty(Ext)) return Found; } assert(isSynthesizedAccessorStub() && "expected an accessor stub"); - for (const auto *Cat : ClassDecl->known_categories()) { + for (auto const *Cat : ClassDecl->known_categories()) { if (Cat == Container) continue; - if (const auto *Found = findMatchingProperty(Cat)) + if (auto const *Found = findMatchingProperty(Cat)) return Found; } @@ -1402,12 +1399,12 @@ if (!CheckOverrides) return nullptr; - using OverridesTy = SmallVector; + using OverridesTy = SmallVector; OverridesTy Overrides; getOverriddenMethods(Overrides); - for (const auto *Override : Overrides) - if (const ObjCPropertyDecl *Prop = Override->findPropertyDecl(false)) + for (auto const *Override : Overrides) + if (ObjCPropertyDecl const *Prop = Override->findPropertyDecl(false)) return Prop; return nullptr; @@ -1419,17 +1416,13 @@ void ObjCTypeParamDecl::anchor() {} -ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc, - ObjCTypeParamVariance variance, - SourceLocation varianceLoc, - unsigned index, - SourceLocation nameLoc, - IdentifierInfo *name, - SourceLocation colonLoc, - TypeSourceInfo *boundInfo) { +ObjCTypeParamDecl *ObjCTypeParamDecl::Create( + ASTContext &ctx, DeclContext *dc, ObjCTypeParamVariance variance, + SourceLocation varianceLoc, unsigned index, SourceLocation nameLoc, + IdentifierInfo *name, SourceLocation colonLoc, TypeSourceInfo *boundInfo) { auto *TPDecl = - new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index, - nameLoc, name, colonLoc, boundInfo); + new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index, + nameLoc, name, colonLoc, boundInfo); QualType TPType = ctx.getObjCTypeParamType(TPDecl, {}); TPDecl->setTypeForDecl(TPType.getTypePtr()); return TPDecl; @@ -1437,10 +1430,9 @@ ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx, unsigned ID) { - return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr, - ObjCTypeParamVariance::Invariant, - SourceLocation(), 0, SourceLocation(), - nullptr, SourceLocation(), nullptr); + return new (ctx, ID) ObjCTypeParamDecl( + ctx, nullptr, ObjCTypeParamVariance::Invariant, SourceLocation(), 0, + SourceLocation(), nullptr, SourceLocation(), nullptr); } SourceRange ObjCTypeParamDecl::getSourceRange() const { @@ -1449,8 +1441,7 @@ startLoc = getLocation(); if (hasExplicitBound()) { - return SourceRange(startLoc, - getTypeSourceInfo()->getTypeLoc().getEndLoc()); + return SourceRange(startLoc, getTypeSourceInfo()->getTypeLoc().getEndLoc()); } return SourceRange(startLoc); @@ -1466,11 +1457,10 @@ std::copy(typeParams.begin(), typeParams.end(), begin()); } -ObjCTypeParamList *ObjCTypeParamList::create( - ASTContext &ctx, - SourceLocation lAngleLoc, - ArrayRef typeParams, - SourceLocation rAngleLoc) { +ObjCTypeParamList * +ObjCTypeParamList::create(ASTContext &ctx, SourceLocation lAngleLoc, + ArrayRef typeParams, + SourceLocation rAngleLoc) { void *mem = ctx.Allocate(totalSizeToAlloc(typeParams.size()), alignof(ObjCTypeParamList)); @@ -1478,7 +1468,7 @@ } void ObjCTypeParamList::gatherDefaultTypeArgs( - SmallVectorImpl &typeArgs) const { + SmallVectorImpl &typeArgs) const { typeArgs.reserve(size()); for (auto typeParam : *this) typeArgs.push_back(typeParam->getUnderlyingType()); @@ -1488,32 +1478,27 @@ // ObjCInterfaceDecl //===----------------------------------------------------------------------===// -ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C, - DeclContext *DC, - SourceLocation atLoc, - IdentifierInfo *Id, - ObjCTypeParamList *typeParamList, - ObjCInterfaceDecl *PrevDecl, - SourceLocation ClassLoc, - bool isInternal){ - auto *Result = new (C, DC) - ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl, - isInternal); +ObjCInterfaceDecl *ObjCInterfaceDecl::Create( + ASTContext const &C, DeclContext *DC, SourceLocation atLoc, + IdentifierInfo *Id, ObjCTypeParamList *typeParamList, + ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc, bool isInternal) { + auto *Result = new (C, DC) ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, + ClassLoc, PrevDecl, isInternal); Result->Data.setInt(!C.getLangOpts().Modules); C.getObjCInterfaceType(Result, PrevDecl); return Result; } -ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C, +ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(ASTContext const &C, unsigned ID) { - auto *Result = new (C, ID) - ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr, - SourceLocation(), nullptr, false); + auto *Result = + new (C, ID) ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, + nullptr, SourceLocation(), nullptr, false); Result->Data.setInt(!C.getLangOpts().Modules); return Result; } -ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, +ObjCInterfaceDecl::ObjCInterfaceDecl(ASTContext const &C, DeclContext *DC, SourceLocation AtLoc, IdentifierInfo *Id, ObjCTypeParamList *typeParamList, SourceLocation CLoc, @@ -1536,7 +1521,7 @@ assert(data().ExternallyCompleted && "Class is not externally completed"); data().ExternallyCompleted = false; getASTContext().getExternalSource()->CompleteType( - const_cast(this)); + const_cast(this)); } void ObjCInterfaceDecl::setExternallyCompleted() { @@ -1564,30 +1549,28 @@ return data().HasDesignatedInitializers; } -StringRef -ObjCInterfaceDecl::getObjCRuntimeNameAsString() const { - if (const auto *ObjCRTName = getAttr()) +StringRef ObjCInterfaceDecl::getObjCRuntimeNameAsString() const { + if (auto const *ObjCRTName = getAttr()) return ObjCRTName->getMetadataName(); return getName(); } -StringRef -ObjCImplementationDecl::getObjCRuntimeNameAsString() const { +StringRef ObjCImplementationDecl::getObjCRuntimeNameAsString() const { if (ObjCInterfaceDecl *ID = - const_cast(this)->getClassInterface()) + const_cast(this)->getClassInterface()) return ID->getObjCRuntimeNameAsString(); return getName(); } ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const { - if (const ObjCInterfaceDecl *Def = getDefinition()) { + if (ObjCInterfaceDecl const *Def = getDefinition()) { if (data().ExternallyCompleted) LoadExternalDefinition(); return getASTContext().getObjCImplementation( - const_cast(Def)); + const_cast(Def)); } // FIXME: Should make sure no callers ever do this. @@ -1608,9 +1591,8 @@ : Size(size), Ivar(ivar) {} }; -bool operator<(const SynthesizeIvarChunk & LHS, - const SynthesizeIvarChunk &RHS) { - return LHS.Size < RHS.Size; +bool operator<(SynthesizeIvarChunk const &LHS, SynthesizeIvarChunk const &RHS) { + return LHS.Size < RHS.Size; } } // namespace @@ -1633,21 +1615,22 @@ if (!data().IvarList) { if (!ivar_empty()) { ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end(); - data().IvarList = *I; ++I; + data().IvarList = *I; + ++I; for (curIvar = data().IvarList; I != E; curIvar = *I, ++I) curIvar->setNextIvar(*I); } - for (const auto *Ext : known_extensions()) { + for (auto const *Ext : known_extensions()) { if (!Ext->ivar_empty()) { - ObjCCategoryDecl::ivar_iterator - I = Ext->ivar_begin(), - E = Ext->ivar_end(); + ObjCCategoryDecl::ivar_iterator I = Ext->ivar_begin(), + E = Ext->ivar_end(); if (!data().IvarList) { - data().IvarList = *I; ++I; + data().IvarList = *I; + ++I; curIvar = data().IvarList; } - for ( ;I != E; curIvar = *I, ++I) + for (; I != E; curIvar = *I, ++I) curIvar->setNextIvar(*I); } } @@ -1656,7 +1639,7 @@ // cached and complete! if (!data().IvarListMissingImplementation) - return data().IvarList; + return data().IvarList; if (ObjCImplementationDecl *ImplDecl = getImplementation()) { data().IvarListMissingImplementation = false; @@ -1665,7 +1648,7 @@ for (auto *IV : ImplDecl->ivars()) { if (IV->getSynthesize() && !IV->isInvalidDecl()) { layout.push_back(SynthesizeIvarChunk( - IV->getASTContext().getTypeSize(IV->getType()), IV)); + IV->getASTContext().getTypeSize(IV->getType()), IV)); continue; } if (!data().IvarList) @@ -1680,10 +1663,11 @@ llvm::stable_sort(layout); unsigned Ix = 0, EIx = layout.size(); if (!data().IvarList) { - data().IvarList = layout[0].Ivar; Ix++; + data().IvarList = layout[0].Ivar; + Ix++; curIvar = data().IvarList; } - for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++) + for (; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++) curIvar->setNextIvar(layout[Ix].Ivar); } } @@ -1713,7 +1697,7 @@ ObjCMethodDecl * ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const { - for (const auto *Cat : visible_categories()) { + for (auto const *Cat : visible_categories()) { if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel)) return MD; @@ -1723,7 +1707,7 @@ } ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const { - for (const auto *Cat : visible_categories()) { + for (auto const *Cat : visible_categories()) { if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel)) return MD; @@ -1736,14 +1720,14 @@ /// has been implemented in IDecl class, its super class or categories (if /// lookupCategory is true). bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, - bool lookupCategory, - bool RHSIsQualifiedID) { + bool lookupCategory, + bool RHSIsQualifiedID) { if (!hasDefinition()) return false; ObjCInterfaceDecl *IDecl = this; // 1st, look up the class. - for (auto *PI : IDecl->protocols()){ + for (auto *PI : IDecl->protocols()) { if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) return true; // This is dubious and is added to be compatible with gcc. In gcc, it is @@ -1759,7 +1743,7 @@ // 2nd, look up the category. if (lookupCategory) - for (const auto *Cat : visible_categories()) { + for (auto const *Cat : visible_categories()) { for (auto *PI : Cat->protocols()) if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) return true; @@ -1767,9 +1751,8 @@ // 3rd, look up the super class(s) if (IDecl->getSuperClass()) - return - IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory, - RHSIsQualifiedID); + return IDecl->getSuperClass()->ClassImplementsProtocol( + lProto, lookupCategory, RHSIsQualifiedID); return false; } @@ -1812,18 +1795,18 @@ ID->setIvarList(nullptr); } - return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW, - synthesized); + return new (C, DC) + ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW, synthesized); } ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(), - nullptr, QualType(), nullptr, - ObjCIvarDecl::None, nullptr, false); + return new (C, ID) + ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(), nullptr, + QualType(), nullptr, ObjCIvarDecl::None, nullptr, false); } -const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const { - const auto *DC = cast(getDeclContext()); +ObjCInterfaceDecl const *ObjCIvarDecl::getContainingInterface() const { + auto const *DC = cast(getDeclContext()); switch (DC->getKind()) { default: @@ -1833,7 +1816,7 @@ // Ivars can only appear in class extension categories. case ObjCCategory: { - const auto *CD = cast(DC); + auto const *CD = cast(DC); assert(CD->IsClassExtension() && "invalid container for ivar!"); return CD->getClassInterface(); } @@ -1857,18 +1840,19 @@ void ObjCAtDefsFieldDecl::anchor() {} -ObjCAtDefsFieldDecl -*ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation StartLoc, SourceLocation IdLoc, - IdentifierInfo *Id, QualType T, Expr *BW) { +ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC, + SourceLocation StartLoc, + SourceLocation IdLoc, + IdentifierInfo *Id, QualType T, + Expr *BW) { return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW); } ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(), - SourceLocation(), nullptr, QualType(), - nullptr); + return new (C, ID) + ObjCAtDefsFieldDecl(nullptr, SourceLocation(), SourceLocation(), nullptr, + QualType(), nullptr); } //===----------------------------------------------------------------------===// @@ -1901,9 +1885,8 @@ ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - ObjCProtocolDecl *Result = - new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(), - SourceLocation(), nullptr); + ObjCProtocolDecl *Result = new (C, ID) ObjCProtocolDecl( + C, nullptr, nullptr, SourceLocation(), SourceLocation(), nullptr); Result->Data.setInt(!C.getLangOpts().Modules); return Result; } @@ -1913,15 +1896,15 @@ } void ObjCProtocolDecl::getImpliedProtocols( - llvm::DenseSet &IPs) const { - std::queue WorkQueue; + llvm::DenseSet &IPs) const { + std::queue WorkQueue; WorkQueue.push(this); while (!WorkQueue.empty()) { - const auto *PD = WorkQueue.front(); + auto const *PD = WorkQueue.front(); WorkQueue.pop(); - for (const auto *Parent : PD->protocols()) { - const auto *Can = Parent->getCanonicalDecl(); + for (auto const *Parent : PD->protocols()) { + auto const *Can = Parent->getCanonicalDecl(); auto Result = IPs.insert(Can); if (Result.second) WorkQueue.push(Parent); @@ -1950,14 +1933,14 @@ // If there is no definition or the definition is hidden, we don't find // anything. - const ObjCProtocolDecl *Def = getDefinition(); + ObjCProtocolDecl const *Def = getDefinition(); if (!Def || !Def->isUnconditionallyVisible()) return nullptr; if ((MethodDecl = getMethod(Sel, isInstance))) return MethodDecl; - for (const auto *I : protocols()) + for (auto const *I : protocols()) if ((MethodDecl = I->lookupMethod(Sel, isInstance))) return MethodDecl; return nullptr; @@ -1977,9 +1960,9 @@ RD->Data = this->Data; } -void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM, - PropertyDeclOrder &PO) const { - if (const ObjCProtocolDecl *PDecl = getDefinition()) { +void ObjCProtocolDecl::collectPropertiesToImplement( + PropertyMap &PM, PropertyDeclOrder &PO) const { + if (ObjCProtocolDecl const *PDecl = getDefinition()) { for (auto *Prop : PDecl->properties()) { // Insert into PM if not there already. PM.insert(std::make_pair( @@ -1988,15 +1971,15 @@ PO.push_back(Prop); } // Scan through protocol's protocols. - for (const auto *PI : PDecl->protocols()) + for (auto const *PI : PDecl->protocols()) PI->collectPropertiesToImplement(PM, PO); } } void ObjCProtocolDecl::collectInheritedProtocolProperties( - const ObjCPropertyDecl *Property, ProtocolPropertySet &PS, + ObjCPropertyDecl const *Property, ProtocolPropertySet &PS, PropertyDeclOrder &PO) const { - if (const ObjCProtocolDecl *PDecl = getDefinition()) { + if (ObjCProtocolDecl const *PDecl = getDefinition()) { if (!PS.insert(PDecl).second) return; for (auto *Prop : PDecl->properties()) { @@ -2008,14 +1991,13 @@ } } // Scan through protocol's protocols which did not have a matching property. - for (const auto *PI : PDecl->protocols()) + for (auto const *PI : PDecl->protocols()) PI->collectInheritedProtocolProperties(Property, PS, PO); } } -StringRef -ObjCProtocolDecl::getObjCRuntimeNameAsString() const { - if (const auto *ObjCRTName = getAttr()) +StringRef ObjCProtocolDecl::getObjCRuntimeNameAsString() const { + if (auto const *ObjCRTName = getAttr()) return ObjCRTName->getMetadataName(); return getName(); @@ -2040,19 +2022,15 @@ setTypeParamList(typeParamList); } -ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation AtLoc, - SourceLocation ClassNameLoc, - SourceLocation CategoryNameLoc, - IdentifierInfo *Id, - ObjCInterfaceDecl *IDecl, - ObjCTypeParamList *typeParamList, - SourceLocation IvarLBraceLoc, - SourceLocation IvarRBraceLoc) { - auto *CatDecl = - new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id, - IDecl, typeParamList, IvarLBraceLoc, - IvarRBraceLoc); +ObjCCategoryDecl *ObjCCategoryDecl::Create( + ASTContext &C, DeclContext *DC, SourceLocation AtLoc, + SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc, + IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, + ObjCTypeParamList *typeParamList, SourceLocation IvarLBraceLoc, + SourceLocation IvarRBraceLoc) { + auto *CatDecl = new (C, DC) + ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id, IDecl, + typeParamList, IvarLBraceLoc, IvarRBraceLoc); if (IDecl) { // Link this category into its class's category list. CatDecl->NextClassCategory = IDecl->getCategoryListRaw(); @@ -2068,14 +2046,14 @@ ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(), - SourceLocation(), SourceLocation(), - nullptr, nullptr, nullptr); + return new (C, ID) + ObjCCategoryDecl(nullptr, SourceLocation(), SourceLocation(), + SourceLocation(), nullptr, nullptr, nullptr); } ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const { return getASTContext().getObjCImplementation( - const_cast(this)); + const_cast(this)); } void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) { @@ -2098,11 +2076,9 @@ void ObjCCategoryImplDecl::anchor() {} ObjCCategoryImplDecl * -ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, - IdentifierInfo *Id, +ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, IdentifierInfo *Id, ObjCInterfaceDecl *ClassInterface, - SourceLocation nameLoc, - SourceLocation atStartLoc, + SourceLocation nameLoc, SourceLocation atStartLoc, SourceLocation CategoryNameLoc) { if (ClassInterface && ClassInterface->hasDefinition()) ClassInterface = ClassInterface->getDefinition(); @@ -2112,14 +2088,14 @@ ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr, - SourceLocation(), SourceLocation(), - SourceLocation()); + return new (C, ID) + ObjCCategoryImplDecl(nullptr, nullptr, nullptr, SourceLocation(), + SourceLocation(), SourceLocation()); } ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const { // The class interface might be NULL if we are working with invalid code. - if (const ObjCInterfaceDecl *ID = getClassInterface()) + if (ObjCInterfaceDecl const *ID = getClassInterface()) return ID->FindCategoryDeclaration(getIdentifier()); return nullptr; } @@ -2150,8 +2126,8 @@ /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of /// properties implemented in this \@implementation block and returns /// the implemented property that uses it. -ObjCPropertyImplDecl *ObjCImplDecl:: -FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const { +ObjCPropertyImplDecl * +ObjCImplDecl::FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const { for (auto *PID : property_impls()) if (PID->getPropertyIvarDecl() && PID->getPropertyIvarDecl()->getIdentifier() == ivarId) @@ -2162,9 +2138,9 @@ /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl /// added to the list of those properties \@synthesized/\@dynamic in this /// category \@implementation block. -ObjCPropertyImplDecl *ObjCImplDecl:: -FindPropertyImplDecl(IdentifierInfo *Id, - ObjCPropertyQueryKind QueryKind) const { +ObjCPropertyImplDecl * +ObjCImplDecl::FindPropertyImplDecl(IdentifierInfo *Id, + ObjCPropertyQueryKind QueryKind) const { ObjCPropertyImplDecl *ClassPropImpl = nullptr; for (auto *PID : property_impls()) // If queryKind is unknown, we return the instance property if one @@ -2190,7 +2166,7 @@ } raw_ostream &clang::operator<<(raw_ostream &OS, - const ObjCCategoryImplDecl &CID) { + ObjCCategoryImplDecl const &CID) { OS << CID.getName(); return OS; } @@ -2201,20 +2177,16 @@ void ObjCImplementationDecl::anchor() {} -ObjCImplementationDecl * -ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, - ObjCInterfaceDecl *ClassInterface, - ObjCInterfaceDecl *SuperDecl, - SourceLocation nameLoc, - SourceLocation atStartLoc, - SourceLocation superLoc, - SourceLocation IvarLBraceLoc, - SourceLocation IvarRBraceLoc) { +ObjCImplementationDecl *ObjCImplementationDecl::Create( + ASTContext &C, DeclContext *DC, ObjCInterfaceDecl *ClassInterface, + ObjCInterfaceDecl *SuperDecl, SourceLocation nameLoc, + SourceLocation atStartLoc, SourceLocation superLoc, + SourceLocation IvarLBraceLoc, SourceLocation IvarRBraceLoc) { if (ClassInterface && ClassInterface->hasDefinition()) ClassInterface = ClassInterface->getDefinition(); - return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl, - nameLoc, atStartLoc, superLoc, - IvarLBraceLoc, IvarRBraceLoc); + return new (C, DC) + ObjCImplementationDecl(DC, ClassInterface, SuperDecl, nameLoc, atStartLoc, + superLoc, IvarLBraceLoc, IvarRBraceLoc); } ObjCImplementationDecl * @@ -2223,14 +2195,14 @@ SourceLocation(), SourceLocation()); } -void ObjCImplementationDecl::setIvarInitializers(ASTContext &C, - CXXCtorInitializer ** initializers, - unsigned numInitializers) { +void ObjCImplementationDecl::setIvarInitializers( + ASTContext &C, CXXCtorInitializer **initializers, + unsigned numInitializers) { if (numInitializers > 0) { NumIvarInitializers = numInitializers; - auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers]; + auto **ivarInitializers = new (C) CXXCtorInitializer *[NumIvarInitializers]; memcpy(ivarInitializers, initializers, - numInitializers * sizeof(CXXCtorInitializer*)); + numInitializers * sizeof(CXXCtorInitializer *)); IvarInitializers = ivarInitializers; } } @@ -2241,7 +2213,7 @@ } raw_ostream &clang::operator<<(raw_ostream &OS, - const ObjCImplementationDecl &ID) { + ObjCImplementationDecl const &ID) { OS << ID.getName(); return OS; } @@ -2254,16 +2226,15 @@ ObjCCompatibleAliasDecl * ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation L, - IdentifierInfo *Id, - ObjCInterfaceDecl* AliasedClass) { + SourceLocation L, IdentifierInfo *Id, + ObjCInterfaceDecl *AliasedClass) { return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass); } ObjCCompatibleAliasDecl * ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(), - nullptr, nullptr); + return new (C, ID) + ObjCCompatibleAliasDecl(nullptr, SourceLocation(), nullptr, nullptr); } //===----------------------------------------------------------------------===// @@ -2273,22 +2244,20 @@ void ObjCPropertyDecl::anchor() {} ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC, - SourceLocation L, - IdentifierInfo *Id, + SourceLocation L, IdentifierInfo *Id, SourceLocation AtLoc, - SourceLocation LParenLoc, - QualType T, + SourceLocation LParenLoc, QualType T, TypeSourceInfo *TSI, PropertyControl propControl) { - return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI, - propControl); + return new (C, DC) + ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI, propControl); } ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr, - SourceLocation(), SourceLocation(), - QualType(), nullptr, None); + return new (C, ID) + ObjCPropertyDecl(nullptr, SourceLocation(), nullptr, SourceLocation(), + SourceLocation(), QualType(), nullptr, None); } QualType ObjCPropertyDecl::getUsageType(QualType objectType) const { @@ -2305,23 +2274,20 @@ // ObjCPropertyImplDecl //===----------------------------------------------------------------------===// -ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C, - DeclContext *DC, - SourceLocation atLoc, - SourceLocation L, - ObjCPropertyDecl *property, - Kind PK, - ObjCIvarDecl *ivar, - SourceLocation ivarLoc) { - return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar, - ivarLoc); +ObjCPropertyImplDecl * +ObjCPropertyImplDecl::Create(ASTContext &C, DeclContext *DC, + SourceLocation atLoc, SourceLocation L, + ObjCPropertyDecl *property, Kind PK, + ObjCIvarDecl *ivar, SourceLocation ivarLoc) { + return new (C, DC) + ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar, ivarLoc); } ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(), - SourceLocation(), nullptr, Dynamic, - nullptr, SourceLocation()); + return new (C, ID) + ObjCPropertyImplDecl(nullptr, SourceLocation(), SourceLocation(), nullptr, + Dynamic, nullptr, SourceLocation()); } SourceRange ObjCPropertyImplDecl::getSourceRange() const { Index: clang/lib/AST/DeclOpenMP.cpp =================================================================== --- clang/lib/AST/DeclOpenMP.cpp +++ clang/lib/AST/DeclOpenMP.cpp @@ -11,10 +11,10 @@ /// //===----------------------------------------------------------------------===// +#include "clang/AST/DeclOpenMP.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclBase.h" -#include "clang/AST/DeclOpenMP.h" #include "clang/AST/Expr.h" using namespace clang; @@ -52,7 +52,7 @@ // OMPAllocateDecl Implementation. //===----------------------------------------------------------------------===// -void OMPAllocateDecl::anchor() { } +void OMPAllocateDecl::anchor() {} OMPAllocateDecl *OMPAllocateDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, ArrayRef VL, @@ -127,7 +127,7 @@ return cast_or_null( PrevDeclInScope.get(getASTContext().getExternalSource())); } -const OMPDeclareReductionDecl * +OMPDeclareReductionDecl const * OMPDeclareReductionDecl::getPrevDeclInScope() const { return cast_or_null( PrevDeclInScope.get(getASTContext().getExternalSource())); @@ -160,7 +160,7 @@ PrevDeclInScope.get(getASTContext().getExternalSource())); } -const OMPDeclareMapperDecl *OMPDeclareMapperDecl::getPrevDeclInScope() const { +OMPDeclareMapperDecl const *OMPDeclareMapperDecl::getPrevDeclInScope() const { return cast_or_null( PrevDeclInScope.get(getASTContext().getExternalSource())); } Index: clang/lib/AST/DeclPrinter.cpp =================================================================== --- clang/lib/AST/DeclPrinter.cpp +++ clang/lib/AST/DeclPrinter.cpp @@ -25,123 +25,123 @@ using namespace clang; namespace { - class DeclPrinter : public DeclVisitor { - raw_ostream &Out; - PrintingPolicy Policy; - const ASTContext &Context; - unsigned Indentation; - bool PrintInstantiation; - - raw_ostream& Indent() { return Indent(Indentation); } - raw_ostream& Indent(unsigned Indentation); - void ProcessDeclGroup(SmallVectorImpl& Decls); - - void Print(AccessSpecifier AS); - void PrintConstructorInitializers(CXXConstructorDecl *CDecl, - std::string &Proto); - - /// Print an Objective-C method type in parentheses. - /// - /// \param Quals The Objective-C declaration qualifiers. - /// \param T The type to print. - void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals, - QualType T); - - void PrintObjCTypeParams(ObjCTypeParamList *Params); - - public: - DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy, - const ASTContext &Context, unsigned Indentation = 0, - bool PrintInstantiation = false) - : Out(Out), Policy(Policy), Context(Context), Indentation(Indentation), - PrintInstantiation(PrintInstantiation) {} - - void VisitDeclContext(DeclContext *DC, bool Indent = true); - - void VisitTranslationUnitDecl(TranslationUnitDecl *D); - void VisitTypedefDecl(TypedefDecl *D); - void VisitTypeAliasDecl(TypeAliasDecl *D); - void VisitEnumDecl(EnumDecl *D); - void VisitRecordDecl(RecordDecl *D); - void VisitEnumConstantDecl(EnumConstantDecl *D); - void VisitEmptyDecl(EmptyDecl *D); - void VisitFunctionDecl(FunctionDecl *D); - void VisitFriendDecl(FriendDecl *D); - void VisitFieldDecl(FieldDecl *D); - void VisitVarDecl(VarDecl *D); - void VisitLabelDecl(LabelDecl *D); - void VisitParmVarDecl(ParmVarDecl *D); - void VisitFileScopeAsmDecl(FileScopeAsmDecl *D); - void VisitImportDecl(ImportDecl *D); - void VisitStaticAssertDecl(StaticAssertDecl *D); - void VisitNamespaceDecl(NamespaceDecl *D); - void VisitUsingDirectiveDecl(UsingDirectiveDecl *D); - void VisitNamespaceAliasDecl(NamespaceAliasDecl *D); - void VisitCXXRecordDecl(CXXRecordDecl *D); - void VisitLinkageSpecDecl(LinkageSpecDecl *D); - void VisitTemplateDecl(const TemplateDecl *D); - void VisitFunctionTemplateDecl(FunctionTemplateDecl *D); - void VisitClassTemplateDecl(ClassTemplateDecl *D); - void VisitClassTemplateSpecializationDecl( - ClassTemplateSpecializationDecl *D); - void VisitClassTemplatePartialSpecializationDecl( - ClassTemplatePartialSpecializationDecl *D); - void VisitObjCMethodDecl(ObjCMethodDecl *D); - void VisitObjCImplementationDecl(ObjCImplementationDecl *D); - void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); - void VisitObjCProtocolDecl(ObjCProtocolDecl *D); - void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); - void VisitObjCCategoryDecl(ObjCCategoryDecl *D); - void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D); - void VisitObjCPropertyDecl(ObjCPropertyDecl *D); - void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); - void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); - void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); - void VisitUsingDecl(UsingDecl *D); - void VisitUsingEnumDecl(UsingEnumDecl *D); - void VisitUsingShadowDecl(UsingShadowDecl *D); - void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D); - void VisitOMPAllocateDecl(OMPAllocateDecl *D); - void VisitOMPRequiresDecl(OMPRequiresDecl *D); - void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D); - void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D); - void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D); - void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP); - void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *NTTP); - - void printTemplateParameters(const TemplateParameterList *Params, - bool OmitTemplateKW = false); - void printTemplateArguments(llvm::ArrayRef Args, - const TemplateParameterList *Params, - bool TemplOverloaded); - void printTemplateArguments(llvm::ArrayRef Args, - const TemplateParameterList *Params, - bool TemplOverloaded); - void prettyPrintAttributes(Decl *D); - void prettyPrintPragmas(Decl *D); - void printDeclType(QualType T, StringRef DeclName, bool Pack = false); - }; -} +class DeclPrinter : public DeclVisitor { + raw_ostream &Out; + PrintingPolicy Policy; + ASTContext const &Context; + unsigned Indentation; + bool PrintInstantiation; + + raw_ostream &Indent() { return Indent(Indentation); } + raw_ostream &Indent(unsigned Indentation); + void ProcessDeclGroup(SmallVectorImpl &Decls); + + void Print(AccessSpecifier AS); + void PrintConstructorInitializers(CXXConstructorDecl *CDecl, + std::string &Proto); + + /// Print an Objective-C method type in parentheses. + /// + /// \param Quals The Objective-C declaration qualifiers. + /// \param T The type to print. + void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals, + QualType T); + + void PrintObjCTypeParams(ObjCTypeParamList *Params); + +public: + DeclPrinter(raw_ostream &Out, PrintingPolicy const &Policy, + ASTContext const &Context, unsigned Indentation = 0, + bool PrintInstantiation = false) + : Out(Out), Policy(Policy), Context(Context), Indentation(Indentation), + PrintInstantiation(PrintInstantiation) {} + + void VisitDeclContext(DeclContext *DC, bool Indent = true); + + void VisitTranslationUnitDecl(TranslationUnitDecl *D); + void VisitTypedefDecl(TypedefDecl *D); + void VisitTypeAliasDecl(TypeAliasDecl *D); + void VisitEnumDecl(EnumDecl *D); + void VisitRecordDecl(RecordDecl *D); + void VisitEnumConstantDecl(EnumConstantDecl *D); + void VisitEmptyDecl(EmptyDecl *D); + void VisitFunctionDecl(FunctionDecl *D); + void VisitFriendDecl(FriendDecl *D); + void VisitFieldDecl(FieldDecl *D); + void VisitVarDecl(VarDecl *D); + void VisitLabelDecl(LabelDecl *D); + void VisitParmVarDecl(ParmVarDecl *D); + void VisitFileScopeAsmDecl(FileScopeAsmDecl *D); + void VisitImportDecl(ImportDecl *D); + void VisitStaticAssertDecl(StaticAssertDecl *D); + void VisitNamespaceDecl(NamespaceDecl *D); + void VisitUsingDirectiveDecl(UsingDirectiveDecl *D); + void VisitNamespaceAliasDecl(NamespaceAliasDecl *D); + void VisitCXXRecordDecl(CXXRecordDecl *D); + void VisitLinkageSpecDecl(LinkageSpecDecl *D); + void VisitTemplateDecl(TemplateDecl const *D); + void VisitFunctionTemplateDecl(FunctionTemplateDecl *D); + void VisitClassTemplateDecl(ClassTemplateDecl *D); + void VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D); + void VisitClassTemplatePartialSpecializationDecl( + ClassTemplatePartialSpecializationDecl *D); + void VisitObjCMethodDecl(ObjCMethodDecl *D); + void VisitObjCImplementationDecl(ObjCImplementationDecl *D); + void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); + void VisitObjCProtocolDecl(ObjCProtocolDecl *D); + void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); + void VisitObjCCategoryDecl(ObjCCategoryDecl *D); + void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D); + void VisitObjCPropertyDecl(ObjCPropertyDecl *D); + void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); + void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); + void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); + void VisitUsingDecl(UsingDecl *D); + void VisitUsingEnumDecl(UsingEnumDecl *D); + void VisitUsingShadowDecl(UsingShadowDecl *D); + void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D); + void VisitOMPAllocateDecl(OMPAllocateDecl *D); + void VisitOMPRequiresDecl(OMPRequiresDecl *D); + void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D); + void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D); + void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D); + void VisitTemplateTypeParmDecl(TemplateTypeParmDecl const *TTP); + void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl const *NTTP); + + void printTemplateParameters(TemplateParameterList const *Params, + bool OmitTemplateKW = false); + void printTemplateArguments(llvm::ArrayRef Args, + TemplateParameterList const *Params, + bool TemplOverloaded); + void printTemplateArguments(llvm::ArrayRef Args, + TemplateParameterList const *Params, + bool TemplOverloaded); + void prettyPrintAttributes(Decl *D); + void prettyPrintPragmas(Decl *D); + void printDeclType(QualType T, StringRef DeclName, bool Pack = false); +}; +} // namespace void Decl::print(raw_ostream &Out, unsigned Indentation, bool PrintInstantiation) const { - print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation); + print(Out, getASTContext().getPrintingPolicy(), Indentation, + PrintInstantiation); } -void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy, +void Decl::print(raw_ostream &Out, PrintingPolicy const &Policy, unsigned Indentation, bool PrintInstantiation) const { DeclPrinter Printer(Out, Policy, getASTContext(), Indentation, PrintInstantiation); - Printer.Visit(const_cast(this)); + Printer.Visit(const_cast(this)); } -void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context, +void TemplateParameterList::print(raw_ostream &Out, ASTContext const &Context, bool OmitTemplateKW) const { print(Out, Context, Context.getPrintingPolicy(), OmitTemplateKW); } -void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context, - const PrintingPolicy &Policy, +void TemplateParameterList::print(raw_ostream &Out, ASTContext const &Context, + PrintingPolicy const &Policy, bool OmitTemplateKW) const { DeclPrinter Printer(Out, Policy, Context); Printer.printTemplateParameters(this, OmitTemplateKW); @@ -151,21 +151,21 @@ // FIXME: This should be on the Type class! QualType BaseType = T; while (!BaseType->isSpecifierType()) { - if (const PointerType *PTy = BaseType->getAs()) + if (PointerType const *PTy = BaseType->getAs()) BaseType = PTy->getPointeeType(); - else if (const BlockPointerType *BPy = BaseType->getAs()) + else if (BlockPointerType const *BPy = BaseType->getAs()) BaseType = BPy->getPointeeType(); - else if (const ArrayType* ATy = dyn_cast(BaseType)) + else if (ArrayType const *ATy = dyn_cast(BaseType)) BaseType = ATy->getElementType(); - else if (const FunctionType* FTy = BaseType->getAs()) + else if (FunctionType const *FTy = BaseType->getAs()) BaseType = FTy->getReturnType(); - else if (const VectorType *VTy = BaseType->getAs()) + else if (VectorType const *VTy = BaseType->getAs()) BaseType = VTy->getElementType(); - else if (const ReferenceType *RTy = BaseType->getAs()) + else if (ReferenceType const *RTy = BaseType->getAs()) BaseType = RTy->getPointeeType(); - else if (const AutoType *ATy = BaseType->getAs()) + else if (AutoType const *ATy = BaseType->getAs()) BaseType = ATy->getDeducedType(); - else if (const ParenType *PTy = BaseType->getAs()) + else if (ParenType const *PTy = BaseType->getAs()) BaseType = PTy->desugar(); else // This must be a syntax error. @@ -174,38 +174,38 @@ return BaseType; } -static QualType getDeclType(Decl* D) { - if (TypedefNameDecl* TDD = dyn_cast(D)) +static QualType getDeclType(Decl *D) { + if (TypedefNameDecl *TDD = dyn_cast(D)) return TDD->getUnderlyingType(); - if (ValueDecl* VD = dyn_cast(D)) + if (ValueDecl *VD = dyn_cast(D)) return VD->getType(); return QualType(); } -void Decl::printGroup(Decl** Begin, unsigned NumDecls, - raw_ostream &Out, const PrintingPolicy &Policy, - unsigned Indentation) { +void Decl::printGroup(Decl **Begin, unsigned NumDecls, raw_ostream &Out, + PrintingPolicy const &Policy, unsigned Indentation) { if (NumDecls == 1) { (*Begin)->print(Out, Policy, Indentation); return; } - Decl** End = Begin + NumDecls; - TagDecl* TD = dyn_cast(*Begin); + Decl **End = Begin + NumDecls; + TagDecl *TD = dyn_cast(*Begin); if (TD) ++Begin; PrintingPolicy SubPolicy(Policy); bool isFirst = true; - for ( ; Begin != End; ++Begin) { + for (; Begin != End; ++Begin) { if (isFirst) { - if(TD) + if (TD) SubPolicy.IncludeTagDefinition = true; SubPolicy.SuppressSpecifiers = false; isFirst = false; } else { - if (!isFirst) Out << ", "; + if (!isFirst) + Out << ", "; SubPolicy.IncludeTagDefinition = false; SubPolicy.SuppressSpecifiers = true; } @@ -216,7 +216,7 @@ LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const { // Get the translation unit - const DeclContext *DC = this; + DeclContext const *DC = this; while (!DC->isTranslationUnit()) DC = DC->getParent(); @@ -225,7 +225,7 @@ Printer.VisitDeclContext(const_cast(this), /*Indent=*/false); } -raw_ostream& DeclPrinter::Indent(unsigned Indentation) { +raw_ostream &DeclPrinter::Indent(unsigned Indentation) { for (unsigned i = 0; i != Indentation; ++i) Out << " "; return Out; @@ -285,16 +285,15 @@ T.print(Out, Policy, (Pack ? "..." : "") + DeclName, Indentation); } -void DeclPrinter::ProcessDeclGroup(SmallVectorImpl& Decls) { +void DeclPrinter::ProcessDeclGroup(SmallVectorImpl &Decls) { this->Indent(); Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation); Out << ";\n"; Decls.clear(); - } void DeclPrinter::Print(AccessSpecifier AS) { - const auto AccessSpelling = getAccessSpelling(AS); + auto const AccessSpelling = getAccessSpelling(AS); if (AccessSpelling.empty()) llvm_unreachable("No access specifier!"); Out << AccessSpelling; @@ -303,7 +302,7 @@ void DeclPrinter::PrintConstructorInitializers(CXXConstructorDecl *CDecl, std::string &Proto) { bool HasInitializerList = false; - for (const auto *BMInitializer : CDecl->inits()) { + for (auto const *BMInitializer : CDecl->inits()) { if (BMInitializer->isInClassMemberInitializer()) continue; @@ -378,7 +377,7 @@ if (Indent) Indentation += Policy.Indentation; - SmallVector Decls; + SmallVector Decls; for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); D != DEnd; ++D) { @@ -444,7 +443,7 @@ Visit(*D); // FIXME: Need to be able to tell the DeclPrinter when - const char *Terminator = nullptr; + char const *Terminator = nullptr; if (isa(*D) || isa(*D) || isa(*D) || isa(*D) || isa(*D)) @@ -462,11 +461,9 @@ else Terminator = ";"; } else if (isa(*D) || isa(*D) || - isa(*D) || - isa(*D) || - isa(*D) || - isa(*D) || - isa(*D)) + isa(*D) || isa(*D) || + isa(*D) || isa(*D) || + isa(*D)) Terminator = nullptr; else if (isa(*D)) { DeclContext::decl_iterator Next = D; @@ -482,7 +479,9 @@ ((isa(*D) && cast(*D)->doesThisDeclarationHaveABody()) || (isa(*D) && - cast(*D)->getTemplatedDecl()->doesThisDeclarationHaveABody()))) + cast(*D) + ->getTemplatedDecl() + ->doesThisDeclarationHaveABody()))) ; // StmtPrinter already added '\n' after CompoundStmt. else Out << "\n"; @@ -576,7 +575,7 @@ static void printExplicitSpecifier(ExplicitSpecifier ES, llvm::raw_ostream &Out, PrintingPolicy &Policy, unsigned Indentation, - const ASTContext &Context) { + ASTContext const &Context) { std::string Proto = "explicit"; llvm::raw_string_ostream EOut(Proto); if (ES.getExpr()) { @@ -608,20 +607,32 @@ CXXDeductionGuideDecl *GuideDecl = dyn_cast(D); if (!Policy.SuppressSpecifiers) { switch (D->getStorageClass()) { - case SC_None: break; - case SC_Extern: Out << "extern "; break; - case SC_Static: Out << "static "; break; - case SC_PrivateExtern: Out << "__private_extern__ "; break; - case SC_Auto: case SC_Register: + case SC_None: + break; + case SC_Extern: + Out << "extern "; + break; + case SC_Static: + Out << "static "; + break; + case SC_PrivateExtern: + Out << "__private_extern__ "; + break; + case SC_Auto: + case SC_Register: llvm_unreachable("invalid for functions"); } - if (D->isInlineSpecified()) Out << "inline "; - if (D->isVirtualAsWritten()) Out << "virtual "; - if (D->isModulePrivate()) Out << "__module_private__ "; + if (D->isInlineSpecified()) + Out << "inline "; + if (D->isVirtualAsWritten()) + Out << "virtual "; + if (D->isModulePrivate()) + Out << "__module_private__ "; if (D->isConstexprSpecified() && !D->isExplicitlyDefaulted()) Out << "constexpr "; - if (D->isConsteval()) Out << "consteval "; + if (D->isConsteval()) + Out << "consteval "; ExplicitSpecifier ExplicitSpec = ExplicitSpecifier::getFromDecl(D); if (ExplicitSpec.isSpecified()) printExplicitSpecifier(ExplicitSpec, Out, Policy, Indentation, Context); @@ -636,7 +647,7 @@ } else { llvm::raw_string_ostream OS(Proto); if (!Policy.SuppressScope) { - if (const NestedNameSpecifier *NS = D->getQualifier()) { + if (NestedNameSpecifier const *NS = D->getQualifier()) { NS->print(OS, Policy); } } @@ -648,27 +659,27 @@ if (D->isFunctionTemplateSpecialization()) { llvm::raw_string_ostream POut(Proto); DeclPrinter TArgPrinter(POut, SubPolicy, Context, Indentation); - const auto *TArgAsWritten = D->getTemplateSpecializationArgsAsWritten(); - const TemplateParameterList *TPL = D->getTemplateSpecializationInfo() + auto const *TArgAsWritten = D->getTemplateSpecializationArgsAsWritten(); + TemplateParameterList const *TPL = D->getTemplateSpecializationInfo() ->getTemplate() ->getTemplateParameters(); if (TArgAsWritten && !Policy.PrintCanonicalTypes) TArgPrinter.printTemplateArguments(TArgAsWritten->arguments(), TPL, /*TemplOverloaded*/ true); - else if (const TemplateArgumentList *TArgs = + else if (TemplateArgumentList const *TArgs = D->getTemplateSpecializationArgs()) TArgPrinter.printTemplateArguments(TArgs->asArray(), TPL, /*TemplOverloaded*/ true); } QualType Ty = D->getType(); - while (const ParenType *PT = dyn_cast(Ty)) { + while (ParenType const *PT = dyn_cast(Ty)) { Proto = '(' + Proto + ')'; Ty = PT->getInnerType(); } - if (const FunctionType *AFT = Ty->getAs()) { - const FunctionProtoType *FT = nullptr; + if (FunctionType const *AFT = Ty->getAs()) { + FunctionProtoType const *FT = nullptr; if (D->hasWrittenPrototype()) FT = dyn_cast(AFT); @@ -677,12 +688,14 @@ llvm::raw_string_ostream POut(Proto); DeclPrinter ParamPrinter(POut, SubPolicy, Context, Indentation); for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) { - if (i) POut << ", "; + if (i) + POut << ", "; ParamPrinter.VisitParmVarDecl(D->getParamDecl(i)); } if (FT->isVariadic()) { - if (D->getNumParams()) POut << ", "; + if (D->getNumParams()) + POut << ", "; POut << "..."; } } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) { @@ -806,19 +819,15 @@ printTemplateParameters(D->getFriendTypeTemplateParameterList(i)); Out << "friend "; Out << " " << TSI->getType().getAsString(Policy); - } - else if (FunctionDecl *FD = - dyn_cast(D->getFriendDecl())) { + } else if (FunctionDecl *FD = dyn_cast(D->getFriendDecl())) { Out << "friend "; VisitFunctionDecl(FD); - } - else if (FunctionTemplateDecl *FTD = - dyn_cast(D->getFriendDecl())) { + } else if (FunctionTemplateDecl *FTD = + dyn_cast(D->getFriendDecl())) { Out << "friend "; VisitFunctionTemplateDecl(FTD); - } - else if (ClassTemplateDecl *CTD = - dyn_cast(D->getFriendDecl())) { + } else if (ClassTemplateDecl *CTD = + dyn_cast(D->getFriendDecl())) { Out << "friend "; VisitRedeclarableTemplateDecl(CTD); } @@ -831,8 +840,9 @@ if (!Policy.SuppressSpecifiers && D->isModulePrivate()) Out << "__module_private__ "; - Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()). - stream(Policy, D->getName(), Indentation); + Out << D->getASTContext() + .getUnqualifiedObjCPointerType(D->getType()) + .stream(Policy, D->getName(), Indentation); if (D->isBitField()) { Out << " : "; @@ -851,16 +861,15 @@ prettyPrintAttributes(D); } -void DeclPrinter::VisitLabelDecl(LabelDecl *D) { - Out << *D << ":"; -} +void DeclPrinter::VisitLabelDecl(LabelDecl *D) { Out << *D << ":"; } void DeclPrinter::VisitVarDecl(VarDecl *D) { prettyPrintPragmas(D); - QualType T = D->getTypeSourceInfo() - ? D->getTypeSourceInfo()->getType() - : D->getASTContext().getUnqualifiedObjCPointerType(D->getType()); + QualType T = + D->getTypeSourceInfo() + ? D->getTypeSourceInfo()->getType() + : D->getASTContext().getUnqualifiedObjCPointerType(D->getType()); if (!Policy.SuppressSpecifiers) { StorageClass SC = D->getStorageClass(); @@ -899,7 +908,7 @@ if (D->getInitStyle() == VarDecl::CallInit && !Construct->isListInitialization()) { ImplicitInit = Construct->getNumArgs() == 0 || - Construct->getArg(0)->isDefaultArgument(); + Construct->getArg(0)->isDefaultArgument(); } } if (!ImplicitInit) { @@ -919,9 +928,7 @@ prettyPrintAttributes(D); } -void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) { - VisitVarDecl(D); -} +void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) { VisitVarDecl(D); } void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) { Out << "__asm ("; @@ -931,8 +938,7 @@ } void DeclPrinter::VisitImportDecl(ImportDecl *D) { - Out << "@import " << D->getImportedModule()->getFullModuleName() - << ";\n"; + Out << "@import " << D->getImportedModule()->getFullModuleName() << ";\n"; } void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) { @@ -976,9 +982,7 @@ Out << *D->getAliasedNamespace(); } -void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) { - prettyPrintAttributes(D); -} +void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) { prettyPrintAttributes(D); } void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) { // FIXME: add printing of pragma attributes if required. @@ -994,8 +998,8 @@ if (auto S = dyn_cast(D)) { ArrayRef Args = S->getTemplateArgs().asArray(); if (!Policy.PrintCanonicalTypes) - if (const auto* TSI = S->getTypeAsWritten()) - if (const auto *TST = + if (auto const *TSI = S->getTypeAsWritten()) + if (auto const *TST = dyn_cast(TSI->getType())) Args = TST->template_arguments(); printTemplateArguments( @@ -1009,7 +1013,8 @@ if (D->getNumBases()) { Out << " : "; for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(), - BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) { + BaseEnd = D->bases_end(); + Base != BaseEnd; ++Base) { if (Base != D->bases_begin()) Out << ", "; @@ -1041,7 +1046,7 @@ } void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { - const char *l; + char const *l; if (D->getLanguage() == LinkageSpecDecl::lang_c) l = "C"; else { @@ -1059,7 +1064,7 @@ Visit(*D->decls_begin()); } -void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params, +void DeclPrinter::printTemplateParameters(TemplateParameterList const *Params, bool OmitTemplateKW) { assert(Params); @@ -1068,7 +1073,7 @@ Out << '<'; bool NeedComma = false; - for (const Decl *Param : *Params) { + for (Decl const *Param : *Params) { if (Param->isImplicit()) continue; @@ -1077,7 +1082,7 @@ else NeedComma = true; - if (const auto *TTP = dyn_cast(Param)) { + if (auto const *TTP = dyn_cast(Param)) { VisitTemplateTypeParmDecl(TTP); } else if (auto NTTP = dyn_cast(Param)) { VisitNonTypeTemplateParmDecl(NTTP); @@ -1093,7 +1098,7 @@ } void DeclPrinter::printTemplateArguments(ArrayRef Args, - const TemplateParameterList *Params, + TemplateParameterList const *Params, bool TemplOverloaded) { Out << "<"; for (size_t I = 0, E = Args.size(); I < E; ++I) { @@ -1110,7 +1115,7 @@ } void DeclPrinter::printTemplateArguments(ArrayRef Args, - const TemplateParameterList *Params, + TemplateParameterList const *Params, bool TemplOverloaded) { Out << "<"; for (size_t I = 0, E = Args.size(); I < E; ++I) { @@ -1126,11 +1131,11 @@ Out << ">"; } -void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) { +void DeclPrinter::VisitTemplateDecl(TemplateDecl const *D) { printTemplateParameters(D->getTemplateParameters()); - if (const TemplateTemplateParmDecl *TTP = - dyn_cast(D)) { + if (TemplateTemplateParmDecl const *TTP = + dyn_cast(D)) { Out << "class"; if (TTP->isParameterPack()) @@ -1142,8 +1147,8 @@ Out << TTP->getDeclName(); } else if (auto *TD = D->getTemplatedDecl()) Visit(TD); - else if (const auto *Concept = dyn_cast(D)) { - Out << "concept " << Concept->getName() << " = " ; + else if (auto const *Concept = dyn_cast(D)) { + Out << "concept " << Concept->getName() << " = "; Concept->getConstraintExpr()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context); } @@ -1152,7 +1157,7 @@ void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { prettyPrintPragmas(D->getTemplatedDecl()); // Print any leading template parameter lists. - if (const FunctionDecl *FD = D->getTemplatedDecl()) { + if (FunctionDecl const *FD = D->getTemplatedDecl()) { for (unsigned I = 0, NumTemplateParams = FD->getNumTemplateParameterLists(); I < NumTemplateParams; ++I) printTemplateParameters(FD->getTemplateParameterList(I)); @@ -1168,7 +1173,7 @@ if (PrintInstantiation && !isa(D->getTemplatedDecl())) { FunctionDecl *PrevDecl = D->getTemplatedDecl(); - const FunctionDecl *Def; + FunctionDecl const *Def; if (PrevDecl->isDefined(Def) && Def != PrevDecl) return; for (auto *I : D->specializations()) @@ -1197,13 +1202,13 @@ } void DeclPrinter::VisitClassTemplateSpecializationDecl( - ClassTemplateSpecializationDecl *D) { + ClassTemplateSpecializationDecl *D) { Out << "template<> "; VisitCXXRecordDecl(D); } void DeclPrinter::VisitClassTemplatePartialSpecializationDecl( - ClassTemplatePartialSpecializationDecl *D) { + ClassTemplatePartialSpecializationDecl *D) { printTemplateParameters(D->getTemplateParameters()); VisitCXXRecordDecl(D); } @@ -1281,14 +1286,13 @@ std::string name = OMD->getSelector().getAsString(); std::string::size_type pos, lastPos = 0; - for (const auto *PI : OMD->parameters()) { + for (auto const *PI : OMD->parameters()) { // FIXME: selector is missing here! pos = name.find_first_of(':', lastPos); if (lastPos != 0) Out << " "; Out << name.substr(lastPos, pos - lastPos) << ':'; - PrintObjCMethodType(OMD->getASTContext(), - PI->getObjCDeclQualifier(), + PrintObjCMethodType(OMD->getASTContext(), PI->getObjCDeclQualifier(), PI->getType()); Out << *PI; lastPos = pos + 1; @@ -1298,7 +1302,7 @@ Out << name; if (OMD->isVariadic()) - Out << ", ..."; + Out << ", ..."; prettyPrintAttributes(OMD); @@ -1306,8 +1310,7 @@ Out << ' '; OMD->getBody()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context); - } - else if (Policy.PolishForDeclaration) + } else if (Policy.PolishForDeclaration) Out << ';'; } @@ -1325,14 +1328,15 @@ Out << "{\n"; eolnOut = true; Indentation += Policy.Indentation; - for (const auto *I : OID->ivars()) { - Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()). - getAsString(Policy) << ' ' << *I << ";\n"; + for (auto const *I : OID->ivars()) { + Indent() << I->getASTContext() + .getUnqualifiedObjCPointerType(I->getType()) + .getAsString(Policy) + << ' ' << *I << ";\n"; } Indentation -= Policy.Indentation; Out << "}\n"; - } - else if (SID || (OID->decls_begin() != OID->decls_end())) { + } else if (SID || (OID->decls_begin() != OID->decls_end())) { Out << "\n"; eolnOut = true; } @@ -1367,10 +1371,11 @@ Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy); // Protocols? - const ObjCList &Protocols = OID->getReferencedProtocols(); + ObjCList const &Protocols = OID->getReferencedProtocols(); if (!Protocols.empty()) { for (ObjCList::iterator I = Protocols.begin(), - E = Protocols.end(); I != E; ++I) + E = Protocols.end(); + I != E; ++I) Out << (I == Protocols.begin() ? '<' : ',') << **I; Out << "> "; } @@ -1379,15 +1384,15 @@ Out << "{\n"; eolnOut = true; Indentation += Policy.Indentation; - for (const auto *I : OID->ivars()) { + for (auto const *I : OID->ivars()) { Indent() << I->getASTContext() .getUnqualifiedObjCPointerType(I->getType()) - .getAsString(Policy) << ' ' << *I << ";\n"; + .getAsString(Policy) + << ' ' << *I << ";\n"; } Indentation -= Policy.Indentation; Out << "}\n"; - } - else if (SID || (OID->decls_begin() != OID->decls_end())) { + } else if (SID || (OID->decls_begin() != OID->decls_end())) { Out << "\n"; eolnOut = true; } @@ -1405,11 +1410,12 @@ return; } // Protocols? - const ObjCList &Protocols = PID->getReferencedProtocols(); + ObjCList const &Protocols = PID->getReferencedProtocols(); if (!Protocols.empty()) { Out << "@protocol " << *PID; for (ObjCList::iterator I = Protocols.begin(), - E = Protocols.end(); I != E; ++I) + E = Protocols.end(); + I != E; ++I) Out << (I == Protocols.begin() ? '<' : ',') << **I; Out << ">\n"; } else @@ -1420,7 +1426,7 @@ void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) { Out << "@implementation "; - if (const auto *CID = PID->getClassInterface()) + if (auto const *CID = PID->getClassInterface()) Out << *CID; else Out << "<>"; @@ -1433,7 +1439,7 @@ void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) { Out << "@interface "; - if (const auto *CID = PID->getClassInterface()) + if (auto const *CID = PID->getClassInterface()) Out << *CID; else Out << "<>"; @@ -1444,9 +1450,11 @@ if (PID->ivar_size() > 0) { Out << "{\n"; Indentation += Policy.Indentation; - for (const auto *I : PID->ivars()) - Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()). - getAsString(Policy) << ' ' << *I << ";\n"; + for (auto const *I : PID->ivars()) + Indent() << I->getASTContext() + .getUnqualifiedObjCPointerType(I->getType()) + .getAsString(Policy) + << ' ' << *I << ";\n"; Indentation -= Policy.Indentation; Out << "}\n"; } @@ -1458,8 +1466,8 @@ } void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) { - Out << "@compatibility_alias " << *AID - << ' ' << *AID->getClassInterface() << ";\n"; + Out << "@compatibility_alias " << *AID << ' ' << *AID->getClassInterface() + << ";\n"; } /// PrintObjCPropertyDecl - print a property declaration. @@ -1566,11 +1574,12 @@ } } - (void) first; // Silence dead store warning due to idiomatic code. + (void)first; // Silence dead store warning due to idiomatic code. Out << ")"; } - std::string TypeStr = PDecl->getASTContext().getUnqualifiedObjCPointerType(T). - getAsString(Policy); + std::string TypeStr = + PDecl->getASTContext().getUnqualifiedObjCPointerType(T).getAsString( + Policy); Out << ' ' << TypeStr; if (!StringRef(TypeStr).endswith("*")) Out << ' '; @@ -1598,8 +1607,8 @@ // Use the correct record name when the using declaration is used for // inheriting constructors. - for (const auto *Shadow : D->shadows()) { - if (const auto *ConstructorShadow = + for (auto const *Shadow : D->shadows()) { + if (auto const *ConstructorShadow = dyn_cast(Shadow)) { assert(Shadow->getDeclContext() == ConstructorShadow->getDeclContext()); Out << *ConstructorShadow->getNominatedBaseClass(); @@ -1613,8 +1622,8 @@ Out << "using enum " << D->getEnumDecl(); } -void -DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { +void DeclPrinter::VisitUnresolvedUsingTypenameDecl( + UnresolvedUsingTypenameDecl *D) { Out << "using typename "; D->getQualifier()->print(Out, Policy); Out << D->getDeclName(); @@ -1636,7 +1645,7 @@ if (!D->varlist_empty()) { for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(), E = D->varlist_end(); - I != E; ++I) { + I != E; ++I) { Out << (I == D->varlist_begin() ? '(' : ','); NamedDecl *ND = cast(*I)->getDecl(); ND->printQualifiedName(Out); @@ -1678,7 +1687,7 @@ if (!D->isInvalidDecl()) { Out << "#pragma omp declare reduction ("; if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) { - const char *OpName = + char const *OpName = getOperatorSpelling(D->getDeclName().getCXXOverloadedOperator()); assert(OpName && "not an overloaded operator"); Out << OpName; @@ -1734,8 +1743,8 @@ D->getInit()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context); } -void DeclPrinter::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP) { - if (const TypeConstraint *TC = TTP->getTypeConstraint()) +void DeclPrinter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl const *TTP) { + if (TypeConstraint const *TC = TTP->getTypeConstraint()) TC->print(Out, Policy); else if (TTP->wasDeclaredWithTypename()) Out << "typename"; @@ -1757,7 +1766,7 @@ } void DeclPrinter::VisitNonTypeTemplateParmDecl( - const NonTypeTemplateParmDecl *NTTP) { + NonTypeTemplateParmDecl const *NTTP) { StringRef Name; if (IdentifierInfo *II = NTTP->getIdentifier()) Name = II->getName(); Index: clang/lib/AST/DeclTemplate.cpp =================================================================== --- clang/lib/AST/DeclTemplate.cpp +++ clang/lib/AST/DeclTemplate.cpp @@ -43,8 +43,7 @@ // TemplateParameterList Implementation //===----------------------------------------------------------------------===// - -TemplateParameterList::TemplateParameterList(const ASTContext& C, +TemplateParameterList::TemplateParameterList(ASTContext const &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef Params, @@ -59,19 +58,19 @@ begin()[Idx] = P; bool IsPack = P->isTemplateParameterPack(); - if (const auto *NTTP = dyn_cast(P)) { + if (auto const *NTTP = dyn_cast(P)) { if (!IsPack && NTTP->getType()->containsUnexpandedParameterPack()) ContainsUnexpandedParameterPack = true; if (NTTP->hasPlaceholderTypeConstraint()) HasConstrainedParameters = true; - } else if (const auto *TTP = dyn_cast(P)) { + } else if (auto const *TTP = dyn_cast(P)) { if (!IsPack && TTP->getTemplateParameters()->containsUnexpandedParameterPack()) ContainsUnexpandedParameterPack = true; - } else if (const auto *TTP = dyn_cast(P)) { - if (const TypeConstraint *TC = TTP->getTypeConstraint()) { + } else if (auto const *TTP = dyn_cast(P)) { + if (TypeConstraint const *TC = TTP->getTypeConstraint()) { if (TC->getImmediatelyDeclaredConstraint() - ->containsUnexpandedParameterPack()) + ->containsUnexpandedParameterPack()) ContainsUnexpandedParameterPack = true; } if (TTP->hasTypeConstraint()) @@ -99,12 +98,12 @@ // An implicit constrained parameter might have had a use of an unexpanded // pack added to it after the template parameter list was created. All // implicit parameters are at the end of the parameter list. - for (const NamedDecl *Param : llvm::reverse(asArray())) { + for (NamedDecl const *Param : llvm::reverse(asArray())) { if (!Param->isImplicit()) break; - if (const auto *TTP = dyn_cast(Param)) { - const auto *TC = TTP->getTypeConstraint(); + if (auto const *TTP = dyn_cast(Param)) { + auto const *TC = TTP->getTypeConstraint(); if (TC && TC->getImmediatelyDeclaredConstraint() ->containsUnexpandedParameterPack()) return true; @@ -115,7 +114,7 @@ } TemplateParameterList * -TemplateParameterList::Create(const ASTContext &C, SourceLocation TemplateLoc, +TemplateParameterList::Create(ASTContext const &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef Params, SourceLocation RAngleLoc, Expr *RequiresClause) { @@ -128,7 +127,7 @@ unsigned TemplateParameterList::getMinRequiredArguments() const { unsigned NumRequiredArgs = 0; - for (const NamedDecl *P : asArray()) { + for (NamedDecl const *P : asArray()) { if (P->isTemplateParameterPack()) { if (Optional Expansions = getExpandedPackSize(P)) { NumRequiredArgs += *Expansions; @@ -137,10 +136,10 @@ break; } - if (const auto *TTP = dyn_cast(P)) { + if (auto const *TTP = dyn_cast(P)) { if (TTP->hasDefaultArgument()) break; - } else if (const auto *NTTP = dyn_cast(P)) { + } else if (auto const *NTTP = dyn_cast(P)) { if (NTTP->hasDefaultArgument()) break; } else if (cast(P)->hasDefaultArgument()) @@ -156,10 +155,10 @@ if (size() == 0) return 0; - const NamedDecl *FirstParm = getParam(0); - if (const auto *TTP = dyn_cast(FirstParm)) + NamedDecl const *FirstParm = getParam(0); + if (auto const *TTP = dyn_cast(FirstParm)) return TTP->getDepth(); - else if (const auto *NTTP = dyn_cast(FirstParm)) + else if (auto const *NTTP = dyn_cast(FirstParm)) return NTTP->getDepth(); else return cast(FirstParm)->getDepth(); @@ -170,20 +169,20 @@ for (NamedDecl *P : *Params) { P->setDeclContext(Owner); - if (const auto *TTP = dyn_cast(P)) + if (auto const *TTP = dyn_cast(P)) AdoptTemplateParameterList(TTP->getTemplateParameters(), Owner); } } -void TemplateParameterList:: -getAssociatedConstraints(llvm::SmallVectorImpl &AC) const { +void TemplateParameterList::getAssociatedConstraints( + llvm::SmallVectorImpl &AC) const { if (HasConstrainedParameters) - for (const NamedDecl *Param : *this) { - if (const auto *TTP = dyn_cast(Param)) { - if (const auto *TC = TTP->getTypeConstraint()) + for (NamedDecl const *Param : *this) { + if (auto const *TTP = dyn_cast(Param)) { + if (auto const *TC = TTP->getTypeConstraint()) AC.push_back(TC->getImmediatelyDeclaredConstraint()); - } else if (const auto *NTTP = dyn_cast(Param)) { - if (const Expr *E = NTTP->getPlaceholderTypeConstraint()) + } else if (auto const *NTTP = dyn_cast(Param)) { + if (Expr const *E = NTTP->getPlaceholderTypeConstraint()) AC.push_back(E); } } @@ -196,11 +195,11 @@ } bool TemplateParameterList::shouldIncludeTypeForArgument( - const TemplateParameterList *TPL, unsigned Idx) { + TemplateParameterList const *TPL, unsigned Idx) { if (!TPL || Idx >= TPL->size()) return true; - const NamedDecl *TemplParam = TPL->getParam(Idx); - if (const auto *ParamValueDecl = + NamedDecl const *TemplParam = TPL->getParam(Idx); + if (auto const *ParamValueDecl = dyn_cast(TemplParam)) if (ParamValueDecl->getType()->getContainedDeducedType()) return true; @@ -209,8 +208,8 @@ namespace clang { -void *allocateDefaultArgStorageChain(const ASTContext &C) { - return new (C) char[sizeof(void*) * 2]; +void *allocateDefaultArgStorageChain(ASTContext const &C) { + return new (C) char[sizeof(void *) * 2]; } } // namespace clang @@ -226,11 +225,11 @@ void TemplateDecl::anchor() {} -void TemplateDecl:: -getAssociatedConstraints(llvm::SmallVectorImpl &AC) const { +void TemplateDecl::getAssociatedConstraints( + llvm::SmallVectorImpl &AC) const { TemplateParams->getAssociatedConstraints(AC); if (auto *FD = dyn_cast_or_null(getTemplatedDecl())) - if (const Expr *TRC = FD->getTrailingRequiresClause()) + if (Expr const *TRC = FD->getTrailingRequiresClause()) AC.push_back(TRC); } @@ -248,14 +247,15 @@ void RedeclarableTemplateDecl::anchor() {} -RedeclarableTemplateDecl::CommonBase *RedeclarableTemplateDecl::getCommonPtr() const { +RedeclarableTemplateDecl::CommonBase * +RedeclarableTemplateDecl::getCommonPtr() const { if (Common) return Common; // Walk the previous-declaration chain until we either find a declaration // with a common pointer or we run out of previous declarations. - SmallVector PrevDecls; - for (const RedeclarableTemplateDecl *Prev = getPreviousDecl(); Prev; + SmallVector PrevDecls; + for (RedeclarableTemplateDecl const *Prev = getPreviousDecl(); Prev; Prev = Prev->getPreviousDecl()) { if (Prev->Common) { Common = Prev->Common; @@ -274,7 +274,7 @@ } // Update any previous declarations we saw with the common pointer. - for (const RedeclarableTemplateDecl *Prev : PrevDecls) + for (RedeclarableTemplateDecl const *Prev : PrevDecls) Prev->Common = Common; return Common; @@ -293,11 +293,11 @@ } } -template +template typename RedeclarableTemplateDecl::SpecEntryTraits::DeclType * RedeclarableTemplateDecl::findSpecializationImpl( llvm::FoldingSetVector &Specs, void *&InsertPos, - ProfileArguments&&... ProfileArgs) { + ProfileArguments &&...ProfileArgs) { using SETraits = SpecEntryTraits; llvm::FoldingSetNodeID ID; @@ -307,7 +307,7 @@ return Entry ? SETraits::getDecl(Entry)->getMostRecentDecl() : nullptr; } -template +template void RedeclarableTemplateDecl::addSpecializationImpl( llvm::FoldingSetVector &Specializations, EntryType *Entry, void *InsertPos) { @@ -316,8 +316,7 @@ if (InsertPos) { #ifndef NDEBUG void *CorrectInsertPos; - assert(!findSpecializationImpl(Specializations, - CorrectInsertPos, + assert(!findSpecializationImpl(Specializations, CorrectInsertPos, SETraits::getTemplateArgs(Entry)) && InsertPos == CorrectInsertPos && "given incorrect InsertPos for specialization"); @@ -339,12 +338,10 @@ // FunctionTemplateDecl Implementation //===----------------------------------------------------------------------===// -FunctionTemplateDecl *FunctionTemplateDecl::Create(ASTContext &C, - DeclContext *DC, - SourceLocation L, - DeclarationName Name, - TemplateParameterList *Params, - NamedDecl *Decl) { +FunctionTemplateDecl * +FunctionTemplateDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, + DeclarationName Name, + TemplateParameterList *Params, NamedDecl *Decl) { AdoptTemplateParameterList(Params, cast(Decl)); return new (C, DC) FunctionTemplateDecl(C, DC, L, Name, Params, Decl); } @@ -379,7 +376,7 @@ } void FunctionTemplateDecl::addSpecialization( - FunctionTemplateSpecializationInfo *Info, void *InsertPos) { + FunctionTemplateSpecializationInfo *Info, void *InsertPos) { addSpecializationImpl(getSpecializations(), Info, InsertPos); } @@ -438,8 +435,7 @@ // ClassTemplateDecl Implementation //===----------------------------------------------------------------------===// -ClassTemplateDecl *ClassTemplateDecl::Create(ASTContext &C, - DeclContext *DC, +ClassTemplateDecl *ClassTemplateDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, @@ -490,61 +486,60 @@ } ClassTemplatePartialSpecializationDecl * -ClassTemplateDecl::findPartialSpecialization( - ArrayRef Args, - TemplateParameterList *TPL, void *&InsertPos) { +ClassTemplateDecl::findPartialSpecialization(ArrayRef Args, + TemplateParameterList *TPL, + void *&InsertPos) { return findSpecializationImpl(getPartialSpecializations(), InsertPos, Args, TPL); } static void ProfileTemplateParameterList(ASTContext &C, - llvm::FoldingSetNodeID &ID, const TemplateParameterList *TPL) { - const Expr *RC = TPL->getRequiresClause(); + llvm::FoldingSetNodeID &ID, + TemplateParameterList const *TPL) { + Expr const *RC = TPL->getRequiresClause(); ID.AddBoolean(RC != nullptr); if (RC) RC->Profile(ID, C, /*Canonical=*/true); ID.AddInteger(TPL->size()); for (NamedDecl *D : *TPL) { - if (const auto *NTTP = dyn_cast(D)) { + if (auto const *NTTP = dyn_cast(D)) { ID.AddInteger(0); ID.AddBoolean(NTTP->isParameterPack()); NTTP->getType().getCanonicalType().Profile(ID); continue; } - if (const auto *TTP = dyn_cast(D)) { + if (auto const *TTP = dyn_cast(D)) { ID.AddInteger(1); ID.AddBoolean(TTP->isParameterPack()); ID.AddBoolean(TTP->hasTypeConstraint()); - if (const TypeConstraint *TC = TTP->getTypeConstraint()) + if (TypeConstraint const *TC = TTP->getTypeConstraint()) TC->getImmediatelyDeclaredConstraint()->Profile(ID, C, /*Canonical=*/true); continue; } - const auto *TTP = cast(D); + auto const *TTP = cast(D); ID.AddInteger(2); ID.AddBoolean(TTP->isParameterPack()); ProfileTemplateParameterList(C, ID, TTP->getTemplateParameters()); } } -void -ClassTemplatePartialSpecializationDecl::Profile(llvm::FoldingSetNodeID &ID, - ArrayRef TemplateArgs, TemplateParameterList *TPL, - ASTContext &Context) { +void ClassTemplatePartialSpecializationDecl::Profile( + llvm::FoldingSetNodeID &ID, ArrayRef TemplateArgs, + TemplateParameterList *TPL, ASTContext &Context) { ID.AddInteger(TemplateArgs.size()); - for (const TemplateArgument &TemplateArg : TemplateArgs) + for (TemplateArgument const &TemplateArg : TemplateArgs) TemplateArg.Profile(ID, Context); ProfileTemplateParameterList(Context, ID, TPL); } void ClassTemplateDecl::AddPartialSpecialization( - ClassTemplatePartialSpecializationDecl *D, - void *InsertPos) { + ClassTemplatePartialSpecializationDecl *D, void *InsertPos) { if (InsertPos) getPartialSpecializations().InsertNode(D, InsertPos); else { - ClassTemplatePartialSpecializationDecl *Existing - = getPartialSpecializations().GetOrInsertNode(D); + ClassTemplatePartialSpecializationDecl *Existing = + getPartialSpecializations().GetOrInsertNode(D); (void)Existing; assert(Existing->isCanonicalDecl() && "Non-canonical specialization?"); } @@ -555,8 +550,8 @@ void ClassTemplateDecl::getPartialSpecializations( SmallVectorImpl &PS) const { - llvm::FoldingSetVector &PartialSpecs - = getPartialSpecializations(); + llvm::FoldingSetVector &PartialSpecs = + getPartialSpecializations(); PS.clear(); PS.reserve(PartialSpecs.size()); for (ClassTemplatePartialSpecializationDecl &P : PartialSpecs) @@ -577,9 +572,10 @@ ClassTemplatePartialSpecializationDecl * ClassTemplateDecl::findPartialSpecInstantiatedFromMember( - ClassTemplatePartialSpecializationDecl *D) { + ClassTemplatePartialSpecializationDecl *D) { Decl *DCanon = D->getCanonicalDecl(); - for (ClassTemplatePartialSpecializationDecl &P : getPartialSpecializations()) { + for (ClassTemplatePartialSpecializationDecl &P : + getPartialSpecializations()) { if (P.getInstantiatedFromMember()->getCanonicalDecl() == DCanon) return P.getMostRecentDecl(); } @@ -587,8 +583,7 @@ return nullptr; } -QualType -ClassTemplateDecl::getInjectedClassNameSpecialization() { +QualType ClassTemplateDecl::getInjectedClassNameSpecialization() { Common *CommonPtr = getCommonPtr(); if (!CommonPtr->InjectedClassNameType.isNull()) return CommonPtr->InjectedClassNameType; @@ -604,9 +599,8 @@ TemplateParameterList *Params = getTemplateParameters(); SmallVector TemplateArgs; Context.getInjectedTemplateArgs(Params, TemplateArgs); - CommonPtr->InjectedClassNameType - = Context.getTemplateSpecializationType(TemplateName(this), - TemplateArgs); + CommonPtr->InjectedClassNameType = + Context.getTemplateSpecializationType(TemplateName(this), TemplateArgs); return CommonPtr->InjectedClassNameType; } @@ -614,37 +608,33 @@ // TemplateTypeParm Allocation/Deallocation Method Implementations //===----------------------------------------------------------------------===// -TemplateTypeParmDecl * -TemplateTypeParmDecl::Create(const ASTContext &C, DeclContext *DC, - SourceLocation KeyLoc, SourceLocation NameLoc, - unsigned D, unsigned P, IdentifierInfo *Id, - bool Typename, bool ParameterPack, - bool HasTypeConstraint, - Optional NumExpanded) { - auto *TTPDecl = - new (C, DC, - additionalSizeToAlloc(HasTypeConstraint ? 1 : 0)) - TemplateTypeParmDecl(DC, KeyLoc, NameLoc, Id, Typename, - HasTypeConstraint, NumExpanded); +TemplateTypeParmDecl *TemplateTypeParmDecl::Create( + ASTContext const &C, DeclContext *DC, SourceLocation KeyLoc, + SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, + bool Typename, bool ParameterPack, bool HasTypeConstraint, + Optional NumExpanded) { + auto *TTPDecl = new ( + C, DC, additionalSizeToAlloc(HasTypeConstraint ? 1 : 0)) + TemplateTypeParmDecl(DC, KeyLoc, NameLoc, Id, Typename, HasTypeConstraint, + NumExpanded); QualType TTPType = C.getTemplateTypeParmType(D, P, ParameterPack, TTPDecl); TTPDecl->setTypeForDecl(TTPType.getTypePtr()); return TTPDecl; } TemplateTypeParmDecl * -TemplateTypeParmDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { - return new (C, ID) TemplateTypeParmDecl(nullptr, SourceLocation(), - SourceLocation(), nullptr, false, - false, None); +TemplateTypeParmDecl::CreateDeserialized(ASTContext const &C, unsigned ID) { + return new (C, ID) TemplateTypeParmDecl( + nullptr, SourceLocation(), SourceLocation(), nullptr, false, false, None); } TemplateTypeParmDecl * -TemplateTypeParmDecl::CreateDeserialized(const ASTContext &C, unsigned ID, +TemplateTypeParmDecl::CreateDeserialized(ASTContext const &C, unsigned ID, bool HasTypeConstraint) { return new (C, ID, additionalSizeToAlloc(HasTypeConstraint ? 1 : 0)) - TemplateTypeParmDecl(nullptr, SourceLocation(), SourceLocation(), - nullptr, false, HasTypeConstraint, None); + TemplateTypeParmDecl(nullptr, SourceLocation(), SourceLocation(), nullptr, + false, HasTypeConstraint, None); } SourceLocation TemplateTypeParmDecl::getDefaultArgumentLoc() const { @@ -677,17 +667,19 @@ return getTypeForDecl()->castAs()->isParameterPack(); } -void TemplateTypeParmDecl::setTypeConstraint(NestedNameSpecifierLoc NNS, - DeclarationNameInfo NameInfo, NamedDecl *FoundDecl, ConceptDecl *CD, - const ASTTemplateArgumentListInfo *ArgsAsWritten, +void TemplateTypeParmDecl::setTypeConstraint( + NestedNameSpecifierLoc NNS, DeclarationNameInfo NameInfo, + NamedDecl *FoundDecl, ConceptDecl *CD, + ASTTemplateArgumentListInfo const *ArgsAsWritten, Expr *ImmediatelyDeclaredConstraint) { assert(HasTypeConstraint && "HasTypeConstraint=true must be passed at construction in order to " "call setTypeConstraint"); assert(!TypeConstraintInitialized && "TypeConstraint was already initialized!"); - new (getTrailingObjects()) TypeConstraint(NNS, NameInfo, - FoundDecl, CD, ArgsAsWritten, ImmediatelyDeclaredConstraint); + new (getTrailingObjects()) + TypeConstraint(NNS, NameInfo, FoundDecl, CD, ArgsAsWritten, + ImmediatelyDeclaredConstraint); TypeConstraintInitialized = true; } @@ -712,32 +704,30 @@ } } -NonTypeTemplateParmDecl * -NonTypeTemplateParmDecl::Create(const ASTContext &C, DeclContext *DC, - SourceLocation StartLoc, SourceLocation IdLoc, - unsigned D, unsigned P, IdentifierInfo *Id, - QualType T, bool ParameterPack, - TypeSourceInfo *TInfo) { +NonTypeTemplateParmDecl *NonTypeTemplateParmDecl::Create( + ASTContext const &C, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, + QualType T, bool ParameterPack, TypeSourceInfo *TInfo) { AutoType *AT = C.getLangOpts().CPlusPlus20 ? T->getContainedAutoType() : nullptr; - return new (C, DC, - additionalSizeToAlloc, - Expr *>(0, - AT && AT->isConstrained() ? 1 : 0)) + return new ( + C, DC, + additionalSizeToAlloc, Expr *>( + 0, AT && AT->isConstrained() ? 1 : 0)) NonTypeTemplateParmDecl(DC, StartLoc, IdLoc, D, P, Id, T, ParameterPack, TInfo); } NonTypeTemplateParmDecl *NonTypeTemplateParmDecl::Create( - const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, + ASTContext const &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, ArrayRef ExpandedTypes, ArrayRef ExpandedTInfos) { AutoType *AT = TInfo->getType()->getContainedAutoType(); - return new (C, DC, - additionalSizeToAlloc, - Expr *>( - ExpandedTypes.size(), AT && AT->isConstrained() ? 1 : 0)) + return new ( + C, DC, + additionalSizeToAlloc, Expr *>( + ExpandedTypes.size(), AT && AT->isConstrained() ? 1 : 0)) NonTypeTemplateParmDecl(DC, StartLoc, IdLoc, D, P, Id, T, TInfo, ExpandedTypes, ExpandedTInfos); } @@ -745,12 +735,12 @@ NonTypeTemplateParmDecl * NonTypeTemplateParmDecl::CreateDeserialized(ASTContext &C, unsigned ID, bool HasTypeConstraint) { - return new (C, ID, additionalSizeToAlloc, - Expr *>(0, - HasTypeConstraint ? 1 : 0)) - NonTypeTemplateParmDecl(nullptr, SourceLocation(), SourceLocation(), - 0, 0, nullptr, QualType(), false, nullptr); + return new ( + C, ID, + additionalSizeToAlloc, Expr *>( + 0, HasTypeConstraint ? 1 : 0)) + NonTypeTemplateParmDecl(nullptr, SourceLocation(), SourceLocation(), 0, 0, + nullptr, QualType(), false, nullptr); } NonTypeTemplateParmDecl * @@ -758,9 +748,9 @@ unsigned NumExpandedTypes, bool HasTypeConstraint) { auto *NTTP = - new (C, ID, additionalSizeToAlloc, - Expr *>( - NumExpandedTypes, HasTypeConstraint ? 1 : 0)) + new (C, ID, + additionalSizeToAlloc, Expr *>( + NumExpandedTypes, HasTypeConstraint ? 1 : 0)) NonTypeTemplateParmDecl(nullptr, SourceLocation(), SourceLocation(), 0, 0, nullptr, QualType(), nullptr, None, None); @@ -777,8 +767,8 @@ SourceLocation NonTypeTemplateParmDecl::getDefaultArgumentLoc() const { return hasDefaultArgument() - ? getDefaultArgument()->getSourceRange().getBegin() - : SourceLocation(); + ? getDefaultArgument()->getSourceRange().getBegin() + : SourceLocation(); } //===----------------------------------------------------------------------===// @@ -800,20 +790,18 @@ } TemplateTemplateParmDecl * -TemplateTemplateParmDecl::Create(const ASTContext &C, DeclContext *DC, +TemplateTemplateParmDecl::Create(ASTContext const &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateParameterList *Params) { - return new (C, DC) TemplateTemplateParmDecl(DC, L, D, P, ParameterPack, Id, - Params); + return new (C, DC) + TemplateTemplateParmDecl(DC, L, D, P, ParameterPack, Id, Params); } -TemplateTemplateParmDecl * -TemplateTemplateParmDecl::Create(const ASTContext &C, DeclContext *DC, - SourceLocation L, unsigned D, unsigned P, - IdentifierInfo *Id, - TemplateParameterList *Params, - ArrayRef Expansions) { +TemplateTemplateParmDecl *TemplateTemplateParmDecl::Create( + ASTContext const &C, DeclContext *DC, SourceLocation L, unsigned D, + unsigned P, IdentifierInfo *Id, TemplateParameterList *Params, + ArrayRef Expansions) { return new (C, DC, additionalSizeToAlloc(Expansions.size())) TemplateTemplateParmDecl(DC, L, D, P, Id, Params, Expansions); @@ -842,7 +830,7 @@ } void TemplateTemplateParmDecl::setDefaultArgument( - const ASTContext &C, const TemplateArgumentLoc &DefArg) { + ASTContext const &C, TemplateArgumentLoc const &DefArg) { if (DefArg.getArgument().isNull()) DefaultArgument.set(nullptr); else @@ -868,13 +856,13 @@ FunctionTemplateSpecializationInfo *FunctionTemplateSpecializationInfo::Create( ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template, - TemplateSpecializationKind TSK, const TemplateArgumentList *TemplateArgs, - const TemplateArgumentListInfo *TemplateArgsAsWritten, SourceLocation POI, + TemplateSpecializationKind TSK, TemplateArgumentList const *TemplateArgs, + TemplateArgumentListInfo const *TemplateArgsAsWritten, SourceLocation POI, MemberSpecializationInfo *MSInfo) { - const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr; + ASTTemplateArgumentListInfo const *ArgsAsWritten = nullptr; if (TemplateArgsAsWritten) - ArgsAsWritten = ASTTemplateArgumentListInfo::Create(C, - *TemplateArgsAsWritten); + ArgsAsWritten = + ASTTemplateArgumentListInfo::Create(C, *TemplateArgsAsWritten); void *Mem = C.Allocate(totalSizeToAlloc(MSInfo ? 1 : 0)); @@ -886,19 +874,16 @@ // ClassTemplateSpecializationDecl Implementation //===----------------------------------------------------------------------===// -ClassTemplateSpecializationDecl:: -ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK, - DeclContext *DC, SourceLocation StartLoc, - SourceLocation IdLoc, - ClassTemplateDecl *SpecializedTemplate, - ArrayRef Args, - ClassTemplateSpecializationDecl *PrevDecl) +ClassTemplateSpecializationDecl::ClassTemplateSpecializationDecl( + ASTContext &Context, Kind DK, TagKind TK, DeclContext *DC, + SourceLocation StartLoc, SourceLocation IdLoc, + ClassTemplateDecl *SpecializedTemplate, ArrayRef Args, + ClassTemplateSpecializationDecl *PrevDecl) : CXXRecordDecl(DK, TK, Context, DC, StartLoc, IdLoc, SpecializedTemplate->getIdentifier(), PrevDecl), - SpecializedTemplate(SpecializedTemplate), - TemplateArgs(TemplateArgumentList::CreateCopy(Context, Args)), - SpecializationKind(TSK_Undeclared) { -} + SpecializedTemplate(SpecializedTemplate), + TemplateArgs(TemplateArgumentList::CreateCopy(Context, Args)), + SpecializationKind(TSK_Undeclared) {} ClassTemplateSpecializationDecl::ClassTemplateSpecializationDecl(ASTContext &C, Kind DK) @@ -906,18 +891,14 @@ SourceLocation(), nullptr, nullptr), SpecializationKind(TSK_Undeclared) {} -ClassTemplateSpecializationDecl * -ClassTemplateSpecializationDecl::Create(ASTContext &Context, TagKind TK, - DeclContext *DC, - SourceLocation StartLoc, - SourceLocation IdLoc, - ClassTemplateDecl *SpecializedTemplate, - ArrayRef Args, - ClassTemplateSpecializationDecl *PrevDecl) { - auto *Result = - new (Context, DC) ClassTemplateSpecializationDecl( - Context, ClassTemplateSpecialization, TK, DC, StartLoc, IdLoc, - SpecializedTemplate, Args, PrevDecl); +ClassTemplateSpecializationDecl *ClassTemplateSpecializationDecl::Create( + ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, + ArrayRef Args, + ClassTemplateSpecializationDecl *PrevDecl) { + auto *Result = new (Context, DC) ClassTemplateSpecializationDecl( + Context, ClassTemplateSpecialization, TK, DC, StartLoc, IdLoc, + SpecializedTemplate, Args, PrevDecl); Result->setMayHaveOutOfDateDef(false); Context.getTypeDeclType(Result, PrevDecl); @@ -927,24 +908,24 @@ ClassTemplateSpecializationDecl * ClassTemplateSpecializationDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - auto *Result = - new (C, ID) ClassTemplateSpecializationDecl(C, ClassTemplateSpecialization); + auto *Result = new (C, ID) + ClassTemplateSpecializationDecl(C, ClassTemplateSpecialization); Result->setMayHaveOutOfDateDef(false); return Result; } void ClassTemplateSpecializationDecl::getNameForDiagnostic( - raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { + raw_ostream &OS, PrintingPolicy const &Policy, bool Qualified) const { NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); - const auto *PS = dyn_cast(this); - if (const ASTTemplateArgumentListInfo *ArgsAsWritten = + auto const *PS = dyn_cast(this); + if (ASTTemplateArgumentListInfo const *ArgsAsWritten = PS ? PS->getTemplateArgsAsWritten() : nullptr) { printTemplateArgumentList( OS, ArgsAsWritten->arguments(), Policy, getSpecializedTemplate()->getTemplateParameters()); } else { - const TemplateArgumentList &TemplateArgs = getTemplateArgs(); + TemplateArgumentList const &TemplateArgs = getTemplateArgs(); printTemplateArgumentList( OS, TemplateArgs.asArray(), Policy, getSpecializedTemplate()->getTemplateParameters()); @@ -953,14 +934,13 @@ ClassTemplateDecl * ClassTemplateSpecializationDecl::getSpecializedTemplate() const { - if (const auto *PartialSpec = - SpecializedTemplate.dyn_cast()) + if (auto const *PartialSpec = + SpecializedTemplate.dyn_cast()) return PartialSpec->PartialSpecialization->getSpecializedTemplate(); - return SpecializedTemplate.get(); + return SpecializedTemplate.get(); } -SourceRange -ClassTemplateSpecializationDecl::getSourceRange() const { +SourceRange ClassTemplateSpecializationDecl::getSourceRange() const { if (ExplicitInfo) { SourceLocation Begin = getTemplateKeywordLoc(); if (Begin.isValid()) { @@ -983,18 +963,17 @@ CTPSDecl *inst_from = ctpsd->getInstantiatedFromMember(); assert(inst_from != nullptr); return inst_from->getSourceRange(); - } - else { + } else { // No explicit info available. llvm::PointerUnion - inst_from = getInstantiatedFrom(); + inst_from = getInstantiatedFrom(); if (inst_from.isNull()) return getSpecializedTemplate()->getSourceRange(); - if (const auto *ctd = inst_from.dyn_cast()) + if (auto const *ctd = inst_from.dyn_cast()) return ctd->getSourceRange(); return inst_from.get() - ->getSourceRange(); + ->getSourceRange(); } } @@ -1009,11 +988,9 @@ return new (C, DC) ConceptDecl(DC, L, Name, Params, ConstraintExpr); } -ConceptDecl *ConceptDecl::CreateDeserialized(ASTContext &C, - unsigned ID) { - ConceptDecl *Result = new (C, ID) ConceptDecl(nullptr, SourceLocation(), - DeclarationName(), - nullptr, nullptr); +ConceptDecl *ConceptDecl::CreateDeserialized(ASTContext &C, unsigned ID) { + ConceptDecl *Result = new (C, ID) ConceptDecl( + nullptr, SourceLocation(), DeclarationName(), nullptr, nullptr); return Result; } @@ -1023,42 +1000,33 @@ //===----------------------------------------------------------------------===// void ClassTemplatePartialSpecializationDecl::anchor() {} -ClassTemplatePartialSpecializationDecl:: -ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK, - DeclContext *DC, - SourceLocation StartLoc, - SourceLocation IdLoc, - TemplateParameterList *Params, - ClassTemplateDecl *SpecializedTemplate, - ArrayRef Args, - const ASTTemplateArgumentListInfo *ArgInfos, - ClassTemplatePartialSpecializationDecl *PrevDecl) - : ClassTemplateSpecializationDecl(Context, - ClassTemplatePartialSpecialization, - TK, DC, StartLoc, IdLoc, - SpecializedTemplate, Args, PrevDecl), +ClassTemplatePartialSpecializationDecl::ClassTemplatePartialSpecializationDecl( + ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, TemplateParameterList *Params, + ClassTemplateDecl *SpecializedTemplate, ArrayRef Args, + ASTTemplateArgumentListInfo const *ArgInfos, + ClassTemplatePartialSpecializationDecl *PrevDecl) + : ClassTemplateSpecializationDecl( + Context, ClassTemplatePartialSpecialization, TK, DC, StartLoc, IdLoc, + SpecializedTemplate, Args, PrevDecl), TemplateParams(Params), ArgsAsWritten(ArgInfos), InstantiatedFromMember(nullptr, false) { AdoptTemplateParameterList(Params, this); } ClassTemplatePartialSpecializationDecl * -ClassTemplatePartialSpecializationDecl:: -Create(ASTContext &Context, TagKind TK,DeclContext *DC, - SourceLocation StartLoc, SourceLocation IdLoc, - TemplateParameterList *Params, - ClassTemplateDecl *SpecializedTemplate, - ArrayRef Args, - const TemplateArgumentListInfo &ArgInfos, - QualType CanonInjectedType, - ClassTemplatePartialSpecializationDecl *PrevDecl) { - const ASTTemplateArgumentListInfo *ASTArgInfos = - ASTTemplateArgumentListInfo::Create(Context, ArgInfos); - - auto *Result = new (Context, DC) - ClassTemplatePartialSpecializationDecl(Context, TK, DC, StartLoc, IdLoc, - Params, SpecializedTemplate, Args, - ASTArgInfos, PrevDecl); +ClassTemplatePartialSpecializationDecl::Create( + ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, + SourceLocation IdLoc, TemplateParameterList *Params, + ClassTemplateDecl *SpecializedTemplate, ArrayRef Args, + TemplateArgumentListInfo const &ArgInfos, QualType CanonInjectedType, + ClassTemplatePartialSpecializationDecl *PrevDecl) { + ASTTemplateArgumentListInfo const *ASTArgInfos = + ASTTemplateArgumentListInfo::Create(Context, ArgInfos); + + auto *Result = new (Context, DC) ClassTemplatePartialSpecializationDecl( + Context, TK, DC, StartLoc, IdLoc, Params, SpecializedTemplate, Args, + ASTArgInfos, PrevDecl); Result->setSpecializationKind(TSK_ExplicitSpecialization); Result->setMayHaveOutOfDateDef(false); @@ -1097,12 +1065,10 @@ // TypeAliasTemplateDecl Implementation //===----------------------------------------------------------------------===// -TypeAliasTemplateDecl *TypeAliasTemplateDecl::Create(ASTContext &C, - DeclContext *DC, - SourceLocation L, - DeclarationName Name, - TemplateParameterList *Params, - NamedDecl *Decl) { +TypeAliasTemplateDecl * +TypeAliasTemplateDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, + DeclarationName Name, + TemplateParameterList *Params, NamedDecl *Decl) { AdoptTemplateParameterList(Params, DC); return new (C, DC) TypeAliasTemplateDecl(C, DC, L, Name, Params, Decl); } @@ -1197,17 +1163,17 @@ VarTemplatePartialSpecializationDecl * VarTemplateDecl::findPartialSpecialization(ArrayRef Args, - TemplateParameterList *TPL, void *&InsertPos) { + TemplateParameterList *TPL, + void *&InsertPos) { return findSpecializationImpl(getPartialSpecializations(), InsertPos, Args, TPL); } -void -VarTemplatePartialSpecializationDecl::Profile(llvm::FoldingSetNodeID &ID, - ArrayRef TemplateArgs, TemplateParameterList *TPL, - ASTContext &Context) { +void VarTemplatePartialSpecializationDecl::Profile( + llvm::FoldingSetNodeID &ID, ArrayRef TemplateArgs, + TemplateParameterList *TPL, ASTContext &Context) { ID.AddInteger(TemplateArgs.size()); - for (const TemplateArgument &TemplateArg : TemplateArgs) + for (TemplateArgument const &TemplateArg : TemplateArgs) TemplateArg.Profile(ID, Context); ProfileTemplateParameterList(Context, ID, TPL); } @@ -1285,17 +1251,17 @@ } void VarTemplateSpecializationDecl::getNameForDiagnostic( - raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { + raw_ostream &OS, PrintingPolicy const &Policy, bool Qualified) const { NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); - const auto *PS = dyn_cast(this); - if (const ASTTemplateArgumentListInfo *ArgsAsWritten = + auto const *PS = dyn_cast(this); + if (ASTTemplateArgumentListInfo const *ArgsAsWritten = PS ? PS->getTemplateArgsAsWritten() : nullptr) { printTemplateArgumentList( OS, ArgsAsWritten->arguments(), Policy, getSpecializedTemplate()->getTemplateParameters()); } else { - const TemplateArgumentList &TemplateArgs = getTemplateArgs(); + TemplateArgumentList const &TemplateArgs = getTemplateArgs(); printTemplateArgumentList( OS, TemplateArgs.asArray(), Policy, getSpecializedTemplate()->getTemplateParameters()); @@ -1303,17 +1269,17 @@ } VarTemplateDecl *VarTemplateSpecializationDecl::getSpecializedTemplate() const { - if (const auto *PartialSpec = + if (auto const *PartialSpec = SpecializedTemplate.dyn_cast()) return PartialSpec->PartialSpecialization->getSpecializedTemplate(); return SpecializedTemplate.get(); } void VarTemplateSpecializationDecl::setTemplateArgsInfo( - const TemplateArgumentListInfo &ArgsInfo) { + TemplateArgumentListInfo const &ArgsInfo) { TemplateArgsInfo.setLAngleLoc(ArgsInfo.getLAngleLoc()); TemplateArgsInfo.setRAngleLoc(ArgsInfo.getRAngleLoc()); - for (const TemplateArgumentLoc &Loc : ArgsInfo.arguments()) + for (TemplateArgumentLoc const &Loc : ArgsInfo.arguments()) TemplateArgsInfo.addArgument(Loc); } @@ -1328,7 +1294,7 @@ SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef Args, - const ASTTemplateArgumentListInfo *ArgInfos) + ASTTemplateArgumentListInfo const *ArgInfos) : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization, Context, DC, StartLoc, IdLoc, SpecializedTemplate, T, TInfo, S, Args), @@ -1344,14 +1310,13 @@ SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef Args, - const TemplateArgumentListInfo &ArgInfos) { - const ASTTemplateArgumentListInfo *ASTArgInfos - = ASTTemplateArgumentListInfo::Create(Context, ArgInfos); - - auto *Result = - new (Context, DC) VarTemplatePartialSpecializationDecl( - Context, DC, StartLoc, IdLoc, Params, SpecializedTemplate, T, TInfo, - S, Args, ASTArgInfos); + TemplateArgumentListInfo const &ArgInfos) { + ASTTemplateArgumentListInfo const *ASTArgInfos = + ASTTemplateArgumentListInfo::Create(Context, ArgInfos); + + auto *Result = new (Context, DC) VarTemplatePartialSpecializationDecl( + Context, DC, StartLoc, IdLoc, Params, SpecializedTemplate, T, TInfo, S, + Args, ASTArgInfos); Result->setSpecializationKind(TSK_ExplicitSpecialization); return Result; } @@ -1363,7 +1328,7 @@ } static TemplateParameterList * -createMakeIntegerSeqParameterList(const ASTContext &C, DeclContext *DC) { +createMakeIntegerSeqParameterList(ASTContext const &C, DeclContext *DC) { // typename T auto *T = TemplateTypeParmDecl::Create( C, DC, SourceLocation(), SourceLocation(), /*Depth=*/1, /*Position=*/0, @@ -1412,7 +1377,7 @@ } static TemplateParameterList * -createTypePackElementParameterList(const ASTContext &C, DeclContext *DC) { +createTypePackElementParameterList(ASTContext const &C, DeclContext *DC) { // std::size_t Index TypeSourceInfo *TInfo = C.getTrivialTypeSourceInfo(C.getSizeType()); auto *Index = NonTypeTemplateParmDecl::Create( @@ -1433,8 +1398,9 @@ SourceLocation(), nullptr); } -static TemplateParameterList *createBuiltinTemplateParameterList( - const ASTContext &C, DeclContext *DC, BuiltinTemplateKind BTK) { +static TemplateParameterList * +createBuiltinTemplateParameterList(ASTContext const &C, DeclContext *DC, + BuiltinTemplateKind BTK) { switch (BTK) { case BTK__make_integer_seq: return createMakeIntegerSeqParameterList(C, DC); @@ -1447,7 +1413,7 @@ void BuiltinTemplateDecl::anchor() {} -BuiltinTemplateDecl::BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC, +BuiltinTemplateDecl::BuiltinTemplateDecl(ASTContext const &C, DeclContext *DC, DeclarationName Name, BuiltinTemplateKind BTK) : TemplateDecl(BuiltinTemplate, DC, SourceLocation(), Name, @@ -1467,9 +1433,9 @@ } } -TemplateParamObjectDecl *TemplateParamObjectDecl::Create(const ASTContext &C, +TemplateParamObjectDecl *TemplateParamObjectDecl::Create(ASTContext const &C, QualType T, - const APValue &V) { + APValue const &V) { DeclContext *DC = C.getTranslationUnitDecl(); auto *TPOD = new (C, DC) TemplateParamObjectDecl(DC, T, V); C.addDestruction(&TPOD->Value); @@ -1478,7 +1444,8 @@ TemplateParamObjectDecl * TemplateParamObjectDecl::CreateDeserialized(ASTContext &C, unsigned ID) { - auto *TPOD = new (C, ID) TemplateParamObjectDecl(nullptr, QualType(), APValue()); + auto *TPOD = + new (C, ID) TemplateParamObjectDecl(nullptr, QualType(), APValue()); C.addDestruction(&TPOD->Value); return TPOD; } @@ -1490,12 +1457,12 @@ } void TemplateParamObjectDecl::printAsExpr(llvm::raw_ostream &OS) const { - const ASTContext &Ctx = getASTContext(); + ASTContext const &Ctx = getASTContext(); getType().getUnqualifiedType().print(OS, Ctx.getPrintingPolicy()); printAsInit(OS); } void TemplateParamObjectDecl::printAsInit(llvm::raw_ostream &OS) const { - const ASTContext &Ctx = getASTContext(); + ASTContext const &Ctx = getASTContext(); getValue().printPretty(OS, Ctx, getType()); } Index: clang/lib/AST/DeclarationName.cpp =================================================================== --- clang/lib/AST/DeclarationName.cpp +++ clang/lib/AST/DeclarationName.cpp @@ -122,7 +122,7 @@ // We know we're printing C++ here. Ensure we print types properly. Policy.adjustForCPlusPlus(); - if (const RecordType *ClassRec = ClassType->getAs()) { + if (RecordType const *ClassRec = ClassType->getAs()) { OS << *ClassRec->getDecl(); return; } @@ -136,10 +136,10 @@ } void DeclarationName::print(raw_ostream &OS, - const PrintingPolicy &Policy) const { + PrintingPolicy const &Policy) const { switch (getNameKind()) { case DeclarationName::Identifier: - if (const IdentifierInfo *II = getAsIdentifierInfo()) { + if (IdentifierInfo const *II = getAsIdentifierInfo()) { StringRef Name = II->getName(); // If this is a mangled OpenMP variant name we strip off the mangling for // printing. It should not be visible to the user at all. @@ -174,7 +174,7 @@ return; case DeclarationName::CXXOperatorName: { - const char *OpName = getOperatorSpelling(getCXXOverloadedOperator()); + char const *OpName = getOperatorSpelling(getCXXOverloadedOperator()); assert(OpName && "not an overloaded operator"); OS << "operator"; @@ -191,7 +191,7 @@ case DeclarationName::CXXConversionFunctionName: { OS << "operator "; QualType Type = getCXXNameType(); - if (const RecordType *Rec = Type->getAs()) { + if (RecordType const *Rec = Type->getAs()) { OS << *Rec->getDecl(); return; } @@ -285,7 +285,7 @@ llvm::errs() << *this << '\n'; } -DeclarationNameTable::DeclarationNameTable(const ASTContext &C) : Ctx(C) { +DeclarationNameTable::DeclarationNameTable(ASTContext const &C) : Ctx(C) { // Initialize the overloaded operator names. for (unsigned Op = 0; Op < NUM_OVERLOADED_OPERATORS; ++Op) CXXOperatorNames[Op].Kind = static_cast(Op); @@ -469,7 +469,8 @@ return OS; } -void DeclarationNameInfo::printName(raw_ostream &OS, PrintingPolicy Policy) const { +void DeclarationNameInfo::printName(raw_ostream &OS, + PrintingPolicy Policy) const { switch (Name.getNameKind()) { case DeclarationName::Identifier: case DeclarationName::ObjCZeroArgSelector: Index: clang/lib/AST/Expr.cpp =================================================================== --- clang/lib/AST/Expr.cpp +++ clang/lib/AST/Expr.cpp @@ -38,8 +38,8 @@ #include using namespace clang; -const Expr *Expr::getBestDynamicClassTypeExpr() const { - const Expr *E = this; +Expr const *Expr::getBestDynamicClassTypeExpr() const { + Expr const *E = this; while (true) { E = E->IgnoreParenBaseCasts(); @@ -63,28 +63,28 @@ return E; } -const CXXRecordDecl *Expr::getBestDynamicClassType() const { - const Expr *E = getBestDynamicClassTypeExpr(); +CXXRecordDecl const *Expr::getBestDynamicClassType() const { + Expr const *E = getBestDynamicClassTypeExpr(); QualType DerivedType = E->getType(); - if (const PointerType *PTy = DerivedType->getAs()) + if (PointerType const *PTy = DerivedType->getAs()) DerivedType = PTy->getPointeeType(); if (DerivedType->isDependentType()) return nullptr; - const RecordType *Ty = DerivedType->castAs(); + RecordType const *Ty = DerivedType->castAs(); Decl *D = Ty->getDecl(); return cast(D); } -const Expr *Expr::skipRValueSubobjectAdjustments( - SmallVectorImpl &CommaLHSs, +Expr const *Expr::skipRValueSubobjectAdjustments( + SmallVectorImpl &CommaLHSs, SmallVectorImpl &Adjustments) const { - const Expr *E = this; + Expr const *E = this; while (true) { E = E->IgnoreParens(); - if (const CastExpr *CE = dyn_cast(E)) { + if (CastExpr const *CE = dyn_cast(E)) { if ((CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_UncheckedDerivedToBase) && E->getType()->isRecordType()) { @@ -99,7 +99,7 @@ E = CE->getSubExpr(); continue; } - } else if (const MemberExpr *ME = dyn_cast(E)) { + } else if (MemberExpr const *ME = dyn_cast(E)) { if (!ME->isArrow()) { assert(ME->getBase()->getType()->isRecordType()); if (FieldDecl *Field = dyn_cast(ME->getMemberDecl())) { @@ -110,12 +110,12 @@ } } } - } else if (const BinaryOperator *BO = dyn_cast(E)) { + } else if (BinaryOperator const *BO = dyn_cast(E)) { if (BO->getOpcode() == BO_PtrMemD) { assert(BO->getRHS()->isPRValue()); E = BO->getLHS(); - const MemberPointerType *MPT = - BO->getRHS()->getType()->getAs(); + MemberPointerType const *MPT = + BO->getRHS()->getType()->getAs(); Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS())); continue; } @@ -133,14 +133,16 @@ } bool Expr::isKnownToHaveBooleanValue(bool Semantic) const { - const Expr *E = IgnoreParens(); + Expr const *E = IgnoreParens(); // If this value has _Bool type, it is obvious 0/1. - if (E->getType()->isBooleanType()) return true; + if (E->getType()->isBooleanType()) + return true; // If this is a non-scalar-integer type, we don't care enough to try. - if (!E->getType()->isIntegralOrEnumerationType()) return false; + if (!E->getType()->isIntegralOrEnumerationType()) + return false; - if (const UnaryOperator *UO = dyn_cast(E)) { + if (UnaryOperator const *UO = dyn_cast(E)) { switch (UO->getOpcode()) { case UO_Plus: return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic); @@ -154,25 +156,26 @@ // Only look through implicit casts. If the user writes // '(int) (a && b)' treat it as an arbitrary int. // FIXME: Should we look through any cast expression in !Semantic mode? - if (const ImplicitCastExpr *CE = dyn_cast(E)) + if (ImplicitCastExpr const *CE = dyn_cast(E)) return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic); - if (const BinaryOperator *BO = dyn_cast(E)) { + if (BinaryOperator const *BO = dyn_cast(E)) { switch (BO->getOpcode()) { - default: return false; - case BO_LT: // Relational operators. + default: + return false; + case BO_LT: // Relational operators. case BO_GT: case BO_LE: case BO_GE: - case BO_EQ: // Equality operators. + case BO_EQ: // Equality operators. case BO_NE: case BO_LAnd: // AND operator. case BO_LOr: // Logical OR operator. return true; - case BO_And: // Bitwise AND operator. - case BO_Xor: // Bitwise XOR operator. - case BO_Or: // Bitwise OR operator. + case BO_And: // Bitwise AND operator. + case BO_Xor: // Bitwise XOR operator. + case BO_Or: // Bitwise OR operator. // Handle things like (x==2)|(y==12). return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) && BO->getRHS()->isKnownToHaveBooleanValue(Semantic); @@ -183,17 +186,17 @@ } } - if (const ConditionalOperator *CO = dyn_cast(E)) + if (ConditionalOperator const *CO = dyn_cast(E)) return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) && CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic); if (isa(E)) return true; - if (const auto *OVE = dyn_cast(E)) + if (auto const *OVE = dyn_cast(E)) return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic); - if (const FieldDecl *FD = E->getSourceBitField()) + if (FieldDecl const *FD = E->getSourceBitField()) if (!Semantic && FD->getType()->isUnsignedIntegerType() && !FD->getBitWidth()->isValueDependent() && FD->getBitWidthValue(FD->getASTContext()) == 1) @@ -207,33 +210,36 @@ // // See also Stmt.cpp:{getBeginLoc(),getEndLoc()}. namespace { - /// This implementation is used when a class provides a custom - /// implementation of getExprLoc. - template - SourceLocation getExprLocImpl(const Expr *expr, - SourceLocation (T::*v)() const) { - return static_cast(expr)->getExprLoc(); - } +/// This implementation is used when a class provides a custom +/// implementation of getExprLoc. +template +SourceLocation getExprLocImpl(Expr const *expr, + SourceLocation (T::*v)() const) { + return static_cast(expr)->getExprLoc(); +} - /// This implementation is used when a class doesn't provide - /// a custom implementation of getExprLoc. Overload resolution - /// should pick it over the implementation above because it's - /// more specialized according to function template partial ordering. - template - SourceLocation getExprLocImpl(const Expr *expr, - SourceLocation (Expr::*v)() const) { - return static_cast(expr)->getBeginLoc(); - } +/// This implementation is used when a class doesn't provide +/// a custom implementation of getExprLoc. Overload resolution +/// should pick it over the implementation above because it's +/// more specialized according to function template partial ordering. +template +SourceLocation getExprLocImpl(Expr const *expr, + SourceLocation (Expr::*v)() const) { + return static_cast(expr)->getBeginLoc(); } +} // namespace SourceLocation Expr::getExprLoc() const { switch (getStmtClass()) { - case Stmt::NoStmtClass: llvm_unreachable("statement without class"); + case Stmt::NoStmtClass: + llvm_unreachable("statement without class"); #define ABSTRACT_STMT(type) -#define STMT(type, base) \ - case Stmt::type##Class: break; -#define EXPR(type, base) \ - case Stmt::type##Class: return getExprLocImpl(this, &type::getExprLoc); +#define STMT(type, base) \ + case Stmt::type##Class: \ + break; +#define EXPR(type, base) \ + case Stmt::type##Class: \ + return getExprLocImpl(this, &type::getExprLoc); #include "clang/AST/StmtNodes.inc" } llvm_unreachable("unknown expression kind"); @@ -251,7 +257,7 @@ } ConstantExpr::ResultStorageKind -ConstantExpr::getStorageKind(const APValue &Value) { +ConstantExpr::getStorageKind(APValue const &Value) { switch (Value.getKind()) { case APValue::None: case APValue::Indeterminate: @@ -266,7 +272,7 @@ } ConstantExpr::ResultStorageKind -ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) { +ConstantExpr::getStorageKind(Type const *T, ASTContext const &Context) { if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64) return ConstantExpr::RSK_Int64; return ConstantExpr::RSK_APValue; @@ -286,7 +292,7 @@ ::new (getTrailingObjects()) APValue(); } -ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E, +ConstantExpr *ConstantExpr::Create(ASTContext const &Context, Expr *E, ResultStorageKind StorageKind, bool IsImmediateInvocation) { assert(!isa(E)); @@ -299,8 +305,8 @@ return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation); } -ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E, - const APValue &Result) { +ConstantExpr *ConstantExpr::Create(ASTContext const &Context, Expr *E, + APValue const &Result) { ResultStorageKind StorageKind = getStorageKind(Result); ConstantExpr *Self = Create(Context, E, StorageKind); Self->SetResult(Result, Context); @@ -315,7 +321,7 @@ ::new (getTrailingObjects()) APValue(); } -ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context, +ConstantExpr *ConstantExpr::CreateEmpty(ASTContext const &Context, ResultStorageKind StorageKind) { AssertResultStorageKind(StorageKind); @@ -326,7 +332,7 @@ return new (Mem) ConstantExpr(EmptyShell(), StorageKind); } -void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) { +void ConstantExpr::MoveIntoResult(APValue &Value, ASTContext const &Context) { assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind && "Invalid storage for this value kind"); ConstantExprBits.APValueKind = Value.getKind(); @@ -378,10 +384,10 @@ llvm_unreachable("invalid ResultKind"); } -DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D, +DeclRefExpr::DeclRefExpr(ASTContext const &Ctx, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T, ExprValueKind VK, SourceLocation L, - const DeclarationNameLoc &LocInfo, + DeclarationNameLoc const &LocInfo, NonOdrUseReason NOUR) : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) { DeclRefExprBits.HasQualifier = false; @@ -395,12 +401,12 @@ setDependence(computeDependence(this, Ctx)); } -DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, +DeclRefExpr::DeclRefExpr(ASTContext const &Ctx, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, - const DeclarationNameInfo &NameInfo, NamedDecl *FoundD, - const TemplateArgumentListInfo *TemplateArgs, + DeclarationNameInfo const &NameInfo, NamedDecl *FoundD, + TemplateArgumentListInfo const *TemplateArgs, QualType T, ExprValueKind VK, NonOdrUseReason NOUR) : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(NameInfo.getInfo()) { @@ -412,8 +418,8 @@ DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0; if (FoundD) *getTrailingObjects() = FoundD; - DeclRefExprBits.HasTemplateKWAndArgsInfo - = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0; + DeclRefExprBits.HasTemplateKWAndArgsInfo = + (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0; DeclRefExprBits.RefersToEnclosingVariableOrCapture = RefersToEnclosingVariableOrCapture; DeclRefExprBits.NonOdrUseReason = NOUR; @@ -432,28 +438,28 @@ setDependence(computeDependence(this, Ctx)); } -DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context, +DeclRefExpr *DeclRefExpr::Create(ASTContext const &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD, - const TemplateArgumentListInfo *TemplateArgs, + TemplateArgumentListInfo const *TemplateArgs, NonOdrUseReason NOUR) { return Create(Context, QualifierLoc, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture, - DeclarationNameInfo(D->getDeclName(), NameLoc), - T, VK, FoundD, TemplateArgs, NOUR); + DeclarationNameInfo(D->getDeclName(), NameLoc), T, VK, FoundD, + TemplateArgs, NOUR); } -DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context, +DeclRefExpr *DeclRefExpr::Create(ASTContext const &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, - const DeclarationNameInfo &NameInfo, + DeclarationNameInfo const &NameInfo, QualType T, ExprValueKind VK, NamedDecl *FoundD, - const TemplateArgumentListInfo *TemplateArgs, + TemplateArgumentListInfo const *TemplateArgs, NonOdrUseReason NOUR) { // Filter out cases where the found Decl is the same as the value refenenced. if (D == FoundD) @@ -473,9 +479,8 @@ FoundD, TemplateArgs, T, VK, NOUR); } -DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context, - bool HasQualifier, - bool HasFoundDecl, +DeclRefExpr *DeclRefExpr::CreateEmpty(ASTContext const &Context, + bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) { assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo); @@ -522,7 +527,7 @@ : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {} SYCLUniqueStableNameExpr * -SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc, +SYCLUniqueStableNameExpr::Create(ASTContext const &Ctx, SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI) { QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst()); @@ -531,7 +536,7 @@ } SYCLUniqueStableNameExpr * -SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) { +SYCLUniqueStableNameExpr::CreateEmpty(ASTContext const &Ctx) { QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst()); return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy); } @@ -544,7 +549,7 @@ std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context, QualType Ty) { auto MangleCallback = [](ASTContext &Ctx, - const NamedDecl *ND) -> llvm::Optional { + NamedDecl const *ND) -> llvm::Optional { // This replaces the 'lambda number' in the mangling with a unique number // based on its order in the declaration. To provide some level of visual // notability (actual uniqueness from normal lambdas isn't necessary, as @@ -589,7 +594,7 @@ PredefinedExprBits.HasFunctionName = HasFunctionName; } -PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L, +PredefinedExpr *PredefinedExpr::Create(ASTContext const &Ctx, SourceLocation L, QualType FNTy, IdentKind IK, StringLiteral *SL) { bool HasFunctionName = SL != nullptr; @@ -598,7 +603,7 @@ return new (Mem) PredefinedExpr(L, FNTy, IK, SL); } -PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx, +PredefinedExpr *PredefinedExpr::CreateEmpty(ASTContext const &Ctx, bool HasFunctionName) { void *Mem = Ctx.Allocate(totalSizeToAlloc(HasFunctionName), alignof(PredefinedExpr)); @@ -629,11 +634,11 @@ // FIXME: Maybe this should use DeclPrinter with a special "print predefined // expr" policy instead. -std::string PredefinedExpr::ComputeName(IdentKind IK, const Decl *CurrentDecl) { +std::string PredefinedExpr::ComputeName(IdentKind IK, Decl const *CurrentDecl) { ASTContext &Context = CurrentDecl->getASTContext(); if (IK == PredefinedExpr::FuncDName) { - if (const NamedDecl *ND = dyn_cast(CurrentDecl)) { + if (NamedDecl const *ND = dyn_cast(CurrentDecl)) { std::unique_ptr MC; MC.reset(Context.createMangleContext()); @@ -641,9 +646,9 @@ SmallString<256> Buffer; llvm::raw_svector_ostream Out(Buffer); GlobalDecl GD; - if (const CXXConstructorDecl *CD = dyn_cast(ND)) + if (CXXConstructorDecl const *CD = dyn_cast(ND)) GD = GlobalDecl(CD, Ctor_Base); - else if (const CXXDestructorDecl *DD = dyn_cast(ND)) + else if (CXXDestructorDecl const *DD = dyn_cast(ND)) GD = GlobalDecl(DD, Dtor_Base); else if (ND->hasAttr()) GD = GlobalDecl(cast(ND)); @@ -676,7 +681,7 @@ Out << ComputeName(IK, DCDecl) << "_block_invoke"; return std::string(Out.str()); } - if (const FunctionDecl *FD = dyn_cast(CurrentDecl)) { + if (FunctionDecl const *FD = dyn_cast(CurrentDecl)) { if (IK != PrettyFunction && IK != PrettyFunctionNoVirtual && IK != FuncSig && IK != LFuncSig) return FD->getNameAsString(); @@ -684,7 +689,7 @@ SmallString<256> Name; llvm::raw_svector_ostream Out(Name); - if (const CXXMethodDecl *MD = dyn_cast(FD)) { + if (CXXMethodDecl const *MD = dyn_cast(FD)) { if (MD->isVirtual() && IK != PrettyFunctionNoVirtual) Out << "virtual "; if (MD->isStatic()) @@ -695,24 +700,37 @@ std::string Proto; llvm::raw_string_ostream POut(Proto); - const FunctionDecl *Decl = FD; - if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern()) + FunctionDecl const *Decl = FD; + if (FunctionDecl const *Pattern = FD->getTemplateInstantiationPattern()) Decl = Pattern; - const FunctionType *AFT = Decl->getType()->getAs(); - const FunctionProtoType *FT = nullptr; + FunctionType const *AFT = Decl->getType()->getAs(); + FunctionProtoType const *FT = nullptr; if (FD->hasWrittenPrototype()) FT = dyn_cast(AFT); if (IK == FuncSig || IK == LFuncSig) { switch (AFT->getCallConv()) { - case CC_C: POut << "__cdecl "; break; - case CC_X86StdCall: POut << "__stdcall "; break; - case CC_X86FastCall: POut << "__fastcall "; break; - case CC_X86ThisCall: POut << "__thiscall "; break; - case CC_X86VectorCall: POut << "__vectorcall "; break; - case CC_X86RegCall: POut << "__regcall "; break; + case CC_C: + POut << "__cdecl "; + break; + case CC_X86StdCall: + POut << "__stdcall "; + break; + case CC_X86FastCall: + POut << "__fastcall "; + break; + case CC_X86ThisCall: + POut << "__thiscall "; + break; + case CC_X86VectorCall: + POut << "__vectorcall "; + break; + case CC_X86RegCall: + POut << "__regcall "; + break; // Only bother printing the conventions that MSVC knows about. - default: break; + default: + break; } } @@ -721,12 +739,14 @@ POut << "("; if (FT) { for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) { - if (i) POut << ", "; + if (i) + POut << ", "; POut << Decl->getParamDecl(i)->getType().stream(Policy); } if (FT->isVariadic()) { - if (FD->getNumParams()) POut << ", "; + if (FD->getNumParams()) + POut << ", "; POut << "..."; } else if ((IK == FuncSig || IK == LFuncSig || !Context.getLangOpts().CPlusPlus) && @@ -736,7 +756,7 @@ } POut << ")"; - if (const CXXMethodDecl *MD = dyn_cast(FD)) { + if (CXXMethodDecl const *MD = dyn_cast(FD)) { assert(FT && "We must have a written prototype in this case."); if (FT->isConst()) POut << " const"; @@ -749,12 +769,12 @@ POut << " &&"; } - typedef SmallVector SpecsTy; + typedef SmallVector SpecsTy; SpecsTy Specs; - const DeclContext *Ctx = FD->getDeclContext(); + DeclContext const *Ctx = FD->getDeclContext(); while (Ctx && isa(Ctx)) { - const ClassTemplateSpecializationDecl *Spec - = dyn_cast(Ctx); + ClassTemplateSpecializationDecl const *Spec = + dyn_cast(Ctx); if (Spec && !Spec->isExplicitSpecialization()) Specs.push_back(Spec); Ctx = Ctx->getParent(); @@ -762,15 +782,16 @@ std::string TemplateParams; llvm::raw_string_ostream TOut(TemplateParams); - for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend(); - I != E; ++I) { - const TemplateParameterList *Params - = (*I)->getSpecializedTemplate()->getTemplateParameters(); - const TemplateArgumentList &Args = (*I)->getTemplateArgs(); + for (SpecsTy::reverse_iterator I = Specs.rbegin(), E = Specs.rend(); I != E; + ++I) { + TemplateParameterList const *Params = + (*I)->getSpecializedTemplate()->getTemplateParameters(); + TemplateArgumentList const &Args = (*I)->getTemplateArgs(); assert(Params->size() == Args.size()); for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) { StringRef Param = Params->getParam(i)->getName(); - if (Param.empty()) continue; + if (Param.empty()) + continue; TOut << Param << " = "; Args.get(i).print( Policy, TOut, @@ -779,16 +800,17 @@ } } - FunctionTemplateSpecializationInfo *FSI - = FD->getTemplateSpecializationInfo(); + FunctionTemplateSpecializationInfo *FSI = + FD->getTemplateSpecializationInfo(); if (FSI && !FSI->isExplicitSpecialization()) { - const TemplateParameterList* Params - = FSI->getTemplate()->getTemplateParameters(); - const TemplateArgumentList* Args = FSI->TemplateArguments; + TemplateParameterList const *Params = + FSI->getTemplate()->getTemplateParameters(); + TemplateArgumentList const *Args = FSI->TemplateArguments; assert(Params->size() == Args->size()); for (unsigned i = 0, e = Params->size(); i != e; ++i) { StringRef Param = Params->getParam(i)->getName(); - if (Param.empty()) continue; + if (Param.empty()) + continue; TOut << Param << " = "; Args->get(i).print(Policy, TOut, /*IncludeType*/ true); TOut << ", "; @@ -809,7 +831,7 @@ // decltype expression. Otherwise print the real type when this is // not a constructor or destructor. if (isa(FD) && - cast(FD)->getParent()->isLambda()) + cast(FD)->getParent()->isLambda()) Proto = "auto " + Proto; else if (FT && FT->getReturnType()->getAs()) FT->getReturnType() @@ -823,17 +845,17 @@ return std::string(Name); } - if (const CapturedDecl *CD = dyn_cast(CurrentDecl)) { - for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent()) + if (CapturedDecl const *CD = dyn_cast(CurrentDecl)) { + for (DeclContext const *DC = CD->getParent(); DC; DC = DC->getParent()) // Skip to its enclosing function or method, but not its enclosing // CapturedDecl. if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) { - const Decl *D = Decl::castFromDeclContext(DC); + Decl const *D = Decl::castFromDeclContext(DC); return ComputeName(IK, D); } llvm_unreachable("CapturedDecl not inside a function or method"); } - if (const ObjCMethodDecl *MD = dyn_cast(CurrentDecl)) { + if (ObjCMethodDecl const *MD = dyn_cast(CurrentDecl)) { SmallString<256> Name; llvm::raw_svector_ostream Out(Name); Out << (MD->isInstanceMethod() ? '-' : '+'); @@ -841,16 +863,16 @@ // For incorrect code, there might not be an ObjCInterfaceDecl. Do // a null check to avoid a crash. - if (const ObjCInterfaceDecl *ID = MD->getClassInterface()) + if (ObjCInterfaceDecl const *ID = MD->getClassInterface()) Out << *ID; - if (const ObjCCategoryImplDecl *CID = - dyn_cast(MD->getDeclContext())) + if (ObjCCategoryImplDecl const *CID = + dyn_cast(MD->getDeclContext())) Out << '(' << *CID << ')'; - Out << ' '; + Out << ' '; MD->getSelector().print(Out); - Out << ']'; + Out << ']'; return std::string(Name); } @@ -861,14 +883,14 @@ return ""; } -void APNumericStorage::setIntValue(const ASTContext &C, - const llvm::APInt &Val) { +void APNumericStorage::setIntValue(ASTContext const &C, + llvm::APInt const &Val) { if (hasAllocation()) C.Deallocate(pVal); BitWidth = Val.getBitWidth(); unsigned NumWords = Val.getNumWords(); - const uint64_t* Words = Val.getRawData(); + uint64_t const *Words = Val.getRawData(); if (NumWords > 1) { pVal = new (C) uint64_t[NumWords]; std::copy(Words, Words + NumWords, pVal); @@ -878,7 +900,7 @@ VAL = 0; } -IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V, +IntegerLiteral::IntegerLiteral(ASTContext const &C, llvm::APInt const &V, QualType type, SourceLocation l) : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) { assert(type->isIntegerType() && "Illegal type in IntegerLiteral"); @@ -888,18 +910,17 @@ setDependence(ExprDependence::None); } -IntegerLiteral * -IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V, - QualType type, SourceLocation l) { +IntegerLiteral *IntegerLiteral::Create(ASTContext const &C, + llvm::APInt const &V, QualType type, + SourceLocation l) { return new (C) IntegerLiteral(C, V, type, l); } -IntegerLiteral * -IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) { +IntegerLiteral *IntegerLiteral::Create(ASTContext const &C, EmptyShell Empty) { return new (C) IntegerLiteral(Empty); } -FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, +FixedPointLiteral::FixedPointLiteral(ASTContext const &C, llvm::APInt const &V, QualType type, SourceLocation l, unsigned Scale) : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l), @@ -911,15 +932,15 @@ setDependence(ExprDependence::None); } -FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C, - const llvm::APInt &V, +FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(ASTContext const &C, + llvm::APInt const &V, QualType type, SourceLocation l, unsigned Scale) { return new (C) FixedPointLiteral(C, V, type, l, Scale); } -FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C, +FixedPointLiteral *FixedPointLiteral::Create(ASTContext const &C, EmptyShell Empty) { return new (C) FixedPointLiteral(Empty); } @@ -1004,7 +1025,7 @@ } } -FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, +FloatingLiteral::FloatingLiteral(ASTContext const &C, llvm::APFloat const &V, bool isexact, QualType Type, SourceLocation L) : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) { setSemantics(V.getSemantics()); @@ -1013,20 +1034,20 @@ setDependence(ExprDependence::None); } -FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty) - : Expr(FloatingLiteralClass, Empty) { +FloatingLiteral::FloatingLiteral(ASTContext const &C, EmptyShell Empty) + : Expr(FloatingLiteralClass, Empty) { setRawSemantics(llvm::APFloatBase::S_IEEEhalf); FloatingLiteralBits.IsExact = false; } -FloatingLiteral * -FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V, - bool isexact, QualType Type, SourceLocation L) { +FloatingLiteral *FloatingLiteral::Create(ASTContext const &C, + llvm::APFloat const &V, bool isexact, + QualType Type, SourceLocation L) { return new (C) FloatingLiteral(C, V, isexact, Type, L); } -FloatingLiteral * -FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) { +FloatingLiteral *FloatingLiteral::Create(ASTContext const &C, + EmptyShell Empty) { return new (C) FloatingLiteral(C, Empty); } @@ -1066,9 +1087,9 @@ return CharByteWidth; } -StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str, +StringLiteral::StringLiteral(ASTContext const &Ctx, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, - const SourceLocation *Loc, + SourceLocation const *Loc, unsigned NumConcatenated) : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) { assert(Ctx.getAsConstantArrayType(Ty) && @@ -1121,9 +1142,9 @@ *getTrailingObjects() = Length; } -StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str, +StringLiteral *StringLiteral::Create(ASTContext const &Ctx, StringRef Str, StringKind Kind, bool Pascal, QualType Ty, - const SourceLocation *Loc, + SourceLocation const *Loc, unsigned NumConcatenated) { void *Mem = Ctx.Allocate(totalSizeToAlloc( 1, NumConcatenated, Str.size()), @@ -1132,7 +1153,7 @@ StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated); } -StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx, +StringLiteral *StringLiteral::CreateEmpty(ASTContext const &Ctx, unsigned NumConcatenated, unsigned Length, unsigned CharByteWidth) { @@ -1145,14 +1166,23 @@ void StringLiteral::outputString(raw_ostream &OS) const { switch (getKind()) { - case Ascii: break; // no prefix. - case Wide: OS << 'L'; break; - case UTF8: OS << "u8"; break; - case UTF16: OS << 'u'; break; - case UTF32: OS << 'U'; break; + case Ascii: + break; // no prefix. + case Wide: + OS << 'L'; + break; + case UTF8: + OS << "u8"; + break; + case UTF16: + OS << 'u'; + break; + case UTF32: + OS << 'U'; + break; } OS << '"'; - static const char Hex[] = "0123456789ABCDEF"; + static char const Hex[] = "0123456789ABCDEF"; unsigned LastSlashX = getLength(); for (unsigned I = 0, N = getLength(); I != N; ++I) { @@ -1175,8 +1205,8 @@ // If this is a wide string, output characters over 0xff using \x // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a // codepoint: use \x escapes for invalid codepoints. - if (getKind() == Wide || - (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) { + if (getKind() == Wide || (Char >= 0xd800 && Char <= 0xdfff) || + Char >= 0x110000) { // FIXME: Is this the best way to print wchar_t? OS << "\\x"; int Shift = 28; @@ -1189,15 +1219,11 @@ } if (Char > 0xffff) - OS << "\\U00" - << Hex[(Char >> 20) & 15] - << Hex[(Char >> 16) & 15]; + OS << "\\U00" << Hex[(Char >> 20) & 15] << Hex[(Char >> 16) & 15]; else OS << "\\u"; - OS << Hex[(Char >> 12) & 15] - << Hex[(Char >> 8) & 15] - << Hex[(Char >> 4) & 15] - << Hex[(Char >> 0) & 15]; + OS << Hex[(Char >> 12) & 15] << Hex[(Char >> 8) & 15] + << Hex[(Char >> 4) & 15] << Hex[(Char >> 0) & 15]; break; } @@ -1205,11 +1231,29 @@ // hexadecimal digit, prevent it being slurped as part of the \x. if (LastSlashX + 1 == I) { switch (Char) { - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': - case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': - OS << "\"\""; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + OS << "\"\""; } } @@ -1218,22 +1262,39 @@ if (isPrintable(Char)) OS << (char)Char; - else // Output anything hard as an octal escape. - OS << '\\' - << (char)('0' + ((Char >> 6) & 7)) + else // Output anything hard as an octal escape. + OS << '\\' << (char)('0' + ((Char >> 6) & 7)) << (char)('0' + ((Char >> 3) & 7)) << (char)('0' + ((Char >> 0) & 7)); break; // Handle some common non-printable cases to make dumps prettier. - case '\\': OS << "\\\\"; break; - case '"': OS << "\\\""; break; - case '\a': OS << "\\a"; break; - case '\b': OS << "\\b"; break; - case '\f': OS << "\\f"; break; - case '\n': OS << "\\n"; break; - case '\r': OS << "\\r"; break; - case '\t': OS << "\\t"; break; - case '\v': OS << "\\v"; break; + case '\\': + OS << "\\\\"; + break; + case '"': + OS << "\\\""; + break; + case '\a': + OS << "\\a"; + break; + case '\b': + OS << "\\b"; + break; + case '\f': + OS << "\\f"; + break; + case '\n': + OS << "\\n"; + break; + case '\r': + OS << "\\r"; + break; + case '\t': + OS << "\\t"; + break; + case '\v': + OS << "\\v"; + break; } } OS << '"'; @@ -1256,13 +1317,13 @@ /// string. /// SourceLocation -StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM, - const LangOptions &Features, - const TargetInfo &Target, unsigned *StartToken, +StringLiteral::getLocationOfByte(unsigned ByteNo, SourceManager const &SM, + LangOptions const &Features, + TargetInfo const &Target, unsigned *StartToken, unsigned *StartTokenByteOffset) const { - assert((getKind() == StringLiteral::Ascii || - getKind() == StringLiteral::UTF8) && - "Only narrow string literals are currently supported"); + assert( + (getKind() == StringLiteral::Ascii || getKind() == StringLiteral::UTF8) && + "Only narrow string literals are currently supported"); // Loop over all of the tokens in this string until we find the one that // contains the byte we're looking for. @@ -1296,7 +1357,7 @@ return StrTokSpellingLoc; } - const char *StrData = Buffer.data()+LocInfo.second; + char const *StrData = Buffer.data() + LocInfo.second; // Create a lexer starting at the beginning of this token. Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features, @@ -1333,44 +1394,67 @@ /// corresponds to, e.g. "sizeof" or "[pre]++". StringRef UnaryOperator::getOpcodeStr(Opcode Op) { switch (Op) { -#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling; +#define UNARY_OPERATION(Name, Spelling) \ + case UO_##Name: \ + return Spelling; #include "clang/AST/OperationKinds.def" } llvm_unreachable("Unknown unary operator"); } -UnaryOperatorKind -UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) { +UnaryOperatorKind UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, + bool Postfix) { switch (OO) { - default: llvm_unreachable("No unary operator for overloaded function"); - case OO_PlusPlus: return Postfix ? UO_PostInc : UO_PreInc; - case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec; - case OO_Amp: return UO_AddrOf; - case OO_Star: return UO_Deref; - case OO_Plus: return UO_Plus; - case OO_Minus: return UO_Minus; - case OO_Tilde: return UO_Not; - case OO_Exclaim: return UO_LNot; - case OO_Coawait: return UO_Coawait; + default: + llvm_unreachable("No unary operator for overloaded function"); + case OO_PlusPlus: + return Postfix ? UO_PostInc : UO_PreInc; + case OO_MinusMinus: + return Postfix ? UO_PostDec : UO_PreDec; + case OO_Amp: + return UO_AddrOf; + case OO_Star: + return UO_Deref; + case OO_Plus: + return UO_Plus; + case OO_Minus: + return UO_Minus; + case OO_Tilde: + return UO_Not; + case OO_Exclaim: + return UO_LNot; + case OO_Coawait: + return UO_Coawait; } } OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) { switch (Opc) { - case UO_PostInc: case UO_PreInc: return OO_PlusPlus; - case UO_PostDec: case UO_PreDec: return OO_MinusMinus; - case UO_AddrOf: return OO_Amp; - case UO_Deref: return OO_Star; - case UO_Plus: return OO_Plus; - case UO_Minus: return OO_Minus; - case UO_Not: return OO_Tilde; - case UO_LNot: return OO_Exclaim; - case UO_Coawait: return OO_Coawait; - default: return OO_None; + case UO_PostInc: + case UO_PreInc: + return OO_PlusPlus; + case UO_PostDec: + case UO_PreDec: + return OO_MinusMinus; + case UO_AddrOf: + return OO_Amp; + case UO_Deref: + return OO_Star; + case UO_Plus: + return OO_Plus; + case UO_Minus: + return OO_Minus; + case UO_Not: + return OO_Tilde; + case UO_LNot: + return OO_Exclaim; + case UO_Coawait: + return OO_Coawait; + default: + return OO_None; } } - //===----------------------------------------------------------------------===// // Postfix Operators. //===----------------------------------------------------------------------===// @@ -1420,7 +1504,7 @@ CallExprBits.HasFPFeatures = HasFPFeatures; } -CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn, +CallExpr *CallExpr::Create(ASTContext const &Ctx, Expr *Fn, ArrayRef Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs, @@ -1444,7 +1528,7 @@ /*MinNumArgs=*/0, UsesADL); } -CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs, +CallExpr *CallExpr::CreateEmpty(ASTContext const &Ctx, unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty) { unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures); @@ -1513,18 +1597,18 @@ return FDecl ? FDecl->getBuiltinID() : 0; } -bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const { +bool CallExpr::isUnevaluatedBuiltinCall(ASTContext const &Ctx) const { if (unsigned BI = getBuiltinCallee()) return Ctx.BuiltinInfo.isUnevaluated(BI); return false; } -QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const { - const Expr *Callee = getCallee(); +QualType CallExpr::getCallReturnType(ASTContext const &Ctx) const { + Expr const *Callee = getCallee(); QualType CalleeType = Callee->getType(); - if (const auto *FnTypePtr = CalleeType->getAs()) { + if (auto const *FnTypePtr = CalleeType->getAs()) { CalleeType = FnTypePtr->getPointeeType(); - } else if (const auto *BPT = CalleeType->getAs()) { + } else if (auto const *BPT = CalleeType->getAs()) { CalleeType = BPT->getPointeeType(); } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) { if (isa(Callee->IgnoreParens())) @@ -1541,20 +1625,20 @@ return Ctx.DependentTy; } - const FunctionType *FnType = CalleeType->castAs(); + FunctionType const *FnType = CalleeType->castAs(); return FnType->getReturnType(); } -const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const { +Attr const *CallExpr::getUnusedResultAttr(ASTContext const &Ctx) const { // If the return type is a struct, union, or enum that is marked nodiscard, // then return the return type attribute. - if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl()) - if (const auto *A = TD->getAttr()) + if (TagDecl const *TD = getCallReturnType(Ctx)->getAsTagDecl()) + if (auto const *A = TD->getAttr()) return A; // Otherwise, see if the callee is marked nodiscard and return that attribute // instead. - const Decl *D = getCalleeDecl(); + Decl const *D = getCalleeDecl(); return D ? D->getAttr() : nullptr; } @@ -1577,27 +1661,27 @@ return end; } -OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type, +OffsetOfExpr *OffsetOfExpr::Create(ASTContext const &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef comps, - ArrayRef exprs, + ArrayRef exprs, SourceLocation RParenLoc) { void *Mem = C.Allocate( totalSizeToAlloc(comps.size(), exprs.size())); - return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs, - RParenLoc); + return new (Mem) + OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs, RParenLoc); } -OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C, - unsigned numComps, unsigned numExprs) { +OffsetOfExpr *OffsetOfExpr::CreateEmpty(ASTContext const &C, unsigned numComps, + unsigned numExprs) { void *Mem = C.Allocate(totalSizeToAlloc(numComps, numExprs)); return new (Mem) OffsetOfExpr(numComps, numExprs); } -OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type, +OffsetOfExpr::OffsetOfExpr(ASTContext const &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef comps, ArrayRef exprs, SourceLocation RParenLoc) @@ -1617,7 +1701,7 @@ if (getKind() == Field) return getField()->getIdentifier(); - return reinterpret_cast (Data & ~(uintptr_t)Mask); + return reinterpret_cast(Data & ~(uintptr_t)Mask); } UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr( @@ -1636,7 +1720,7 @@ MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc, ValueDecl *MemberDecl, - const DeclarationNameInfo &NameInfo, QualType T, + DeclarationNameInfo const &NameInfo, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl), @@ -1653,10 +1737,10 @@ } MemberExpr *MemberExpr::Create( - const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, + ASTContext const &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, - DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs, + DeclarationNameInfo NameInfo, TemplateArgumentListInfo const *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) { bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl || FoundDecl.getAccess() != MemberDecl->getAccess(); @@ -1708,7 +1792,7 @@ return E; } -MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context, +MemberExpr *MemberExpr::CreateEmpty(ASTContext const &Context, bool HasQualifier, bool HasFoundDecl, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) { @@ -1871,9 +1955,9 @@ case CK_MemberPointerToBoolean: case CK_FloatingComplexToBoolean: case CK_IntegralComplexToBoolean: - case CK_LValueBitCast: // -> bool& + case CK_LValueBitCast: // -> bool& case CK_LValueToRValueBitCast: - case CK_UserDefinedConversion: // operator bool() + case CK_UserDefinedConversion: // operator bool() case CK_BuiltinFnToFnPtr: case CK_FixedPointToBoolean: CheckNoBasePath: @@ -1883,43 +1967,44 @@ return true; } -const char *CastExpr::getCastKindName(CastKind CK) { +char const *CastExpr::getCastKindName(CastKind CK) { switch (CK) { -#define CAST_OPERATION(Name) case CK_##Name: return #Name; +#define CAST_OPERATION(Name) \ + case CK_##Name: \ + return #Name; #include "clang/AST/OperationKinds.def" } llvm_unreachable("Unhandled cast kind!"); } namespace { - const Expr *skipImplicitTemporary(const Expr *E) { - // Skip through reference binding to temporary. - if (auto *Materialize = dyn_cast(E)) - E = Materialize->getSubExpr(); +Expr const *skipImplicitTemporary(Expr const *E) { + // Skip through reference binding to temporary. + if (auto *Materialize = dyn_cast(E)) + E = Materialize->getSubExpr(); - // Skip any temporary bindings; they're implicit. - if (auto *Binder = dyn_cast(E)) - E = Binder->getSubExpr(); + // Skip any temporary bindings; they're implicit. + if (auto *Binder = dyn_cast(E)) + E = Binder->getSubExpr(); - return E; - } + return E; } +} // namespace Expr *CastExpr::getSubExprAsWritten() { - const Expr *SubExpr = nullptr; - const CastExpr *E = this; + Expr const *SubExpr = nullptr; + CastExpr const *E = this; do { SubExpr = skipImplicitTemporary(E->getSubExpr()); // Conversions by constructor and conversion functions have a // subexpression describing the call; strip it off. if (E->getCastKind() == CK_ConstructorConversion) - SubExpr = - skipImplicitTemporary(cast(SubExpr->IgnoreImplicit())->getArg(0)); + SubExpr = skipImplicitTemporary( + cast(SubExpr->IgnoreImplicit())->getArg(0)); else if (E->getCastKind() == CK_UserDefinedConversion) { SubExpr = SubExpr->IgnoreImplicit(); - assert((isa(SubExpr) || - isa(SubExpr)) && + assert((isa(SubExpr) || isa(SubExpr)) && "Unexpected SubExpr for CK_UserDefinedConversion."); if (auto *MCE = dyn_cast(SubExpr)) SubExpr = MCE->getImplicitObjectArgument(); @@ -1929,13 +2014,13 @@ // through that, too. } while ((E = dyn_cast(SubExpr))); - return const_cast(SubExpr); + return const_cast(SubExpr); } NamedDecl *CastExpr::getConversionFunction() const { - const Expr *SubExpr = nullptr; + Expr const *SubExpr = nullptr; - for (const CastExpr *E = this; E; E = dyn_cast(SubExpr)) { + for (CastExpr const *E = this; E; E = dyn_cast(SubExpr)) { SubExpr = skipImplicitTemporary(E->getSubExpr()); if (E->getCastKind() == CK_ConstructorConversion) @@ -1963,18 +2048,18 @@ } } -const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType, +FieldDecl const *CastExpr::getTargetFieldForToUnionCast(QualType unionType, QualType opType) { auto RD = unionType->castAs()->getDecl(); return getTargetFieldForToUnionCast(RD, opType); } -const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD, +FieldDecl const *CastExpr::getTargetFieldForToUnionCast(RecordDecl const *RD, QualType OpType) { auto &Ctx = RD->getASTContext(); RecordDecl::field_iterator Field, FieldEnd; - for (Field = RD->field_begin(), FieldEnd = RD->field_end(); - Field != FieldEnd; ++Field) { + for (Field = RD->field_begin(), FieldEnd = RD->field_end(); Field != FieldEnd; + ++Field) { if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) && !Field->isUnnamedBitfield()) { return *Field; @@ -2003,9 +2088,9 @@ } } -ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T, +ImplicitCastExpr *ImplicitCastExpr::Create(ASTContext const &C, QualType T, CastKind Kind, Expr *Operand, - const CXXCastPath *BasePath, + CXXCastPath const *BasePath, ExprValueKind VK, FPOptionsOverride FPO) { unsigned PathSize = (BasePath ? BasePath->size() : 0); @@ -2025,7 +2110,7 @@ return E; } -ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C, +ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(ASTContext const &C, unsigned PathSize, bool HasFPFeatures) { void *Buffer = @@ -2034,9 +2119,9 @@ return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures); } -CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T, +CStyleCastExpr *CStyleCastExpr::Create(ASTContext const &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, - const CXXCastPath *BasePath, + CXXCastPath const *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R) { @@ -2052,7 +2137,7 @@ return E; } -CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C, +CStyleCastExpr *CStyleCastExpr::CreateEmpty(ASTContext const &C, unsigned PathSize, bool HasFPFeatures) { void *Buffer = @@ -2065,7 +2150,9 @@ /// corresponds to, e.g. "<<=". StringRef BinaryOperator::getOpcodeStr(Opcode Op) { switch (Op) { -#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling; +#define BINARY_OPERATION(Name, Spelling) \ + case BO_##Name: \ + return Spelling; #include "clang/AST/OperationKinds.def" } llvm_unreachable("Invalid OpCode!"); @@ -2074,70 +2161,116 @@ BinaryOperatorKind BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) { switch (OO) { - default: llvm_unreachable("Not an overloadable binary operator"); - case OO_Plus: return BO_Add; - case OO_Minus: return BO_Sub; - case OO_Star: return BO_Mul; - case OO_Slash: return BO_Div; - case OO_Percent: return BO_Rem; - case OO_Caret: return BO_Xor; - case OO_Amp: return BO_And; - case OO_Pipe: return BO_Or; - case OO_Equal: return BO_Assign; - case OO_Spaceship: return BO_Cmp; - case OO_Less: return BO_LT; - case OO_Greater: return BO_GT; - case OO_PlusEqual: return BO_AddAssign; - case OO_MinusEqual: return BO_SubAssign; - case OO_StarEqual: return BO_MulAssign; - case OO_SlashEqual: return BO_DivAssign; - case OO_PercentEqual: return BO_RemAssign; - case OO_CaretEqual: return BO_XorAssign; - case OO_AmpEqual: return BO_AndAssign; - case OO_PipeEqual: return BO_OrAssign; - case OO_LessLess: return BO_Shl; - case OO_GreaterGreater: return BO_Shr; - case OO_LessLessEqual: return BO_ShlAssign; - case OO_GreaterGreaterEqual: return BO_ShrAssign; - case OO_EqualEqual: return BO_EQ; - case OO_ExclaimEqual: return BO_NE; - case OO_LessEqual: return BO_LE; - case OO_GreaterEqual: return BO_GE; - case OO_AmpAmp: return BO_LAnd; - case OO_PipePipe: return BO_LOr; - case OO_Comma: return BO_Comma; - case OO_ArrowStar: return BO_PtrMemI; + default: + llvm_unreachable("Not an overloadable binary operator"); + case OO_Plus: + return BO_Add; + case OO_Minus: + return BO_Sub; + case OO_Star: + return BO_Mul; + case OO_Slash: + return BO_Div; + case OO_Percent: + return BO_Rem; + case OO_Caret: + return BO_Xor; + case OO_Amp: + return BO_And; + case OO_Pipe: + return BO_Or; + case OO_Equal: + return BO_Assign; + case OO_Spaceship: + return BO_Cmp; + case OO_Less: + return BO_LT; + case OO_Greater: + return BO_GT; + case OO_PlusEqual: + return BO_AddAssign; + case OO_MinusEqual: + return BO_SubAssign; + case OO_StarEqual: + return BO_MulAssign; + case OO_SlashEqual: + return BO_DivAssign; + case OO_PercentEqual: + return BO_RemAssign; + case OO_CaretEqual: + return BO_XorAssign; + case OO_AmpEqual: + return BO_AndAssign; + case OO_PipeEqual: + return BO_OrAssign; + case OO_LessLess: + return BO_Shl; + case OO_GreaterGreater: + return BO_Shr; + case OO_LessLessEqual: + return BO_ShlAssign; + case OO_GreaterGreaterEqual: + return BO_ShrAssign; + case OO_EqualEqual: + return BO_EQ; + case OO_ExclaimEqual: + return BO_NE; + case OO_LessEqual: + return BO_LE; + case OO_GreaterEqual: + return BO_GE; + case OO_AmpAmp: + return BO_LAnd; + case OO_PipePipe: + return BO_LOr; + case OO_Comma: + return BO_Comma; + case OO_ArrowStar: + return BO_PtrMemI; } } OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) { static const OverloadedOperatorKind OverOps[] = { - /* .* Cannot be overloaded */OO_None, OO_ArrowStar, - OO_Star, OO_Slash, OO_Percent, - OO_Plus, OO_Minus, - OO_LessLess, OO_GreaterGreater, - OO_Spaceship, - OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual, - OO_EqualEqual, OO_ExclaimEqual, - OO_Amp, - OO_Caret, - OO_Pipe, - OO_AmpAmp, - OO_PipePipe, - OO_Equal, OO_StarEqual, - OO_SlashEqual, OO_PercentEqual, - OO_PlusEqual, OO_MinusEqual, - OO_LessLessEqual, OO_GreaterGreaterEqual, - OO_AmpEqual, OO_CaretEqual, - OO_PipeEqual, - OO_Comma - }; + /* .* Cannot be overloaded */ OO_None, + OO_ArrowStar, + OO_Star, + OO_Slash, + OO_Percent, + OO_Plus, + OO_Minus, + OO_LessLess, + OO_GreaterGreater, + OO_Spaceship, + OO_Less, + OO_Greater, + OO_LessEqual, + OO_GreaterEqual, + OO_EqualEqual, + OO_ExclaimEqual, + OO_Amp, + OO_Caret, + OO_Pipe, + OO_AmpAmp, + OO_PipePipe, + OO_Equal, + OO_StarEqual, + OO_SlashEqual, + OO_PercentEqual, + OO_PlusEqual, + OO_MinusEqual, + OO_LessLessEqual, + OO_GreaterGreaterEqual, + OO_AmpEqual, + OO_CaretEqual, + OO_PipeEqual, + OO_Comma}; return OverOps[Opc]; } bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx, - Opcode Opc, - Expr *LHS, Expr *RHS) { + Opcode Opc, Expr *LHS, + Expr *RHS) { if (Opc != BO_Add) return false; @@ -2156,19 +2289,19 @@ } // Check that the pointer is a nullptr. - if (!PExp->IgnoreParenCasts() - ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull)) + if (!PExp->IgnoreParenCasts()->isNullPointerConstant( + Ctx, Expr::NPC_ValueDependentIsNotNull)) return false; // Check that the pointee type is char-sized. - const PointerType *PTy = PExp->getType()->getAs(); + PointerType const *PTy = PExp->getType()->getAs(); if (!PTy || !PTy->getPointeeType()->isCharType()) return false; return true; } -static QualType getDecayedSourceLocExprType(const ASTContext &Ctx, +static QualType getDecayedSourceLocExprType(ASTContext const &Ctx, SourceLocExpr::IdentKind Kind) { switch (Kind) { case SourceLocExpr::File: @@ -2183,7 +2316,7 @@ llvm_unreachable("unhandled case"); } -SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, IdentKind Kind, +SourceLocExpr::SourceLocExpr(ASTContext const &Ctx, IdentKind Kind, SourceLocation BLoc, SourceLocation RParenLoc, DeclContext *ParentContext) : Expr(SourceLocExprClass, getDecayedSourceLocExprType(Ctx, Kind), @@ -2207,13 +2340,13 @@ llvm_unreachable("unexpected IdentKind!"); } -APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx, - const Expr *DefaultExpr) const { +APValue SourceLocExpr::EvaluateInContext(ASTContext const &Ctx, + Expr const *DefaultExpr) const { SourceLocation Loc; - const DeclContext *Context; + DeclContext const *Context; std::tie(Loc, - Context) = [&]() -> std::pair { + Context) = [&]() -> std::pair { if (auto *DIE = dyn_cast_or_null(DefaultExpr)) return {DIE->getUsedLocation(), DIE->getUsedContext()}; if (auto *DAE = dyn_cast_or_null(DefaultExpr)) @@ -2239,7 +2372,7 @@ return MakeStringLiteral(Path); } case SourceLocExpr::Function: { - const Decl *CurDecl = dyn_cast_or_null(Context); + Decl const *CurDecl = dyn_cast_or_null(Context); return MakeStringLiteral( CurDecl ? PredefinedExpr::ComputeName(PredefinedExpr::Function, CurDecl) : std::string("")); @@ -2256,7 +2389,7 @@ llvm_unreachable("unhandled case"); } -InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc, +InitListExpr::InitListExpr(ASTContext const &C, SourceLocation lbraceloc, ArrayRef initExprs, SourceLocation rbraceloc) : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary), InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc), @@ -2267,16 +2400,16 @@ setDependence(computeDependence(this)); } -void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) { +void InitListExpr::reserveInits(ASTContext const &C, unsigned NumInits) { if (NumInits > InitExprs.size()) InitExprs.reserve(C, NumInits); } -void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) { +void InitListExpr::resizeInits(ASTContext const &C, unsigned NumInits) { InitExprs.resize(C, NumInits, nullptr); } -Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) { +Expr *InitListExpr::updateInit(ASTContext const &C, unsigned Init, Expr *expr) { if (Init >= InitExprs.size()) { InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr); setInit(Init, expr); @@ -2301,11 +2434,11 @@ bool InitListExpr::isStringLiteralInit() const { if (getNumInits() != 1) return false; - const ArrayType *AT = getType()->getAsArrayTypeUnsafe(); + ArrayType const *AT = getType()->getAsArrayTypeUnsafe(); if (!AT || !AT->getElementType()->isIntegerType()) return false; // It is possible for getInit() to return null. - const Expr *Init = getInit(0); + Expr const *Init = getInit(0); if (!Init) return false; Init = Init->IgnoreParenImpCasts(); @@ -2335,14 +2468,16 @@ getInit(0)->getType().getCanonicalType(); } -bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const { +bool InitListExpr::isIdiomaticZeroInitializer( + LangOptions const &LangOpts) const { assert(isSyntacticForm() && "only test syntactic form as zero initializer"); if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) { return false; } - const IntegerLiteral *Lit = dyn_cast(getInit(0)->IgnoreImplicit()); + IntegerLiteral const *Lit = + dyn_cast(getInit(0)->IgnoreImplicit()); return Lit && Lit->getValue() == 0; } @@ -2352,9 +2487,8 @@ SourceLocation Beg = LBraceLoc; if (Beg.isInvalid()) { // Find the first non-null initializer. - for (InitExprsTy::const_iterator I = InitExprs.begin(), - E = InitExprs.end(); - I != E; ++I) { + for (InitExprsTy::const_iterator I = InitExprs.begin(), E = InitExprs.end(); + I != E; ++I) { if (Stmt *S = *I) { Beg = S->getBeginLoc(); break; @@ -2371,7 +2505,7 @@ if (End.isInvalid()) { // Find the first non-null initializer from the end. for (InitExprsTy::const_reverse_iterator I = InitExprs.rbegin(), - E = InitExprs.rend(); + E = InitExprs.rend(); I != E; ++I) { if (Stmt *S = *I) { End = S->getEndLoc(); @@ -2384,22 +2518,18 @@ /// getFunctionType - Return the underlying function type for this block. /// -const FunctionProtoType *BlockExpr::getFunctionType() const { +FunctionProtoType const *BlockExpr::getFunctionType() const { // The block pointer is never sugared, but the function type might be. return cast(getType()) - ->getPointeeType()->castAs(); + ->getPointeeType() + ->castAs(); } SourceLocation BlockExpr::getCaretLocation() const { return TheBlock->getCaretLocation(); } -const Stmt *BlockExpr::getBody() const { - return TheBlock->getBody(); -} -Stmt *BlockExpr::getBody() { - return TheBlock->getBody(); -} - +Stmt const *BlockExpr::getBody() const { return TheBlock->getBody(); } +Stmt *BlockExpr::getBody() { return TheBlock->getBody(); } //===----------------------------------------------------------------------===// // Generic Expression Routines @@ -2414,7 +2544,7 @@ if (!isGLValue() || !getType().isVolatileQualified()) return false; - const Expr *E = IgnoreParens(); + Expr const *E = IgnoreParens(); // - id-expression (5.1.1), if (isa(E)) @@ -2449,8 +2579,7 @@ return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() && CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11(); // The related edge case of "*x ?: *x". - if (auto *BCO = - dyn_cast(E)) { + if (auto *BCO = dyn_cast(E)) { if (auto *OVE = dyn_cast(BCO->getTrueExpr())) return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() && BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11(); @@ -2467,7 +2596,7 @@ /// be warned about if the result is unused. If so, fill in Loc and Ranges /// with location to warn on and the source range[s] to report with the /// warning. -bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc, +bool Expr::isUnusedResultAWarning(Expr const *&WarnE, SourceLocation &Loc, SourceRange &R1, SourceRange &R2, ASTContext &Ctx) const { // Don't warn if the expr is type dependent. The type could end up @@ -2484,20 +2613,22 @@ R1 = getSourceRange(); return true; case ParenExprClass: - return cast(this)->getSubExpr()-> - isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); + return cast(this)->getSubExpr()->isUnusedResultAWarning( + WarnE, Loc, R1, R2, Ctx); case GenericSelectionExprClass: - return cast(this)->getResultExpr()-> - isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); + return cast(this) + ->getResultExpr() + ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case CoawaitExprClass: case CoyieldExprClass: - return cast(this)->getResumeExpr()-> - isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); + return cast(this) + ->getResumeExpr() + ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case ChooseExprClass: - return cast(this)->getChosenSubExpr()-> - isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); + return cast(this)->getChosenSubExpr()->isUnusedResultAWarning( + WarnE, Loc, R1, R2, Ctx); case UnaryOperatorClass: { - const UnaryOperator *UO = cast(this); + UnaryOperator const *UO = cast(this); switch (UO->getOpcode()) { case UO_Plus: @@ -2513,13 +2644,13 @@ case UO_PostInc: case UO_PostDec: case UO_PreInc: - case UO_PreDec: // ++/-- - return false; // Not a warning. + case UO_PreDec: // ++/-- + return false; // Not a warning. case UO_Real: case UO_Imag: // accessing a piece of a volatile complex is a side-effect. if (Ctx.getCanonicalType(UO->getSubExpr()->getType()) - .isVolatileQualified()) + .isVolatileQualified()) return false; break; case UO_Extension: @@ -2531,27 +2662,27 @@ return true; } case BinaryOperatorClass: { - const BinaryOperator *BO = cast(this); + BinaryOperator const *BO = cast(this); switch (BO->getOpcode()) { - default: - break; - // Consider the RHS of comma for side effects. LHS was checked by - // Sema::CheckCommaOperands. - case BO_Comma: - // ((foo = ), 0) is an idiom for hiding the result (and - // lvalue-ness) of an assignment written in a macro. - if (IntegerLiteral *IE = + default: + break; + // Consider the RHS of comma for side effects. LHS was checked by + // Sema::CheckCommaOperands. + case BO_Comma: + // ((foo = ), 0) is an idiom for hiding the result (and + // lvalue-ness) of an assignment written in a macro. + if (IntegerLiteral *IE = dyn_cast(BO->getRHS()->IgnoreParens())) - if (IE->getValue() == 0) - return false; - return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); - // Consider '||', '&&' to have side effects if the LHS or RHS does. - case BO_LAnd: - case BO_LOr: - if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) || - !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)) + if (IE->getValue() == 0) return false; - break; + return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); + // Consider '||', '&&' to have side effects if the LHS or RHS does. + case BO_LAnd: + case BO_LOr: + if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) || + !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)) + return false; + break; } if (BO->isAssignmentOp()) return false; @@ -2570,12 +2701,12 @@ // If only one of the LHS or RHS is a warning, the operator might // be being used for control flow. Only warn if both the LHS and // RHS are warnings. - const auto *Exp = cast(this); + auto const *Exp = cast(this); return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) && Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } case BinaryConditionalOperatorClass: { - const auto *Exp = cast(this); + auto const *Exp = cast(this); return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } @@ -2600,7 +2731,7 @@ // warning: operators == and != are commonly typo'ed, and so warning on them // provides additional value as well. If this list is updated, // DiagnoseUnusedComparison should be as well. - const CXXOperatorCallExpr *Op = cast(this); + CXXOperatorCallExpr const *Op = cast(this); switch (Op->getOperator()) { default: break; @@ -2626,15 +2757,15 @@ case CXXMemberCallExprClass: case UserDefinedLiteralClass: { // If this is a direct call, get the callee. - const CallExpr *CE = cast(this); - if (const Decl *FD = CE->getCalleeDecl()) { + CallExpr const *CE = cast(this); + if (Decl const *FD = CE->getCalleeDecl()) { // If the callee has attribute pure, const, or warn_unused_result, warn // about it. void foo() { strlen("bar"); } should warn. // // Note: If new cases are added here, DiagnoseUnusedExprResult should be // updated to match for QoI. - if (CE->hasUnusedResultAttr(Ctx) || - FD->hasAttr() || FD->hasAttr()) { + if (CE->hasUnusedResultAttr(Ctx) || FD->hasAttr() || + FD->hasAttr()) { WarnE = this; Loc = CE->getCallee()->getBeginLoc(); R1 = CE->getCallee()->getSourceRange(); @@ -2656,8 +2787,8 @@ case CXXTemporaryObjectExprClass: case CXXConstructExprClass: { - if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) { - const auto *WarnURAttr = Type->getAttr(); + if (CXXRecordDecl const *Type = getType()->getAsCXXRecordDecl()) { + auto const *WarnURAttr = Type->getAttr(); if (Type->hasAttr() || (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) { WarnE = this; @@ -2667,9 +2798,9 @@ } } - const auto *CE = cast(this); - if (const CXXConstructorDecl *Ctor = CE->getConstructor()) { - const auto *WarnURAttr = Ctor->getAttr(); + auto const *CE = cast(this); + if (CXXConstructorDecl const *Ctor = CE->getConstructor()) { + auto const *WarnURAttr = Ctor->getAttr(); if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) { WarnE = this; Loc = getBeginLoc(); @@ -2686,18 +2817,16 @@ } case ObjCMessageExprClass: { - const ObjCMessageExpr *ME = cast(this); - if (Ctx.getLangOpts().ObjCAutoRefCount && - ME->isInstanceMessage() && - !ME->getType()->isVoidType() && - ME->getMethodFamily() == OMF_init) { + ObjCMessageExpr const *ME = cast(this); + if (Ctx.getLangOpts().ObjCAutoRefCount && ME->isInstanceMessage() && + !ME->getType()->isVoidType() && ME->getMethodFamily() == OMF_init) { WarnE = this; Loc = getExprLoc(); R1 = ME->getSourceRange(); return true; } - if (const ObjCMethodDecl *MD = ME->getMethodDecl()) + if (ObjCMethodDecl const *MD = ME->getMethodDecl()) if (MD->hasAttr()) { WarnE = this; Loc = getExprLoc(); @@ -2714,7 +2843,7 @@ return true; case PseudoObjectExprClass: { - const PseudoObjectExpr *PO = cast(this); + PseudoObjectExpr const *PO = cast(this); // Only complain about things that have the form of a getter. if (isa(PO->getSyntacticForm()) || @@ -2733,12 +2862,12 @@ // For example ({ blah; foo(); }) will end up with a type if foo has a type. // however, if the result of the stmt expr is dead, we don't want to emit a // warning. - const CompoundStmt *CS = cast(this)->getSubStmt(); + CompoundStmt const *CS = cast(this)->getSubStmt(); if (!CS->body_empty()) { - if (const Expr *E = dyn_cast(CS->body_back())) + if (Expr const *E = dyn_cast(CS->body_back())) return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); - if (const LabelStmt *Label = dyn_cast(CS->body_back())) - if (const Expr *E = dyn_cast(Label->getSubStmt())) + if (LabelStmt const *Label = dyn_cast(CS->body_back())) + if (Expr const *E = dyn_cast(Label->getSubStmt())) return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } @@ -2757,8 +2886,8 @@ // the lvalue conversion in C, and happens in C++ for expressions of all // forms where it seems likely the user intended to trigger a volatile // load.) - const CastExpr *CE = cast(this); - const Expr *SubE = CE->getSubExpr()->IgnoreParens(); + CastExpr const *CE = cast(this); + Expr const *SubE = CE->getSubExpr()->IgnoreParens(); if (CE->getCastKind() == CK_ToVoid) { if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 && SubE->isReadIfDiscardedInCPlusPlus11()) { @@ -2788,19 +2917,19 @@ return false; WarnE = this; - if (const CXXFunctionalCastExpr *CXXCE = + if (CXXFunctionalCastExpr const *CXXCE = dyn_cast(this)) { Loc = CXXCE->getBeginLoc(); R1 = CXXCE->getSubExpr()->getSourceRange(); } else { - const CStyleCastExpr *CStyleCE = cast(this); + CStyleCastExpr const *CStyleCE = cast(this); Loc = CStyleCE->getLParenLoc(); R1 = CStyleCE->getSubExpr()->getSourceRange(); } return true; } case ImplicitCastExprClass: { - const CastExpr *ICE = cast(this); + CastExpr const *ICE = cast(this); // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect. if (ICE->getCastKind() == CK_LValueToRValue && @@ -2810,11 +2939,11 @@ return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); } case CXXDefaultArgExprClass: - return (cast(this) - ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); + return (cast(this)->getExpr()->isUnusedResultAWarning( + WarnE, Loc, R1, R2, Ctx)); case CXXDefaultInitExprClass: - return (cast(this) - ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx)); + return (cast(this)->getExpr()->isUnusedResultAWarning( + WarnE, Loc, R1, R2, Ctx)); case CXXNewExprClass: // FIXME: In theory, there might be new expressions that don't have side @@ -2826,18 +2955,19 @@ ->getSubExpr() ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case CXXBindTemporaryExprClass: - return cast(this)->getSubExpr() - ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); + return cast(this) + ->getSubExpr() + ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); case ExprWithCleanupsClass: - return cast(this)->getSubExpr() - ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx); + return cast(this)->getSubExpr()->isUnusedResultAWarning( + WarnE, Loc, R1, R2, Ctx); } } /// isOBJCGCCandidate - Check if an expression is objc gc'able. /// returns true, if it is; false otherwise. bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const { - const Expr *E = IgnoreParens(); + Expr const *E = IgnoreParens(); switch (E->getStmtClass()) { default: return false; @@ -2853,9 +2983,9 @@ case CStyleCastExprClass: return cast(E)->getSubExpr()->isOBJCGCCandidate(Ctx); case DeclRefExprClass: { - const Decl *D = cast(E)->getDecl(); + Decl const *D = cast(E)->getDecl(); - if (const VarDecl *VD = dyn_cast(D)) { + if (VarDecl const *VD = dyn_cast(D)) { if (VD->hasGlobalStorage()) return true; QualType T = VD->getType(); @@ -2867,7 +2997,7 @@ return false; } case MemberExprClass: { - const MemberExpr *M = cast(E); + MemberExpr const *M = cast(E); return M->getBase()->isOBJCGCCandidate(Ctx); } case ArraySubscriptExprClass: @@ -2881,7 +3011,7 @@ return ClassifyLValue(Ctx) == Expr::LV_MemberFunction; } -QualType Expr::findBoundMemberType(const Expr *expr) { +QualType Expr::findBoundMemberType(Expr const *expr) { assert(expr->hasPlaceholderType(BuiltinType::BoundMember)); // Bound member expressions are always one of these possibilities: @@ -2889,14 +3019,14 @@ // (possibly parenthesized) expr = expr->IgnoreParens(); - if (const MemberExpr *mem = dyn_cast(expr)) { + if (MemberExpr const *mem = dyn_cast(expr)) { assert(isa(mem->getMemberDecl())); return mem->getMemberDecl()->getType(); } - if (const BinaryOperator *op = dyn_cast(expr)) { - QualType type = op->getRHS()->getType()->castAs() - ->getPointeeType(); + if (BinaryOperator const *op = dyn_cast(expr)) { + QualType type = + op->getRHS()->getType()->castAs()->getPointeeType(); assert(type->isFunctionType()); return type; } @@ -2952,7 +3082,7 @@ IgnoreBaseCastsSingleStep); } -Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) { +Expr *Expr::IgnoreParenNoopCasts(ASTContext const &Ctx) { auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) { if (auto *CE = dyn_cast(E)) { // We ignore integer <-> casts that are of the same width, ptr<->ptr and @@ -3021,11 +3151,11 @@ } bool Expr::isDefaultArgument() const { - const Expr *E = this; - if (const MaterializeTemporaryExpr *M = dyn_cast(E)) + Expr const *E = this; + if (MaterializeTemporaryExpr const *M = dyn_cast(E)) E = M->getSubExpr(); - while (const ImplicitCastExpr *ICE = dyn_cast(E)) + while (ImplicitCastExpr const *ICE = dyn_cast(E)) E = ICE->getSubExprAsWritten(); return isa(E); @@ -3033,21 +3163,21 @@ /// Skip over any no-op casts and any temporary-binding /// expressions. -static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) { - if (const MaterializeTemporaryExpr *M = dyn_cast(E)) +static Expr const *skipTemporaryBindingsNoOpCastsAndParens(Expr const *E) { + if (MaterializeTemporaryExpr const *M = dyn_cast(E)) E = M->getSubExpr(); - while (const ImplicitCastExpr *ICE = dyn_cast(E)) { + while (ImplicitCastExpr const *ICE = dyn_cast(E)) { if (ICE->getCastKind() == CK_NoOp) E = ICE->getSubExpr(); else break; } - while (const CXXBindTemporaryExpr *BE = dyn_cast(E)) + while (CXXBindTemporaryExpr const *BE = dyn_cast(E)) E = BE->getSubExpr(); - while (const ImplicitCastExpr *ICE = dyn_cast(E)) { + while (ImplicitCastExpr const *ICE = dyn_cast(E)) { if (ICE->getCastKind() == CK_NoOp) E = ICE->getSubExpr(); else @@ -3059,11 +3189,11 @@ /// isTemporaryObject - Determines if this expression produces a /// temporary of the given class type. -bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const { +bool Expr::isTemporaryObject(ASTContext &C, CXXRecordDecl const *TempTy) const { if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy))) return false; - const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this); + Expr const *E = skipTemporaryBindingsNoOpCastsAndParens(this); // Temporaries are by definition pr-values of class type. if (!E->Classify(C).isPRValue()) { @@ -3090,7 +3220,7 @@ if (isa(E)) return false; - if (const BinaryOperator *BO = dyn_cast(E)) + if (BinaryOperator const *BO = dyn_cast(E)) if (BO->isPtrMemOp()) return false; @@ -3102,16 +3232,16 @@ } bool Expr::isImplicitCXXThis() const { - const Expr *E = this; + Expr const *E = this; // Strip away parentheses and casts we don't care about. while (true) { - if (const ParenExpr *Paren = dyn_cast(E)) { + if (ParenExpr const *Paren = dyn_cast(E)) { E = Paren->getSubExpr(); continue; } - if (const ImplicitCastExpr *ICE = dyn_cast(E)) { + if (ImplicitCastExpr const *ICE = dyn_cast(E)) { if (ICE->getCastKind() == CK_NoOp || ICE->getCastKind() == CK_LValueToRValue || ICE->getCastKind() == CK_DerivedToBase || @@ -3121,15 +3251,15 @@ } } - if (const UnaryOperator* UnOp = dyn_cast(E)) { + if (UnaryOperator const *UnOp = dyn_cast(E)) { if (UnOp->getOpcode() == UO_Extension) { E = UnOp->getSubExpr(); continue; } } - if (const MaterializeTemporaryExpr *M - = dyn_cast(E)) { + if (MaterializeTemporaryExpr const *M = + dyn_cast(E)) { E = M->getSubExpr(); continue; } @@ -3137,7 +3267,7 @@ break; } - if (const CXXThisExpr *This = dyn_cast(E)) + if (CXXThisExpr const *This = dyn_cast(E)) return This->isImplicit(); return false; @@ -3154,7 +3284,7 @@ } bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef, - const Expr **Culprit) const { + Expr const **Culprit) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -3177,7 +3307,8 @@ } switch (getStmtClass()) { - default: break; + default: + break; case Stmt::ExprWithCleanupsClass: return cast(this)->getSubExpr()->isConstantInitializer( Ctx, IsForRef, Culprit); @@ -3186,12 +3317,13 @@ return true; case CXXTemporaryObjectExprClass: case CXXConstructExprClass: { - const CXXConstructExpr *CE = cast(this); + CXXConstructExpr const *CE = cast(this); if (CE->getConstructor()->isTrivial() && CE->getConstructor()->getParent()->hasTrivialDestructor()) { // Trivial default constructor - if (!CE->getNumArgs()) return true; + if (!CE->getNumArgs()) + return true; // Trivial copy constructor assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument"); @@ -3203,23 +3335,23 @@ case ConstantExprClass: { // FIXME: We should be able to return "true" here, but it can lead to extra // error messages. E.g. in Sema/array-init.c. - const Expr *Exp = cast(this)->getSubExpr(); + Expr const *Exp = cast(this)->getSubExpr(); return Exp->isConstantInitializer(Ctx, false, Culprit); } case CompoundLiteralExprClass: { // This handles gcc's extension that allows global initializers like // "struct x {int x;} x = (struct x) {};". // FIXME: This accepts other cases it shouldn't! - const Expr *Exp = cast(this)->getInitializer(); + Expr const *Exp = cast(this)->getInitializer(); return Exp->isConstantInitializer(Ctx, false, Culprit); } case DesignatedInitUpdateExprClass: { - const DesignatedInitUpdateExpr *DIUE = cast(this); + DesignatedInitUpdateExpr const *DIUE = cast(this); return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) && DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit); } case InitListExprClass: { - const InitListExpr *ILE = cast(this); + InitListExpr const *ILE = cast(this); assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form"); if (ILE->getType()->isArrayType()) { unsigned numInits = ILE->getNumInits(); @@ -3233,8 +3365,9 @@ if (ILE->getType()->isRecordType()) { unsigned ElementNo = 0; RecordDecl *RD = ILE->getType()->castAs()->getDecl(); - for (const auto *Field : RD->fields()) { - // If this is a union, skip all the fields that aren't being initialized. + for (auto const *Field : RD->fields()) { + // If this is a union, skip all the fields that aren't being + // initialized. if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field) continue; @@ -3243,7 +3376,7 @@ continue; if (ElementNo < ILE->getNumInits()) { - const Expr *Elt = ILE->getInit(ElementNo++); + Expr const *Elt = ILE->getInit(ElementNo++); if (Field->isBitField()) { // Bitfields have to evaluate to an integer. EvalResult Result; @@ -3268,21 +3401,22 @@ case NoInitExprClass: return true; case ParenExprClass: - return cast(this)->getSubExpr() - ->isConstantInitializer(Ctx, IsForRef, Culprit); + return cast(this)->getSubExpr()->isConstantInitializer( + Ctx, IsForRef, Culprit); case GenericSelectionExprClass: - return cast(this)->getResultExpr() - ->isConstantInitializer(Ctx, IsForRef, Culprit); + return cast(this) + ->getResultExpr() + ->isConstantInitializer(Ctx, IsForRef, Culprit); case ChooseExprClass: if (cast(this)->isConditionDependent()) { if (Culprit) *Culprit = this; return false; } - return cast(this)->getChosenSubExpr() - ->isConstantInitializer(Ctx, IsForRef, Culprit); + return cast(this)->getChosenSubExpr()->isConstantInitializer( + Ctx, IsForRef, Culprit); case UnaryOperatorClass: { - const UnaryOperator* Exp = cast(this); + UnaryOperator const *Exp = cast(this); if (Exp->getOpcode() == UO_Extension) return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit); break; @@ -3296,7 +3430,7 @@ case CXXReinterpretCastExprClass: case CXXAddrspaceCastExprClass: case CXXConstCastExprClass: { - const CastExpr *CE = cast(this); + CastExpr const *CE = cast(this); // Handle misc casts we want to ignore. if (CE->getCastKind() == CK_NoOp || @@ -3316,14 +3450,15 @@ ->isConstantInitializer(Ctx, false, Culprit); case SubstNonTypeTemplateParmExprClass: - return cast(this)->getReplacement() - ->isConstantInitializer(Ctx, false, Culprit); + return cast(this) + ->getReplacement() + ->isConstantInitializer(Ctx, false, Culprit); case CXXDefaultArgExprClass: - return cast(this)->getExpr() - ->isConstantInitializer(Ctx, false, Culprit); + return cast(this)->getExpr()->isConstantInitializer( + Ctx, false, Culprit); case CXXDefaultInitExprClass: - return cast(this)->getExpr() - ->isConstantInitializer(Ctx, false, Culprit); + return cast(this)->getExpr()->isConstantInitializer( + Ctx, false, Culprit); } // Allow certain forms of UB in constant initializers: signed integer // overflow and floating-point division by zero. We'll give a warning on @@ -3335,61 +3470,60 @@ return false; } -bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const { - const FunctionDecl* FD = getDirectCallee(); +bool CallExpr::isBuiltinAssumeFalse(ASTContext const &Ctx) const { + FunctionDecl const *FD = getDirectCallee(); if (!FD || (FD->getBuiltinID() != Builtin::BI__assume && FD->getBuiltinID() != Builtin::BI__builtin_assume)) return false; - const Expr* Arg = getArg(0); + Expr const *Arg = getArg(0); bool ArgVal; return !Arg->isValueDependent() && Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal; } namespace { - /// Look for any side effects within a Stmt. - class SideEffectFinder : public ConstEvaluatedExprVisitor { - typedef ConstEvaluatedExprVisitor Inherited; - const bool IncludePossibleEffects; - bool HasSideEffects; - - public: - explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible) - : Inherited(Context), - IncludePossibleEffects(IncludePossible), HasSideEffects(false) { } - - bool hasSideEffects() const { return HasSideEffects; } - - void VisitDecl(const Decl *D) { - if (!D) - return; - - // We assume the caller checks subexpressions (eg, the initializer, VLA - // bounds) for side-effects on our behalf. - if (auto *VD = dyn_cast(D)) { - // Registering a destructor is a side-effect. - if (IncludePossibleEffects && VD->isThisDeclarationADefinition() && - VD->needsDestruction(Context)) - HasSideEffects = true; - } +/// Look for any side effects within a Stmt. +class SideEffectFinder : public ConstEvaluatedExprVisitor { + typedef ConstEvaluatedExprVisitor Inherited; + bool const IncludePossibleEffects; + bool HasSideEffects; + +public: + explicit SideEffectFinder(ASTContext const &Context, bool IncludePossible) + : Inherited(Context), IncludePossibleEffects(IncludePossible), + HasSideEffects(false) {} + + bool hasSideEffects() const { return HasSideEffects; } + + void VisitDecl(Decl const *D) { + if (!D) + return; + + // We assume the caller checks subexpressions (eg, the initializer, VLA + // bounds) for side-effects on our behalf. + if (auto *VD = dyn_cast(D)) { + // Registering a destructor is a side-effect. + if (IncludePossibleEffects && VD->isThisDeclarationADefinition() && + VD->needsDestruction(Context)) + HasSideEffects = true; } + } - void VisitDeclStmt(const DeclStmt *DS) { - for (auto *D : DS->decls()) - VisitDecl(D); - Inherited::VisitDeclStmt(DS); - } + void VisitDeclStmt(DeclStmt const *DS) { + for (auto *D : DS->decls()) + VisitDecl(D); + Inherited::VisitDeclStmt(DS); + } - void VisitExpr(const Expr *E) { - if (!HasSideEffects && - E->HasSideEffects(Context, IncludePossibleEffects)) - HasSideEffects = true; - } - }; -} + void VisitExpr(Expr const *E) { + if (!HasSideEffects && E->HasSideEffects(Context, IncludePossibleEffects)) + HasSideEffects = true; + } +}; +} // namespace -bool Expr::HasSideEffects(const ASTContext &Ctx, +bool Expr::HasSideEffects(ASTContext const &Ctx, bool IncludePossibleEffects) const { // In circumstances where we care about definite side effects instead of // potential side effects, we want to ignore expressions that are part of a @@ -3399,10 +3533,10 @@ switch (getStmtClass()) { case NoStmtClass: - #define ABSTRACT_STMT(Type) - #define STMT(Type, Base) case Type##Class: - #define EXPR(Type, Base) - #include "clang/AST/StmtNodes.inc" +#define ABSTRACT_STMT(Type) +#define STMT(Type, Base) case Type##Class: +#define EXPR(Type, Base) +#include "clang/AST/StmtNodes.inc" llvm_unreachable("unexpected Expr kind"); case DependentScopeDeclRefExprClass: @@ -3470,7 +3604,7 @@ // We don't know a call definitely has side effects, except for calls // to pure/const functions that definitely don't. // If the call itself is considered side-effect free, check the operands. - const Decl *FD = cast(this)->getCalleeDecl(); + Decl const *FD = cast(this)->getCalleeDecl(); bool IsPure = FD && (FD->hasAttr() || FD->hasAttr()); if (IsPure || !IncludePossibleEffects) break; @@ -3548,14 +3682,14 @@ case InitListExprClass: // FIXME: The children for an InitListExpr doesn't include the array filler. - if (const Expr *E = cast(this)->getArrayFiller()) + if (Expr const *E = cast(this)->getArrayFiller()) if (E->HasSideEffects(Ctx, IncludePossibleEffects)) return true; break; case GenericSelectionExprClass: - return cast(this)->getResultExpr()-> - HasSideEffects(Ctx, IncludePossibleEffects); + return cast(this)->getResultExpr()->HasSideEffects( + Ctx, IncludePossibleEffects); case ChooseExprClass: return cast(this)->getChosenSubExpr()->HasSideEffects( @@ -3566,8 +3700,8 @@ Ctx, IncludePossibleEffects); case CXXDefaultInitExprClass: { - const FieldDecl *FD = cast(this)->getField(); - if (const Expr *E = FD->getInClassInitializer()) + FieldDecl const *FD = cast(this)->getField(); + if (Expr const *E = FD->getInClassInitializer()) return E->HasSideEffects(Ctx, IncludePossibleEffects); // If we've not yet parsed the initializer, assume it has side-effects. return true; @@ -3575,11 +3709,11 @@ case CXXDynamicCastExprClass: { // A dynamic_cast expression has side-effects if it can throw. - const CXXDynamicCastExpr *DCE = cast(this); + CXXDynamicCastExpr const *DCE = cast(this); if (DCE->getTypeAsWritten()->isReferenceType() && DCE->getCastKind() == CK_Dynamic) return true; - } + } LLVM_FALLTHROUGH; case ImplicitCastExprClass: case CStyleCastExprClass: @@ -3596,7 +3730,7 @@ if (!IncludePossibleEffects) break; - const CastExpr *CE = cast(this); + CastExpr const *CE = cast(this); if (CE->getCastKind() == CK_LValueToRValue && CE->getSubExpr()->getType().isVolatileQualified()) return true; @@ -3610,7 +3744,7 @@ case CXXConstructExprClass: case CXXTemporaryObjectExprClass: { - const CXXConstructExpr *CE = cast(this); + CXXConstructExpr const *CE = cast(this); if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects) return true; // A trivial constructor does not add any side-effects of its own. Just look @@ -3619,14 +3753,14 @@ } case CXXInheritedCtorInitExprClass: { - const auto *ICIE = cast(this); + auto const *ICIE = cast(this); if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects) return true; break; } case LambdaExprClass: { - const LambdaExpr *LE = cast(this); + LambdaExpr const *LE = cast(this); for (Expr *E : LE->capture_inits()) if (E && E->HasSideEffects(Ctx, IncludePossibleEffects)) return true; @@ -3636,12 +3770,12 @@ case PseudoObjectExprClass: { // Only look for side-effects in the semantic form, and look past // OpaqueValueExpr bindings in that form. - const PseudoObjectExpr *PO = cast(this); + PseudoObjectExpr const *PO = cast(this); for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(), E = PO->semantics_end(); I != E; ++I) { - const Expr *Subexpr = *I; - if (const OpaqueValueExpr *OVE = dyn_cast(Subexpr)) + Expr const *Subexpr = *I; + if (OpaqueValueExpr const *OVE = dyn_cast(Subexpr)) Subexpr = OVE->getSourceExpr(); if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects)) return true; @@ -3660,14 +3794,14 @@ case ObjCBridgedCastExprClass: case ObjCMessageExprClass: case ObjCPropertyRefExprClass: - // FIXME: Classify these cases better. + // FIXME: Classify these cases better. if (IncludePossibleEffects) return true; break; } // Recurse to children. - for (const Stmt *SubStmt : children()) + for (Stmt const *SubStmt : children()) if (SubStmt && cast(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects)) return true; @@ -3675,7 +3809,7 @@ return false; } -FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const { +FPOptions Expr::getFPFeaturesInEffect(LangOptions const &LO) const { if (auto Call = dyn_cast(this)) return Call->getFPFeaturesInEffect(LO); if (auto UO = dyn_cast(this)) @@ -3688,54 +3822,54 @@ } namespace { - /// Look for a call to a non-trivial function within an expression. - class NonTrivialCallFinder : public ConstEvaluatedExprVisitor - { - typedef ConstEvaluatedExprVisitor Inherited; - - bool NonTrivial; - - public: - explicit NonTrivialCallFinder(const ASTContext &Context) - : Inherited(Context), NonTrivial(false) { } - - bool hasNonTrivialCall() const { return NonTrivial; } - - void VisitCallExpr(const CallExpr *E) { - if (const CXXMethodDecl *Method - = dyn_cast_or_null(E->getCalleeDecl())) { - if (Method->isTrivial()) { - // Recurse to children of the call. - Inherited::VisitStmt(E); - return; - } - } +/// Look for a call to a non-trivial function within an expression. +class NonTrivialCallFinder + : public ConstEvaluatedExprVisitor { + typedef ConstEvaluatedExprVisitor Inherited; - NonTrivial = true; - } + bool NonTrivial; + +public: + explicit NonTrivialCallFinder(ASTContext const &Context) + : Inherited(Context), NonTrivial(false) {} + + bool hasNonTrivialCall() const { return NonTrivial; } - void VisitCXXConstructExpr(const CXXConstructExpr *E) { - if (E->getConstructor()->isTrivial()) { + void VisitCallExpr(CallExpr const *E) { + if (CXXMethodDecl const *Method = + dyn_cast_or_null(E->getCalleeDecl())) { + if (Method->isTrivial()) { // Recurse to children of the call. Inherited::VisitStmt(E); return; } + } + + NonTrivial = true; + } - NonTrivial = true; + void VisitCXXConstructExpr(CXXConstructExpr const *E) { + if (E->getConstructor()->isTrivial()) { + // Recurse to children of the call. + Inherited::VisitStmt(E); + return; } - void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { - if (E->getTemporary()->getDestructor()->isTrivial()) { - Inherited::VisitStmt(E); - return; - } + NonTrivial = true; + } - NonTrivial = true; + void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr const *E) { + if (E->getTemporary()->getDestructor()->isTrivial()) { + Inherited::VisitStmt(E); + return; } - }; -} -bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const { + NonTrivial = true; + } +}; +} // namespace + +bool Expr::hasNonTrivialCall(ASTContext const &Ctx) const { NonTrivialCallFinder Finder(Ctx); Finder.Visit(this); return Finder.hasNonTrivialCall(); @@ -3769,10 +3903,10 @@ } // Strip off a cast to void*, if it exists. Except in C++. - if (const ExplicitCastExpr *CE = dyn_cast(this)) { + if (ExplicitCastExpr const *CE = dyn_cast(this)) { if (!Ctx.getLangOpts().CPlusPlus) { // Check that it is a cast to void*. - if (const PointerType *PT = CE->getType()->getAs()) { + if (PointerType const *PT = CE->getType()->getAs()) { QualType Pointee = PT->getPointeeType(); Qualifiers Qs = Pointee.getQualifiers(); // Only (void*)0 or equivalent are treated as nullptr. If pointee type @@ -3786,43 +3920,43 @@ Pointee.getAddressSpace() == LangAS::opencl_private)) Qs.removeAddressSpace(); - if (Pointee->isVoidType() && Qs.empty() && // to void* + if (Pointee->isVoidType() && Qs.empty() && // to void* CE->getSubExpr()->getType()->isIntegerType()) // from int return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC); } } - } else if (const ImplicitCastExpr *ICE = dyn_cast(this)) { + } else if (ImplicitCastExpr const *ICE = dyn_cast(this)) { // Ignore the ImplicitCastExpr type entirely. return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC); - } else if (const ParenExpr *PE = dyn_cast(this)) { + } else if (ParenExpr const *PE = dyn_cast(this)) { // Accept ((void*)0) as a null pointer constant, as many other // implementations do. return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC); - } else if (const GenericSelectionExpr *GE = - dyn_cast(this)) { + } else if (GenericSelectionExpr const *GE = + dyn_cast(this)) { if (GE->isResultDependent()) return NPCK_NotNull; return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC); - } else if (const ChooseExpr *CE = dyn_cast(this)) { + } else if (ChooseExpr const *CE = dyn_cast(this)) { if (CE->isConditionDependent()) return NPCK_NotNull; return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC); - } else if (const CXXDefaultArgExpr *DefaultArg - = dyn_cast(this)) { + } else if (CXXDefaultArgExpr const *DefaultArg = + dyn_cast(this)) { // See through default argument expressions. return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC); - } else if (const CXXDefaultInitExpr *DefaultInit - = dyn_cast(this)) { + } else if (CXXDefaultInitExpr const *DefaultInit = + dyn_cast(this)) { // See through default initializer expressions. return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC); } else if (isa(this)) { // The GNU __null extension is always a null pointer constant. return NPCK_GNUNull; - } else if (const MaterializeTemporaryExpr *M - = dyn_cast(this)) { + } else if (MaterializeTemporaryExpr const *M = + dyn_cast(this)) { return M->getSubExpr()->isNullPointerConstant(Ctx, NPC); - } else if (const OpaqueValueExpr *OVE = dyn_cast(this)) { - if (const Expr *Source = OVE->getSourceExpr()) + } else if (OpaqueValueExpr const *OVE = dyn_cast(this)) { + if (Expr const *Source = OVE->getSourceExpr()) return Source->isNullPointerConstant(Ctx, NPC); } @@ -3835,12 +3969,13 @@ if (getType()->isNullPtrType()) return NPCK_CXX11_nullptr; - if (const RecordType *UT = getType()->getAsUnionType()) - if (!Ctx.getLangOpts().CPlusPlus11 && - UT && UT->getDecl()->hasAttr()) - if (const CompoundLiteralExpr *CLE = dyn_cast(this)){ - const Expr *InitExpr = CLE->getInitializer(); - if (const InitListExpr *ILE = dyn_cast(InitExpr)) + if (RecordType const *UT = getType()->getAsUnionType()) + if (!Ctx.getLangOpts().CPlusPlus11 && UT && + UT->getDecl()->hasAttr()) + if (CompoundLiteralExpr const *CLE = + dyn_cast(this)) { + Expr const *InitExpr = CLE->getInitializer(); + if (InitListExpr const *ILE = dyn_cast(InitExpr)) return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC); } // This expression must be an integer type. @@ -3852,7 +3987,7 @@ // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with // value zero or a prvalue of type std::nullptr_t. // Microsoft mode permits C++98 rules reflecting MSVC behavior. - const IntegerLiteral *Lit = dyn_cast(this); + IntegerLiteral const *Lit = dyn_cast(this); if (Lit && !Lit->getValue()) return NPCK_ZeroLiteral; if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx)) @@ -3874,13 +4009,13 @@ /// If this expression is an l-value for an Objective C /// property, find the underlying property reference expression. -const ObjCPropertyRefExpr *Expr::getObjCProperty() const { - const Expr *E = this; +ObjCPropertyRefExpr const *Expr::getObjCProperty() const { + Expr const *E = this; while (true) { assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) && "expression is not a property reference"); E = E->IgnoreParenCasts(); - if (const BinaryOperator *BO = dyn_cast(E)) { + if (BinaryOperator const *BO = dyn_cast(E)) { if (BO->getOpcode() == BO_Comma) { E = BO->getRHS(); continue; @@ -3894,17 +4029,17 @@ } bool Expr::isObjCSelfExpr() const { - const Expr *E = IgnoreParenImpCasts(); + Expr const *E = IgnoreParenImpCasts(); - const DeclRefExpr *DRE = dyn_cast(E); + DeclRefExpr const *DRE = dyn_cast(E); if (!DRE) return false; - const ImplicitParamDecl *Param = dyn_cast(DRE->getDecl()); + ImplicitParamDecl const *Param = dyn_cast(DRE->getDecl()); if (!Param) return false; - const ObjCMethodDecl *M = dyn_cast(Param->getDeclContext()); + ObjCMethodDecl const *M = dyn_cast(Param->getDeclContext()); if (!M) return false; @@ -3960,16 +4095,16 @@ bool Expr::refersToVectorElement() const { // FIXME: Why do we not just look at the ObjectKind here? - const Expr *E = this->IgnoreParens(); + Expr const *E = this->IgnoreParens(); - while (const ImplicitCastExpr *ICE = dyn_cast(E)) { + while (ImplicitCastExpr const *ICE = dyn_cast(E)) { if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp) E = ICE->getSubExpr()->IgnoreParens(); else break; } - if (const ArraySubscriptExpr *ASE = dyn_cast(E)) + if (ArraySubscriptExpr const *ASE = dyn_cast(E)) return ASE->getBase()->getType()->isVectorType(); if (isa(E)) @@ -3984,18 +4119,18 @@ } bool Expr::refersToGlobalRegisterVar() const { - const Expr *E = this->IgnoreParenImpCasts(); + Expr const *E = this->IgnoreParenImpCasts(); - if (const DeclRefExpr *DRE = dyn_cast(E)) - if (const auto *VD = dyn_cast(DRE->getDecl())) - if (VD->getStorageClass() == SC_Register && - VD->hasAttr() && !VD->isLocalVarDecl()) + if (DeclRefExpr const *DRE = dyn_cast(E)) + if (auto const *VD = dyn_cast(DRE->getDecl())) + if (VD->getStorageClass() == SC_Register && VD->hasAttr() && + !VD->isLocalVarDecl()) return true; return false; } -bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) { +bool Expr::isSameComparisonOperand(Expr const *E1, Expr const *E2) { E1 = E1->IgnoreParens(); E2 = E2->IgnoreParens(); @@ -4003,101 +4138,101 @@ return false; switch (E1->getStmtClass()) { - default: - return false; - case CXXThisExprClass: - return true; - case DeclRefExprClass: { - // DeclRefExpr without an ImplicitCastExpr can happen for integral - // template parameters. - const auto *DRE1 = cast(E1); - const auto *DRE2 = cast(E2); - return DRE1->isPRValue() && DRE2->isPRValue() && - DRE1->getDecl() == DRE2->getDecl(); - } - case ImplicitCastExprClass: { - // Peel off implicit casts. - while (true) { - const auto *ICE1 = dyn_cast(E1); - const auto *ICE2 = dyn_cast(E2); - if (!ICE1 || !ICE2) - return false; - if (ICE1->getCastKind() != ICE2->getCastKind()) - return false; - E1 = ICE1->getSubExpr()->IgnoreParens(); - E2 = ICE2->getSubExpr()->IgnoreParens(); - // The final cast must be one of these types. - if (ICE1->getCastKind() == CK_LValueToRValue || - ICE1->getCastKind() == CK_ArrayToPointerDecay || - ICE1->getCastKind() == CK_FunctionToPointerDecay) { - break; - } - } - - const auto *DRE1 = dyn_cast(E1); - const auto *DRE2 = dyn_cast(E2); - if (DRE1 && DRE2) - return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl()); - - const auto *Ivar1 = dyn_cast(E1); - const auto *Ivar2 = dyn_cast(E2); - if (Ivar1 && Ivar2) { - return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() && - declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl()); + default: + return false; + case CXXThisExprClass: + return true; + case DeclRefExprClass: { + // DeclRefExpr without an ImplicitCastExpr can happen for integral + // template parameters. + auto const *DRE1 = cast(E1); + auto const *DRE2 = cast(E2); + return DRE1->isPRValue() && DRE2->isPRValue() && + DRE1->getDecl() == DRE2->getDecl(); + } + case ImplicitCastExprClass: { + // Peel off implicit casts. + while (true) { + auto const *ICE1 = dyn_cast(E1); + auto const *ICE2 = dyn_cast(E2); + if (!ICE1 || !ICE2) + return false; + if (ICE1->getCastKind() != ICE2->getCastKind()) + return false; + E1 = ICE1->getSubExpr()->IgnoreParens(); + E2 = ICE2->getSubExpr()->IgnoreParens(); + // The final cast must be one of these types. + if (ICE1->getCastKind() == CK_LValueToRValue || + ICE1->getCastKind() == CK_ArrayToPointerDecay || + ICE1->getCastKind() == CK_FunctionToPointerDecay) { + break; } + } - const auto *Array1 = dyn_cast(E1); - const auto *Array2 = dyn_cast(E2); - if (Array1 && Array2) { - if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase())) - return false; + auto const *DRE1 = dyn_cast(E1); + auto const *DRE2 = dyn_cast(E2); + if (DRE1 && DRE2) + return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl()); - auto Idx1 = Array1->getIdx(); - auto Idx2 = Array2->getIdx(); - const auto Integer1 = dyn_cast(Idx1); - const auto Integer2 = dyn_cast(Idx2); - if (Integer1 && Integer2) { - if (!llvm::APInt::isSameValue(Integer1->getValue(), - Integer2->getValue())) - return false; - } else { - if (!isSameComparisonOperand(Idx1, Idx2)) - return false; - } + auto const *Ivar1 = dyn_cast(E1); + auto const *Ivar2 = dyn_cast(E2); + if (Ivar1 && Ivar2) { + return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() && + declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl()); + } - return true; - } + auto const *Array1 = dyn_cast(E1); + auto const *Array2 = dyn_cast(E2); + if (Array1 && Array2) { + if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase())) + return false; - // Walk the MemberExpr chain. - while (isa(E1) && isa(E2)) { - const auto *ME1 = cast(E1); - const auto *ME2 = cast(E2); - if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl())) + auto Idx1 = Array1->getIdx(); + auto Idx2 = Array2->getIdx(); + auto const Integer1 = dyn_cast(Idx1); + auto const Integer2 = dyn_cast(Idx2); + if (Integer1 && Integer2) { + if (!llvm::APInt::isSameValue(Integer1->getValue(), + Integer2->getValue())) + return false; + } else { + if (!isSameComparisonOperand(Idx1, Idx2)) return false; - if (const auto *D = dyn_cast(ME1->getMemberDecl())) - if (D->isStaticDataMember()) - return true; - E1 = ME1->getBase()->IgnoreParenImpCasts(); - E2 = ME2->getBase()->IgnoreParenImpCasts(); } - if (isa(E1) && isa(E2)) - return true; + return true; + } - // A static member variable can end the MemberExpr chain with either - // a MemberExpr or a DeclRefExpr. - auto getAnyDecl = [](const Expr *E) -> const ValueDecl * { - if (const auto *DRE = dyn_cast(E)) - return DRE->getDecl(); - if (const auto *ME = dyn_cast(E)) - return ME->getMemberDecl(); - return nullptr; - }; - - const ValueDecl *VD1 = getAnyDecl(E1); - const ValueDecl *VD2 = getAnyDecl(E2); - return declaresSameEntity(VD1, VD2); + // Walk the MemberExpr chain. + while (isa(E1) && isa(E2)) { + auto const *ME1 = cast(E1); + auto const *ME2 = cast(E2); + if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl())) + return false; + if (auto const *D = dyn_cast(ME1->getMemberDecl())) + if (D->isStaticDataMember()) + return true; + E1 = ME1->getBase()->IgnoreParenImpCasts(); + E2 = ME2->getBase()->IgnoreParenImpCasts(); } + + if (isa(E1) && isa(E2)) + return true; + + // A static member variable can end the MemberExpr chain with either + // a MemberExpr or a DeclRefExpr. + auto getAnyDecl = [](Expr const *E) -> ValueDecl const * { + if (const auto *DRE = dyn_cast(E)) + return DRE->getDecl(); + if (const auto *ME = dyn_cast(E)) + return ME->getMemberDecl(); + return nullptr; + }; + + ValueDecl const *VD1 = getAnyDecl(E1); + ValueDecl const *VD2 = getAnyDecl(E2); + return declaresSameEntity(VD1, VD2); + } } } @@ -4108,7 +4243,7 @@ } unsigned ExtVectorElementExpr::getNumElements() const { - if (const VectorType *VT = getType()->getAs()) + if (VectorType const *VT = getType()->getAs()) return VT->getNumElements(); return 1; } @@ -4129,7 +4264,7 @@ for (unsigned i = 0, e = Comp.size(); i != e; ++i) if (Comp.substr(i + 1).find(Comp[i]) != StringRef::npos) - return true; + return true; return false; } @@ -4144,10 +4279,10 @@ isNumericAccessor = true; } - bool isHi = Comp == "hi"; - bool isLo = Comp == "lo"; + bool isHi = Comp == "hi"; + bool isLo = Comp == "lo"; bool isEven = Comp == "even"; - bool isOdd = Comp == "odd"; + bool isOdd = Comp == "odd"; for (unsigned i = 0, e = getNumElements(); i != e; ++i) { uint64_t Index; @@ -4167,28 +4302,29 @@ } } -ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef args, +ShuffleVectorExpr::ShuffleVectorExpr(ASTContext const &C, ArrayRef args, QualType Type, SourceLocation BLoc, SourceLocation RP) : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary), BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) { - SubExprs = new (C) Stmt*[args.size()]; + SubExprs = new (C) Stmt *[args.size()]; for (unsigned i = 0; i != args.size(); i++) SubExprs[i] = args[i]; setDependence(computeDependence(this)); } -void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef Exprs) { - if (SubExprs) C.Deallocate(SubExprs); +void ShuffleVectorExpr::setExprs(ASTContext const &C, ArrayRef Exprs) { + if (SubExprs) + C.Deallocate(SubExprs); this->NumExprs = Exprs.size(); - SubExprs = new (C) Stmt*[NumExprs]; + SubExprs = new (C) Stmt *[NumExprs]; memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size()); } GenericSelectionExpr::GenericSelectionExpr( - const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr, + ASTContext const &, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef AssocTypes, ArrayRef AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex) @@ -4213,7 +4349,7 @@ } GenericSelectionExpr::GenericSelectionExpr( - const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, + ASTContext const &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef AssocTypes, ArrayRef AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) @@ -4239,7 +4375,7 @@ : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {} GenericSelectionExpr *GenericSelectionExpr::Create( - const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, + ASTContext const &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef AssocTypes, ArrayRef AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex) { @@ -4253,7 +4389,7 @@ } GenericSelectionExpr *GenericSelectionExpr::Create( - const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, + ASTContext const &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef AssocTypes, ArrayRef AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) { @@ -4267,7 +4403,7 @@ } GenericSelectionExpr * -GenericSelectionExpr::CreateEmpty(const ASTContext &Context, +GenericSelectionExpr::CreateEmpty(ASTContext const &Context, unsigned NumAssocs) { void *Mem = Context.Allocate( totalSizeToAlloc(1 + NumAssocs, NumAssocs), @@ -4286,7 +4422,7 @@ return getField()->getIdentifier(); } -DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty, +DesignatedInitExpr::DesignatedInitExpr(ASTContext const &C, QualType Ty, llvm::ArrayRef Designators, SourceLocation EqualOrColonLoc, bool GNUSyntax, @@ -4320,28 +4456,25 @@ setDependence(computeDependence(this)); } -DesignatedInitExpr * -DesignatedInitExpr::Create(const ASTContext &C, - llvm::ArrayRef Designators, - ArrayRef IndexExprs, - SourceLocation ColonOrEqualLoc, - bool UsesColonSyntax, Expr *Init) { +DesignatedInitExpr *DesignatedInitExpr::Create( + ASTContext const &C, llvm::ArrayRef Designators, + ArrayRef IndexExprs, SourceLocation ColonOrEqualLoc, + bool UsesColonSyntax, Expr *Init) { void *Mem = C.Allocate(totalSizeToAlloc(IndexExprs.size() + 1), alignof(DesignatedInitExpr)); - return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators, - ColonOrEqualLoc, UsesColonSyntax, - IndexExprs, Init); + return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators, ColonOrEqualLoc, + UsesColonSyntax, IndexExprs, Init); } -DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C, +DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(ASTContext const &C, unsigned NumIndexExprs) { void *Mem = C.Allocate(totalSizeToAlloc(NumIndexExprs + 1), alignof(DesignatedInitExpr)); return new (Mem) DesignatedInitExpr(NumIndexExprs + 1); } -void DesignatedInitExpr::setDesignators(const ASTContext &C, - const Designator *Desigs, +void DesignatedInitExpr::setDesignators(ASTContext const &C, + Designator const *Desigs, unsigned NumDesigs) { Designators = new (C) Designator[NumDesigs]; NumDesignators = NumDesigs; @@ -4350,7 +4483,7 @@ } SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const { - DesignatedInitExpr *DIE = const_cast(this); + DesignatedInitExpr *DIE = const_cast(this); if (size() == 1) return DIE->getDesignator(0)->getSourceRange(); return SourceRange(DIE->getDesignator(0)->getBeginLoc(), @@ -4372,18 +4505,18 @@ return getInit()->getEndLoc(); } -Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const { +Expr *DesignatedInitExpr::getArrayIndex(Designator const &D) const { assert(D.Kind == Designator::ArrayDesignator && "Requires array designator"); return getSubExpr(D.ArrayOrRange.Index + 1); } -Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const { +Expr *DesignatedInitExpr::getArrayRangeStart(Designator const &D) const { assert(D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"); return getSubExpr(D.ArrayOrRange.Index + 1); } -Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const { +Expr *DesignatedInitExpr::getArrayRangeEnd(Designator const &D) const { assert(D.Kind == Designator::ArrayRangeDesignator && "Requires array range designator"); return getSubExpr(D.ArrayOrRange.Index + 2); @@ -4391,13 +4524,12 @@ /// Replaces the designator at index @p Idx with the series /// of designators in [First, Last). -void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx, - const Designator *First, - const Designator *Last) { +void DesignatedInitExpr::ExpandDesignator(ASTContext const &C, unsigned Idx, + Designator const *First, + Designator const *Last) { unsigned NumNewDesignators = Last - First; if (NumNewDesignators == 0) { - std::copy_backward(Designators + Idx + 1, - Designators + NumDesignators, + std::copy_backward(Designators + Idx + 1, Designators + NumDesignators, Designators + Idx); --NumNewDesignators; return; @@ -4407,8 +4539,8 @@ return; } - Designator *NewDesignators - = new (C) Designator[NumDesignators - 1 + NumNewDesignators]; + Designator *NewDesignators = + new (C) Designator[NumDesignators - 1 + NumNewDesignators]; std::copy(Designators, Designators + Idx, NewDesignators); std::copy(First, Last, NewDesignators + Idx); std::copy(Designators + Idx + 1, Designators + NumDesignators, @@ -4417,7 +4549,7 @@ NumDesignators = NumDesignators - 1 + NumNewDesignators; } -DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C, +DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(ASTContext const &C, SourceLocation lBraceLoc, Expr *baseExpr, SourceLocation rBraceLoc) @@ -4457,7 +4589,7 @@ ParenListExprBits.NumExprs = NumExprs; } -ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx, +ParenListExpr *ParenListExpr::Create(ASTContext const &Ctx, SourceLocation LParenLoc, ArrayRef Exprs, SourceLocation RParenLoc) { @@ -4466,14 +4598,14 @@ return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc); } -ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx, +ParenListExpr *ParenListExpr::CreateEmpty(ASTContext const &Ctx, unsigned NumExprs) { void *Mem = Ctx.Allocate(totalSizeToAlloc(NumExprs), alignof(ParenListExpr)); return new (Mem) ParenListExpr(EmptyShell(), NumExprs); } -BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, +BinaryOperator::BinaryOperator(ASTContext const &Ctx, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures) @@ -4490,7 +4622,7 @@ setDependence(computeDependence(this)); } -BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, +BinaryOperator::BinaryOperator(ASTContext const &Ctx, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, bool dead2) @@ -4507,7 +4639,7 @@ setDependence(computeDependence(this)); } -BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C, +BinaryOperator *BinaryOperator::CreateEmpty(ASTContext const &C, bool HasFPFeatures) { unsigned Extra = sizeOfTrailingObjects(HasFPFeatures); void *Mem = @@ -4515,7 +4647,7 @@ return new (Mem) BinaryOperator(EmptyShell()); } -BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs, +BinaryOperator *BinaryOperator::Create(ASTContext const &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, @@ -4529,7 +4661,7 @@ } CompoundAssignOperator * -CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) { +CompoundAssignOperator::CreateEmpty(ASTContext const &C, bool HasFPFeatures) { unsigned Extra = sizeOfTrailingObjects(HasFPFeatures); void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra, alignof(CompoundAssignOperator)); @@ -4537,7 +4669,7 @@ } CompoundAssignOperator * -CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs, +CompoundAssignOperator::Create(ASTContext const &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, @@ -4551,14 +4683,14 @@ CompLHSType, CompResultType); } -UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C, +UnaryOperator *UnaryOperator::CreateEmpty(ASTContext const &C, bool hasFPFeatures) { void *Mem = C.Allocate(totalSizeToAlloc(hasFPFeatures), alignof(UnaryOperator)); return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell()); } -UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, +UnaryOperator::UnaryOperator(ASTContext const &Ctx, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures) @@ -4572,7 +4704,7 @@ setDependence(computeDependence(this, Ctx)); } -UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input, +UnaryOperator *UnaryOperator::Create(ASTContext const &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, @@ -4584,33 +4716,33 @@ UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures); } -const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) { - if (const ExprWithCleanups *ewc = dyn_cast(e)) +OpaqueValueExpr const *OpaqueValueExpr::findInCopyConstruct(Expr const *e) { + if (ExprWithCleanups const *ewc = dyn_cast(e)) e = ewc->getSubExpr(); - if (const MaterializeTemporaryExpr *m = dyn_cast(e)) + if (MaterializeTemporaryExpr const *m = dyn_cast(e)) e = m->getSubExpr(); e = cast(e)->getArg(0); - while (const ImplicitCastExpr *ice = dyn_cast(e)) + while (ImplicitCastExpr const *ice = dyn_cast(e)) e = ice->getSubExpr(); return cast(e); } -PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context, +PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext const &Context, EmptyShell sh, unsigned numSemanticExprs) { void *buffer = Context.Allocate(totalSizeToAlloc(1 + numSemanticExprs), alignof(PseudoObjectExpr)); - return new(buffer) PseudoObjectExpr(sh, numSemanticExprs); + return new (buffer) PseudoObjectExpr(sh, numSemanticExprs); } PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs) - : Expr(PseudoObjectExprClass, shell) { + : Expr(PseudoObjectExprClass, shell) { PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1; } -PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax, - ArrayRef semantics, +PseudoObjectExpr *PseudoObjectExpr::Create(ASTContext const &C, Expr *syntax, + ArrayRef semantics, unsigned resultIndex) { assert(syntax && "no syntactic expression!"); assert(semantics.size() && "no semantic expressions!"); @@ -4629,8 +4761,8 @@ void *buffer = C.Allocate(totalSizeToAlloc(semantics.size() + 1), alignof(PseudoObjectExpr)); - return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics, - resultIndex); + return new (buffer) + PseudoObjectExpr(type, VK, syntax, semantics, resultIndex); } PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK, @@ -4641,7 +4773,7 @@ PseudoObjectExprBits.ResultIndex = resultIndex + 1; for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) { - Expr *E = (i == 0 ? syntax : semantics[i-1]); + Expr *E = (i == 0 ? syntax : semantics[i - 1]); getSubExprsBuffer()[i] = E; if (isa(E)) @@ -4660,7 +4792,7 @@ // UnaryExprOrTypeTraitExpr Stmt::child_range UnaryExprOrTypeTraitExpr::children() { const_child_range CCR = - const_cast(this)->children(); + const_cast(this)->children(); return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end())); } @@ -4669,7 +4801,7 @@ // size expression of the VLA needs to be treated as an executable expression. // Why isn't this weirdness documented better in StmtIterator? if (isArgumentType()) { - if (const VariableArrayType *T = + if (VariableArrayType const *T = dyn_cast(getArgumentType().getTypePtr())) return const_child_range(const_child_iterator(T), const_child_iterator()); return const_child_range(const_child_iterator(), const_child_iterator()); @@ -4759,7 +4891,7 @@ return T; } -QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) { +QualType OMPArraySectionExpr::getBaseOriginalType(Expr const *Base) { unsigned ArraySectionCount = 0; while (auto *OASE = dyn_cast(Base->IgnoreParens())) { Base = OASE->getBase(); @@ -4780,7 +4912,7 @@ if (OriginalTy->isAnyPointerType()) OriginalTy = OriginalTy->getPointeeType(); else { - assert (OriginalTy->isArrayType()); + assert(OriginalTy->isArrayType()); OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType(); } } @@ -4794,7 +4926,7 @@ OK_Ordinary), BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) { assert(!T.isNull()); - assert(llvm::all_of(SubExprs, [](Expr* E) { return E != nullptr; })); + assert(llvm::all_of(SubExprs, [](Expr *E) { return E != nullptr; })); llvm::copy(SubExprs, getTrailingObjects()); setDependence(computeDependence(this)); @@ -4840,7 +4972,7 @@ } OMPArrayShapingExpr * -OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op, +OMPArrayShapingExpr::Create(ASTContext const &Context, QualType T, Expr *Op, SourceLocation L, SourceLocation R, ArrayRef Dims, ArrayRef BracketRanges) { @@ -4854,7 +4986,7 @@ return E; } -OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context, +OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(ASTContext const &Context, unsigned NumDims) { void *Mem = Context.Allocate( totalSizeToAlloc(NumDims + 1, NumDims), @@ -4938,7 +5070,7 @@ static_cast(RangeLocOffset::SecondColonLoc)]; } -void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) { +void OMPIteratorExpr::setHelper(unsigned I, OMPIteratorHelperData const &D) { getTrailingObjects()[I] = D; } @@ -4946,7 +5078,7 @@ return getTrailingObjects()[I]; } -const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const { +OMPIteratorHelperData const &OMPIteratorExpr::getHelper(unsigned I) const { return getTrailingObjects()[I]; } @@ -4958,7 +5090,7 @@ IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R), NumIterators(Data.size()) { for (unsigned I = 0, E = Data.size(); I < E; ++I) { - const IteratorDefinition &D = Data[I]; + IteratorDefinition const &D = Data[I]; setIteratorDeclaration(I, D.IteratorDecl); setAssignmentLoc(I, D.AssignmentLoc); setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End, @@ -4969,7 +5101,7 @@ } OMPIteratorExpr * -OMPIteratorExpr::Create(const ASTContext &Context, QualType T, +OMPIteratorExpr::Create(ASTContext const &Context, QualType T, SourceLocation IteratorKwLoc, SourceLocation L, SourceLocation R, ArrayRef Data, @@ -4985,7 +5117,7 @@ return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers); } -OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context, +OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(ASTContext const &Context, unsigned NumIterators) { void *Mem = Context.Allocate( totalSizeToAlloc( Index: clang/lib/AST/ExprCXX.cpp =================================================================== --- clang/lib/AST/ExprCXX.cpp +++ clang/lib/AST/ExprCXX.cpp @@ -54,7 +54,8 @@ return false; switch (getOperator()) { - case OO_Call: case OO_Subscript: + case OO_Call: + case OO_Subscript: return false; default: return true; @@ -64,7 +65,7 @@ CXXRewrittenBinaryOperator::DecomposedForm CXXRewrittenBinaryOperator::getDecomposedForm() const { DecomposedForm Result = {}; - const Expr *E = getSemanticForm()->IgnoreImplicit(); + Expr const *E = getSemanticForm()->IgnoreImplicit(); // Remove an outer '!' if it exists (only happens for a '!=' rewrite). bool SkippedNot = false; @@ -85,13 +86,26 @@ assert(!SkippedNot || BO->getOperator() == OO_EqualEqual); assert(BO->isInfixBinaryOp()); switch (BO->getOperator()) { - case OO_Less: Result.Opcode = BO_LT; break; - case OO_LessEqual: Result.Opcode = BO_LE; break; - case OO_Greater: Result.Opcode = BO_GT; break; - case OO_GreaterEqual: Result.Opcode = BO_GE; break; - case OO_Spaceship: Result.Opcode = BO_Cmp; break; - case OO_EqualEqual: Result.Opcode = SkippedNot ? BO_NE : BO_EQ; break; - default: llvm_unreachable("unexpected binop in rewritten operator expr"); + case OO_Less: + Result.Opcode = BO_LT; + break; + case OO_LessEqual: + Result.Opcode = BO_LE; + break; + case OO_Greater: + Result.Opcode = BO_GT; + break; + case OO_GreaterEqual: + Result.Opcode = BO_GE; + break; + case OO_Spaceship: + Result.Opcode = BO_Cmp; + break; + case OO_EqualEqual: + Result.Opcode = SkippedNot ? BO_NE : BO_EQ; + break; + default: + llvm_unreachable("unexpected binop in rewritten operator expr"); } Result.LHS = BO->getArg(0); Result.RHS = BO->getArg(1); @@ -138,8 +152,8 @@ // C++11 [expr.typeid]p3: // When typeid is applied to an expression other than a glvalue of // polymorphic class type, [...] the expression is an unevaluated operand. - const Expr *E = getExprOperand(); - if (const CXXRecordDecl *RD = E->getType()->getAsCXXRecordDecl()) + Expr const *E = getExprOperand(); + if (CXXRecordDecl const *RD = E->getType()->getAsCXXRecordDecl()) if (RD->isPolymorphic() && E->isGLValue()) return true; @@ -148,8 +162,8 @@ bool CXXTypeidExpr::isMostDerived(ASTContext &Context) const { assert(!isTypeOperand() && "Cannot call isMostDerived for typeid(type)"); - const Expr *E = getExprOperand()->IgnoreParenNoopCasts(Context); - if (const auto *DRE = dyn_cast(E)) { + Expr const *E = getExprOperand()->IgnoreParenNoopCasts(Context); + if (auto const *DRE = dyn_cast(E)) { QualType Ty = DRE->getDecl()->getType(); if (!Ty->isPointerType() && !Ty->isReferenceType()) return true; @@ -240,7 +254,7 @@ } CXXNewExpr * -CXXNewExpr::Create(const ASTContext &Ctx, bool IsGlobalNew, +CXXNewExpr::Create(ASTContext const &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize, ArrayRef PlacementArgs, SourceRange TypeIdParens, @@ -263,7 +277,7 @@ AllocatedTypeInfo, Range, DirectInitRange); } -CXXNewExpr *CXXNewExpr::CreateEmpty(const ASTContext &Ctx, bool IsArray, +CXXNewExpr *CXXNewExpr::CreateEmpty(ASTContext const &Ctx, bool IsArray, bool HasInit, unsigned NumPlacementArgs, bool IsParenTypeId) { void *Mem = @@ -285,12 +299,12 @@ // CXXDeleteExpr QualType CXXDeleteExpr::getDestroyedType() const { - const Expr *Arg = getArgument(); + Expr const *Arg = getArgument(); // For a destroying operator delete, we may have implicitly converted the // pointer type to the type of the parameter of the 'operator delete' // function. - while (const auto *ICE = dyn_cast(Arg)) { + while (auto const *ICE = dyn_cast(Arg)) { if (ICE->getCastKind() == CK_DerivedToBase || ICE->getCastKind() == CK_UncheckedDerivedToBase || ICE->getCastKind() == CK_NoOp) { @@ -318,7 +332,7 @@ } CXXPseudoDestructorExpr::CXXPseudoDestructorExpr( - const ASTContext &Context, Expr *Base, bool isArrow, + ASTContext const &Context, Expr *Base, bool isArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, TypeSourceInfo *ScopeType, SourceLocation ColonColonLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType) @@ -347,10 +361,10 @@ // UnresolvedLookupExpr UnresolvedLookupExpr::UnresolvedLookupExpr( - const ASTContext &Context, CXXRecordDecl *NamingClass, + ASTContext const &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, - const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, - const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin, + DeclarationNameInfo const &NameInfo, bool RequiresADL, bool Overloaded, + TemplateArgumentListInfo const *TemplateArgs, UnresolvedSetIterator Begin, UnresolvedSetIterator End) : OverloadExpr(UnresolvedLookupExprClass, Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs, Begin, End, false, @@ -367,8 +381,8 @@ HasTemplateKWAndArgsInfo) {} UnresolvedLookupExpr *UnresolvedLookupExpr::Create( - const ASTContext &Context, CXXRecordDecl *NamingClass, - NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, + ASTContext const &Context, CXXRecordDecl *NamingClass, + NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo const &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End) { unsigned NumResults = End - Begin; @@ -381,10 +395,10 @@ } UnresolvedLookupExpr *UnresolvedLookupExpr::Create( - const ASTContext &Context, CXXRecordDecl *NamingClass, + ASTContext const &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, - const DeclarationNameInfo &NameInfo, bool RequiresADL, - const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin, + DeclarationNameInfo const &NameInfo, bool RequiresADL, + TemplateArgumentListInfo const *Args, UnresolvedSetIterator Begin, UnresolvedSetIterator End) { assert(Args || TemplateKWLoc.isValid()); unsigned NumResults = End - Begin; @@ -399,7 +413,7 @@ } UnresolvedLookupExpr *UnresolvedLookupExpr::CreateEmpty( - const ASTContext &Context, unsigned NumResults, + ASTContext const &Context, unsigned NumResults, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) { assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo); unsigned Size = totalSizeToAlloc 0; --I) { - const Expr *Arg = getArg(I-1); + Expr const *Arg = getArg(I - 1); if (!Arg->isDefaultArgument()) { SourceLocation NewEnd = Arg->getEndLoc(); if (NewEnd.isValid()) { @@ -555,7 +569,7 @@ HasFPFeatures, Empty) {} CXXOperatorCallExpr * -CXXOperatorCallExpr::Create(const ASTContext &Ctx, +CXXOperatorCallExpr::Create(ASTContext const &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, @@ -570,7 +584,7 @@ FPFeatures, UsesADL); } -CXXOperatorCallExpr *CXXOperatorCallExpr::CreateEmpty(const ASTContext &Ctx, +CXXOperatorCallExpr *CXXOperatorCallExpr::CreateEmpty(ASTContext const &Ctx, unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty) { @@ -619,7 +633,7 @@ : CallExpr(CXXMemberCallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty) {} -CXXMemberCallExpr *CXXMemberCallExpr::Create(const ASTContext &Ctx, Expr *Fn, +CXXMemberCallExpr *CXXMemberCallExpr::Create(ASTContext const &Ctx, Expr *Fn, ArrayRef Args, QualType Ty, ExprValueKind VK, SourceLocation RP, @@ -635,7 +649,7 @@ CXXMemberCallExpr(Fn, Args, Ty, VK, RP, FPFeatures, MinNumArgs); } -CXXMemberCallExpr *CXXMemberCallExpr::CreateEmpty(const ASTContext &Ctx, +CXXMemberCallExpr *CXXMemberCallExpr::CreateEmpty(ASTContext const &Ctx, unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty) { @@ -648,10 +662,10 @@ } Expr *CXXMemberCallExpr::getImplicitObjectArgument() const { - const Expr *Callee = getCallee()->IgnoreParens(); - if (const auto *MemExpr = dyn_cast(Callee)) + Expr const *Callee = getCallee()->IgnoreParens(); + if (auto const *MemExpr = dyn_cast(Callee)) return MemExpr->getBase(); - if (const auto *BO = dyn_cast(Callee)) + if (auto const *BO = dyn_cast(Callee)) if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI) return BO->getLHS(); @@ -667,7 +681,7 @@ } CXXMethodDecl *CXXMemberCallExpr::getMethodDecl() const { - if (const auto *MemExpr = dyn_cast(getCallee()->IgnoreParens())) + if (auto const *MemExpr = dyn_cast(getCallee()->IgnoreParens())) return cast(MemExpr->getMemberDecl()); // FIXME: Will eventually need to cope with member pointers. @@ -676,7 +690,7 @@ } CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const { - Expr* ThisArg = getImplicitObjectArgument(); + Expr *ThisArg = getImplicitObjectArgument(); if (!ThisArg) return nullptr; @@ -693,20 +707,26 @@ /// getCastName - Get the name of the C++ cast being used, e.g., /// "static_cast", "dynamic_cast", "reinterpret_cast", or /// "const_cast". The returned pointer must not be freed. -const char *CXXNamedCastExpr::getCastName() const { +char const *CXXNamedCastExpr::getCastName() const { switch (getStmtClass()) { - case CXXStaticCastExprClass: return "static_cast"; - case CXXDynamicCastExprClass: return "dynamic_cast"; - case CXXReinterpretCastExprClass: return "reinterpret_cast"; - case CXXConstCastExprClass: return "const_cast"; - case CXXAddrspaceCastExprClass: return "addrspace_cast"; - default: return ""; + case CXXStaticCastExprClass: + return "static_cast"; + case CXXDynamicCastExprClass: + return "dynamic_cast"; + case CXXReinterpretCastExprClass: + return "reinterpret_cast"; + case CXXConstCastExprClass: + return "const_cast"; + case CXXAddrspaceCastExprClass: + return "addrspace_cast"; + default: + return ""; } } CXXStaticCastExpr * -CXXStaticCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, - CastKind K, Expr *Op, const CXXCastPath *BasePath, +CXXStaticCastExpr::Create(ASTContext const &C, QualType T, ExprValueKind VK, + CastKind K, Expr *Op, CXXCastPath const *BasePath, TypeSourceInfo *WrittenTy, FPOptionsOverride FPO, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { @@ -722,7 +742,7 @@ return E; } -CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C, +CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(ASTContext const &C, unsigned PathSize, bool HasFPFeatures) { void *Buffer = @@ -731,26 +751,21 @@ return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize, HasFPFeatures); } -CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T, - ExprValueKind VK, - CastKind K, Expr *Op, - const CXXCastPath *BasePath, - TypeSourceInfo *WrittenTy, - SourceLocation L, - SourceLocation RParenLoc, - SourceRange AngleBrackets) { +CXXDynamicCastExpr *CXXDynamicCastExpr::Create( + ASTContext const &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, + CXXCastPath const *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, + SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); - auto *E = - new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, - RParenLoc, AngleBrackets); + auto *E = new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, + L, RParenLoc, AngleBrackets); if (PathSize) std::uninitialized_copy_n(BasePath->data(), BasePath->size(), E->getTrailingObjects()); return E; } -CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(const ASTContext &C, +CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(ASTContext const &C, unsigned PathSize) { void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize); @@ -764,12 +779,11 @@ /// struct C { }; /// /// C *f(B* b) { return dynamic_cast(b); } -bool CXXDynamicCastExpr::isAlwaysNull() const -{ +bool CXXDynamicCastExpr::isAlwaysNull() const { QualType SrcType = getSubExpr()->getType(); QualType DestType = getType(); - if (const auto *SrcPTy = SrcType->getAs()) { + if (auto const *SrcPTy = SrcType->getAs()) { SrcType = SrcPTy->getPointeeType(); DestType = DestType->castAs()->getPointeeType(); } @@ -777,57 +791,52 @@ if (DestType->isVoidType()) return false; - const auto *SrcRD = + auto const *SrcRD = cast(SrcType->castAs()->getDecl()); if (!SrcRD->hasAttr()) return false; - const auto *DestRD = + auto const *DestRD = cast(DestType->castAs()->getDecl()); return !DestRD->isDerivedFrom(SrcRD); } -CXXReinterpretCastExpr * -CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T, - ExprValueKind VK, CastKind K, Expr *Op, - const CXXCastPath *BasePath, - TypeSourceInfo *WrittenTy, SourceLocation L, - SourceLocation RParenLoc, - SourceRange AngleBrackets) { +CXXReinterpretCastExpr *CXXReinterpretCastExpr::Create( + ASTContext const &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, + CXXCastPath const *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, + SourceLocation RParenLoc, SourceRange AngleBrackets) { unsigned PathSize = (BasePath ? BasePath->size() : 0); void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); - auto *E = - new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L, - RParenLoc, AngleBrackets); + auto *E = new (Buffer) CXXReinterpretCastExpr( + T, VK, K, Op, PathSize, WrittenTy, L, RParenLoc, AngleBrackets); if (PathSize) std::uninitialized_copy_n(BasePath->data(), BasePath->size(), E->getTrailingObjects()); return E; } -CXXReinterpretCastExpr * -CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) { +CXXReinterpretCastExpr *CXXReinterpretCastExpr::CreateEmpty(ASTContext const &C, + unsigned PathSize) { void *Buffer = C.Allocate(totalSizeToAlloc(PathSize)); return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize); } -CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T, - ExprValueKind VK, Expr *Op, - TypeSourceInfo *WrittenTy, - SourceLocation L, - SourceLocation RParenLoc, - SourceRange AngleBrackets) { - return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets); +CXXConstCastExpr * +CXXConstCastExpr::Create(ASTContext const &C, QualType T, ExprValueKind VK, + Expr *Op, TypeSourceInfo *WrittenTy, SourceLocation L, + SourceLocation RParenLoc, SourceRange AngleBrackets) { + return new (C) + CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets); } -CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(const ASTContext &C) { +CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(ASTContext const &C) { return new (C) CXXConstCastExpr(EmptyShell()); } CXXAddrspaceCastExpr * -CXXAddrspaceCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK, +CXXAddrspaceCastExpr::Create(ASTContext const &C, QualType T, ExprValueKind VK, CastKind K, Expr *Op, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets) { @@ -835,13 +844,13 @@ AngleBrackets); } -CXXAddrspaceCastExpr *CXXAddrspaceCastExpr::CreateEmpty(const ASTContext &C) { +CXXAddrspaceCastExpr *CXXAddrspaceCastExpr::CreateEmpty(ASTContext const &C) { return new (C) CXXAddrspaceCastExpr(EmptyShell()); } CXXFunctionalCastExpr *CXXFunctionalCastExpr::Create( - const ASTContext &C, QualType T, ExprValueKind VK, TypeSourceInfo *Written, - CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, + ASTContext const &C, QualType T, ExprValueKind VK, TypeSourceInfo *Written, + CastKind K, Expr *Op, CXXCastPath const *BasePath, FPOptionsOverride FPO, SourceLocation L, SourceLocation R) { unsigned PathSize = (BasePath ? BasePath->size() : 0); void *Buffer = @@ -855,7 +864,7 @@ return E; } -CXXFunctionalCastExpr *CXXFunctionalCastExpr::CreateEmpty(const ASTContext &C, +CXXFunctionalCastExpr *CXXFunctionalCastExpr::CreateEmpty(ASTContext const &C, unsigned PathSize, bool HasFPFeatures) { void *Buffer = @@ -887,7 +896,7 @@ : CallExpr(UserDefinedLiteralClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty) {} -UserDefinedLiteral *UserDefinedLiteral::Create(const ASTContext &Ctx, Expr *Fn, +UserDefinedLiteral *UserDefinedLiteral::Create(ASTContext const &Ctx, Expr *Fn, ArrayRef Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, @@ -903,7 +912,7 @@ UserDefinedLiteral(Fn, Args, Ty, VK, LitEndLoc, SuffixLoc, FPFeatures); } -UserDefinedLiteral *UserDefinedLiteral::CreateEmpty(const ASTContext &Ctx, +UserDefinedLiteral *UserDefinedLiteral::CreateEmpty(ASTContext const &Ctx, unsigned NumArgs, bool HasFPOptions, EmptyShell Empty) { @@ -924,7 +933,7 @@ assert(getNumArgs() == 1 && "unexpected #args in literal operator call"); QualType ParamTy = - cast(getCalleeDecl())->getParamDecl(0)->getType(); + cast(getCalleeDecl())->getParamDecl(0)->getType(); if (ParamTy->isPointerType()) return LOK_Raw; if (ParamTy->isAnyCharacterType()) @@ -945,11 +954,11 @@ return getArg(0); } -const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const { +IdentifierInfo const *UserDefinedLiteral::getUDSuffix() const { return cast(getCalleeDecl())->getLiteralIdentifier(); } -CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &Ctx, +CXXDefaultInitExpr::CXXDefaultInitExpr(ASTContext const &Ctx, SourceLocation Loc, FieldDecl *Field, QualType Ty, DeclContext *UsedContext) : Expr(CXXDefaultInitExprClass, Ty.getNonLValueExprType(Ctx), @@ -964,14 +973,14 @@ setDependence(computeDependence(this)); } -CXXTemporary *CXXTemporary::Create(const ASTContext &C, - const CXXDestructorDecl *Destructor) { +CXXTemporary *CXXTemporary::Create(ASTContext const &C, + CXXDestructorDecl const *Destructor) { return new (C) CXXTemporary(Destructor); } -CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(const ASTContext &C, +CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(ASTContext const &C, CXXTemporary *Temp, - Expr* SubExpr) { + Expr *SubExpr) { assert((SubExpr->getType()->isRecordType() || SubExpr->getType()->isArrayType()) && "Expression bound to a temporary must have record or array type!"); @@ -996,7 +1005,7 @@ : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty, NumArgs) {} CXXTemporaryObjectExpr *CXXTemporaryObjectExpr::Create( - const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty, + ASTContext const &Ctx, CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI, ArrayRef Args, SourceRange ParenOrBraceRange, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization) { @@ -1010,7 +1019,7 @@ } CXXTemporaryObjectExpr * -CXXTemporaryObjectExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs) { +CXXTemporaryObjectExpr::CreateEmpty(ASTContext const &Ctx, unsigned NumArgs) { unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs); void *Mem = Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects, @@ -1030,7 +1039,7 @@ } CXXConstructExpr *CXXConstructExpr::Create( - const ASTContext &Ctx, QualType Ty, SourceLocation Loc, + ASTContext const &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, @@ -1044,7 +1053,7 @@ ZeroInitialization, ConstructKind, ParenOrBraceRange); } -CXXConstructExpr *CXXConstructExpr::CreateEmpty(const ASTContext &Ctx, +CXXConstructExpr *CXXConstructExpr::CreateEmpty(ASTContext const &Ctx, unsigned NumArgs) { unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs); void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects, @@ -1160,7 +1169,7 @@ getStoredStmts()[NumCaptures] = nullptr; // Not one past the end. } -LambdaExpr *LambdaExpr::Create(const ASTContext &Context, CXXRecordDecl *Class, +LambdaExpr *LambdaExpr::Create(ASTContext const &Context, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, @@ -1180,7 +1189,7 @@ ContainsUnexpandedParameterPack); } -LambdaExpr *LambdaExpr::CreateDeserialized(const ASTContext &C, +LambdaExpr *LambdaExpr::CreateDeserialized(ASTContext const &C, unsigned NumCaptures) { unsigned Size = totalSizeToAlloc(NumCaptures + 1); void *Mem = C.Allocate(Size); @@ -1199,14 +1208,14 @@ return getStoredStmts()[capture_size()]; } -const CompoundStmt *LambdaExpr::getCompoundStmtBody() const { +CompoundStmt const *LambdaExpr::getCompoundStmtBody() const { Stmt *Body = getBody(); - if (const auto *CoroBody = dyn_cast(Body)) + if (auto const *CoroBody = dyn_cast(Body)) return cast(CoroBody->getBody()); return cast(Body); } -bool LambdaExpr::isInitCapture(const LambdaCapture *C) const { +bool LambdaExpr::isInitCapture(LambdaCapture const *C) const { return (C->capturesVariable() && C->getCapturedVar()->isInitCapture() && (getCallOperator() == C->getCapturedVar()->getDeclContext())); } @@ -1228,8 +1237,8 @@ } LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const { - struct CXXRecordDecl::LambdaDefinitionData &Data - = getLambdaClass()->getLambdaData(); + struct CXXRecordDecl::LambdaDefinitionData &Data = + getLambdaClass()->getLambdaData(); return Data.Captures + Data.NumExplicitCaptures; } @@ -1269,7 +1278,7 @@ } ArrayRef LambdaExpr::getExplicitTemplateParameters() const { - const CXXRecordDecl *Record = getLambdaClass(); + CXXRecordDecl const *Record = getLambdaClass(); return Record->getLambdaExplicitTemplateParameters(); } @@ -1290,8 +1299,7 @@ getStoredStmts() + capture_size() + 1); } -ExprWithCleanups::ExprWithCleanups(Expr *subexpr, - bool CleanupsHaveSideEffects, +ExprWithCleanups::ExprWithCleanups(Expr *subexpr, bool CleanupsHaveSideEffects, ArrayRef objects) : FullExpr(ExprWithCleanupsClass, subexpr) { ExprWithCleanupsBits.CleanupsHaveSideEffects = CleanupsHaveSideEffects; @@ -1300,7 +1308,7 @@ getTrailingObjects()[i] = objects[i]; } -ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr, +ExprWithCleanups *ExprWithCleanups::Create(ASTContext const &C, Expr *subexpr, bool CleanupsHaveSideEffects, ArrayRef objects) { void *buffer = C.Allocate(totalSizeToAlloc(objects.size()), @@ -1314,7 +1322,7 @@ ExprWithCleanupsBits.NumObjects = numObjects; } -ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, +ExprWithCleanups *ExprWithCleanups::Create(ASTContext const &C, EmptyShell empty, unsigned numObjects) { void *buffer = C.Allocate(totalSizeToAlloc(numObjects), @@ -1341,15 +1349,15 @@ } CXXUnresolvedConstructExpr *CXXUnresolvedConstructExpr::Create( - const ASTContext &Context, QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc, - ArrayRef Args, SourceLocation RParenLoc) { + ASTContext const &Context, QualType T, TypeSourceInfo *TSI, + SourceLocation LParenLoc, ArrayRef Args, SourceLocation RParenLoc) { void *Mem = Context.Allocate(totalSizeToAlloc(Args.size())); return new (Mem) CXXUnresolvedConstructExpr(T, TSI, LParenLoc, Args, RParenLoc); } CXXUnresolvedConstructExpr * -CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &Context, +CXXUnresolvedConstructExpr::CreateEmpty(ASTContext const &Context, unsigned NumArgs) { void *Mem = Context.Allocate(totalSizeToAlloc(NumArgs)); return new (Mem) CXXUnresolvedConstructExpr(EmptyShell(), NumArgs); @@ -1360,11 +1368,11 @@ } CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr( - const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, + ASTContext const &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, - const TemplateArgumentListInfo *TemplateArgs) + TemplateArgumentListInfo const *TemplateArgs) : Expr(CXXDependentScopeMemberExprClass, Ctx.DependentTy, VK_LValue, OK_Ordinary), Base(Base), BaseType(BaseType), QualifierLoc(QualifierLoc), @@ -1402,11 +1410,11 @@ } CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::Create( - const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, + ASTContext const &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, - const TemplateArgumentListInfo *TemplateArgs) { + TemplateArgumentListInfo const *TemplateArgs) { bool HasTemplateKWAndArgsInfo = (TemplateArgs != nullptr) || TemplateKWLoc.isValid(); unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0; @@ -1423,7 +1431,7 @@ } CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::CreateEmpty( - const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo, + ASTContext const &Ctx, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope) { assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo); @@ -1454,11 +1462,11 @@ } UnresolvedMemberExpr::UnresolvedMemberExpr( - const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base, + ASTContext const &Context, bool HasUnresolvedUsing, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, - const DeclarationNameInfo &MemberNameInfo, - const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin, + DeclarationNameInfo const &MemberNameInfo, + TemplateArgumentListInfo const *TemplateArgs, UnresolvedSetIterator Begin, UnresolvedSetIterator End) : OverloadExpr( UnresolvedMemberExprClass, Context, QualifierLoc, TemplateKWLoc, @@ -1494,11 +1502,11 @@ } UnresolvedMemberExpr *UnresolvedMemberExpr::Create( - const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base, + ASTContext const &Context, bool HasUnresolvedUsing, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, - const DeclarationNameInfo &MemberNameInfo, - const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin, + DeclarationNameInfo const &MemberNameInfo, + TemplateArgumentListInfo const *TemplateArgs, UnresolvedSetIterator Begin, UnresolvedSetIterator End) { unsigned NumResults = End - Begin; bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid(); @@ -1513,7 +1521,7 @@ } UnresolvedMemberExpr *UnresolvedMemberExpr::CreateEmpty( - const ASTContext &Context, unsigned NumResults, + ASTContext const &Context, unsigned NumResults, bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) { assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo); unsigned Size = totalSizeToAllocgetKind() != NestedNameSpecifier::Super) { - const Type *T = getQualifier()->getAsType(); + Type const *T = getQualifier()->getAsType(); assert(T && "qualifier in member expression does not name type"); Record = T->getAsCXXRecordDecl(); assert(Record && "qualifier in member expression does not name record"); @@ -1551,12 +1559,12 @@ return Record; } -SizeOfPackExpr * -SizeOfPackExpr::Create(ASTContext &Context, SourceLocation OperatorLoc, - NamedDecl *Pack, SourceLocation PackLoc, - SourceLocation RParenLoc, - Optional Length, - ArrayRef PartialArgs) { +SizeOfPackExpr *SizeOfPackExpr::Create(ASTContext &Context, + SourceLocation OperatorLoc, + NamedDecl *Pack, SourceLocation PackLoc, + SourceLocation RParenLoc, + Optional Length, + ArrayRef PartialArgs) { void *Storage = Context.Allocate(totalSizeToAlloc(PartialArgs.size())); return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack, @@ -1571,7 +1579,7 @@ } QualType SubstNonTypeTemplateParmExpr::getParameterType( - const ASTContext &Context) const { + ASTContext const &Context) const { // Note that, for a class type NTTP, we will have an lvalue of type 'const // T', so we can't just compute this from the type and value category. if (isReferenceParameter()) @@ -1581,7 +1589,7 @@ SubstNonTypeTemplateParmPackExpr::SubstNonTypeTemplateParmPackExpr( QualType T, ExprValueKind ValueKind, NonTypeTemplateParmDecl *Param, - SourceLocation NameLoc, const TemplateArgument &ArgPack) + SourceLocation NameLoc, TemplateArgument const &ArgPack) : Expr(SubstNonTypeTemplateParmPackExprClass, T, ValueKind, OK_Ordinary), Param(Param), Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) { @@ -1606,16 +1614,17 @@ ExprDependence::UnexpandedPack); } -FunctionParmPackExpr * -FunctionParmPackExpr::Create(const ASTContext &Context, QualType T, - VarDecl *ParamPack, SourceLocation NameLoc, - ArrayRef Params) { +FunctionParmPackExpr *FunctionParmPackExpr::Create(ASTContext const &Context, + QualType T, + VarDecl *ParamPack, + SourceLocation NameLoc, + ArrayRef Params) { return new (Context.Allocate(totalSizeToAlloc(Params.size()))) FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data()); } FunctionParmPackExpr * -FunctionParmPackExpr::CreateEmpty(const ASTContext &Context, +FunctionParmPackExpr::CreateEmpty(ASTContext const &Context, unsigned NumParams) { return new (Context.Allocate(totalSizeToAlloc(NumParams))) FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr); @@ -1653,7 +1662,7 @@ } bool MaterializeTemporaryExpr::isUsableInConstantExpressions( - const ASTContext &Context) const { + ASTContext const &Context) const { // C++20 [expr.const]p4: // An object or reference is usable in constant expressions if it is [...] // a temporary object of non-volatile const-qualified literal type @@ -1687,17 +1696,15 @@ setDependence(computeDependence(this)); } -TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T, - SourceLocation Loc, - TypeTrait Kind, +TypeTraitExpr *TypeTraitExpr::Create(ASTContext const &C, QualType T, + SourceLocation Loc, TypeTrait Kind, ArrayRef Args, - SourceLocation RParenLoc, - bool Value) { + SourceLocation RParenLoc, bool Value) { void *Mem = C.Allocate(totalSizeToAlloc(Args.size())); return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value); } -TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C, +TypeTraitExpr *TypeTraitExpr::CreateDeserialized(ASTContext const &C, unsigned NumArgs) { void *Mem = C.Allocate(totalSizeToAlloc(NumArgs)); return new (Mem) TypeTraitExpr(EmptyShell()); @@ -1717,7 +1724,7 @@ HasFPFeatures, Empty) {} CUDAKernelCallExpr * -CUDAKernelCallExpr::Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, +CUDAKernelCallExpr::Create(ASTContext const &Ctx, Expr *Fn, CallExpr *Config, ArrayRef Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs) { @@ -1731,7 +1738,7 @@ CUDAKernelCallExpr(Fn, Config, Args, Ty, VK, RP, FPFeatures, MinNumArgs); } -CUDAKernelCallExpr *CUDAKernelCallExpr::CreateEmpty(const ASTContext &Ctx, +CUDAKernelCallExpr *CUDAKernelCallExpr::CreateEmpty(ASTContext const &Ctx, unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty) { Index: clang/lib/AST/ExprClassification.cpp =================================================================== --- clang/lib/AST/ExprClassification.cpp +++ clang/lib/AST/ExprClassification.cpp @@ -10,11 +10,11 @@ // //===----------------------------------------------------------------------===// -#include "clang/AST/Expr.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" +#include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "llvm/Support/ErrorHandling.h" @@ -23,15 +23,14 @@ using Cl = Expr::Classification; -static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E); -static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D); +static Cl::Kinds ClassifyInternal(ASTContext &Ctx, Expr const *E); +static Cl::Kinds ClassifyDecl(ASTContext &Ctx, Decl const *D); static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T); -static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E); -static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E); -static Cl::Kinds ClassifyConditional(ASTContext &Ctx, - const Expr *trueExpr, - const Expr *falseExpr); -static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E, +static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, MemberExpr const *E); +static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, BinaryOperator const *E); +static Cl::Kinds ClassifyConditional(ASTContext &Ctx, Expr const *trueExpr, + Expr const *falseExpr); +static Cl::ModifiableType IsModifiable(ASTContext &Ctx, Expr const *E, Cl::Kinds Kind, SourceLocation &Loc); Cl Expr::ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const { @@ -91,8 +90,7 @@ return Cl::CL_PRValue; } -static Cl::Kinds ClassifyExprValueKind(const LangOptions &Lang, - const Expr *E, +static Cl::Kinds ClassifyExprValueKind(LangOptions const &Lang, Expr const *E, ExprValueKind Kind) { switch (Kind) { case VK_PRValue: @@ -105,9 +103,9 @@ llvm_unreachable("Invalid value category of implicit cast."); } -static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) { +static Cl::Kinds ClassifyInternal(ASTContext &Ctx, Expr const *E) { // This function takes the first stab at classifying expressions. - const LangOptions &Lang = Ctx.getLangOpts(); + LangOptions const &Lang = Ctx.getLangOpts(); switch (E->getStmtClass()) { case Stmt::NoStmtClass: @@ -210,8 +208,8 @@ // Next come the complicated cases. case Expr::SubstNonTypeTemplateParmExprClass: - return ClassifyInternal(Ctx, - cast(E)->getReplacement()); + return ClassifyInternal( + Ctx, cast(E)->getReplacement()); // C, C++98 [expr.sub]p1: The result is an lvalue of type "T". // C++11 (DR1213): in the case of an array operand, the result is an lvalue @@ -237,8 +235,8 @@ // function or variable and a prvalue otherwise. case Expr::DeclRefExprClass: if (E->getType() == Ctx.UnknownAnyTy) - return isa(cast(E)->getDecl()) - ? Cl::CL_PRValue : Cl::CL_LValue; + return isa(cast(E)->getDecl()) ? Cl::CL_PRValue + : Cl::CL_LValue; return ClassifyDecl(Ctx, cast(E)->getDecl()); // Member access is complex. @@ -261,9 +259,10 @@ // expressions: l-value only if the operand is a true l-value. case UO_Real: case UO_Imag: { - const Expr *Op = cast(E)->getSubExpr()->IgnoreParens(); + Expr const *Op = cast(E)->getSubExpr()->IgnoreParens(); Cl::Kinds K = ClassifyInternal(Ctx, Op); - if (K != Cl::CL_LValue) return K; + if (K != Cl::CL_LValue) + return K; if (isa(Op)) return Cl::CL_SubObjCPropertySetting; @@ -306,7 +305,8 @@ case Expr::GenericSelectionExprClass: if (cast(E)->isResultDependent()) return Cl::CL_PRValue; - return ClassifyInternal(Ctx,cast(E)->getResultExpr()); + return ClassifyInternal(Ctx, + cast(E)->getResultExpr()); case Expr::BinaryOperatorClass: case Expr::CompoundAssignOperatorClass: @@ -366,31 +366,34 @@ case Expr::ObjCBridgedCastExprClass: case Expr::BuiltinBitCastExprClass: // Only in C++ can casts be interesting at all. - if (!Lang.CPlusPlus) return Cl::CL_PRValue; + if (!Lang.CPlusPlus) + return Cl::CL_PRValue; return ClassifyUnnamed(Ctx, cast(E)->getTypeAsWritten()); case Expr::CXXUnresolvedConstructExprClass: - return ClassifyUnnamed(Ctx, - cast(E)->getTypeAsWritten()); + return ClassifyUnnamed( + Ctx, cast(E)->getTypeAsWritten()); case Expr::BinaryConditionalOperatorClass: { - if (!Lang.CPlusPlus) return Cl::CL_PRValue; - const auto *co = cast(E); + if (!Lang.CPlusPlus) + return Cl::CL_PRValue; + auto const *co = cast(E); return ClassifyConditional(Ctx, co->getTrueExpr(), co->getFalseExpr()); } case Expr::ConditionalOperatorClass: { // Once again, only C++ is interesting. - if (!Lang.CPlusPlus) return Cl::CL_PRValue; - const auto *co = cast(E); + if (!Lang.CPlusPlus) + return Cl::CL_PRValue; + auto const *co = cast(E); return ClassifyConditional(Ctx, co->getTrueExpr(), co->getFalseExpr()); } // ObjC message sends are effectively function calls, if the target function // is known. case Expr::ObjCMessageExprClass: - if (const ObjCMethodDecl *Method = - cast(E)->getMethodDecl()) { + if (ObjCMethodDecl const *Method = + cast(E)->getMethodDecl()) { Cl::Kinds kind = ClassifyUnnamed(Ctx, Method->getReturnType()); return (kind == Cl::CL_PRValue) ? Cl::CL_ObjCMessageRValue : kind; } @@ -411,8 +414,8 @@ return ClassifyInternal(Ctx, cast(E)->getInit()); case Expr::StmtExprClass: { - const CompoundStmt *S = cast(E)->getSubStmt(); - if (const auto *LastExpr = dyn_cast_or_null(S->body_back())) + CompoundStmt const *S = cast(E)->getSubStmt(); + if (auto const *LastExpr = dyn_cast_or_null(S->body_back())) return ClassifyUnnamed(Ctx, LastExpr->getType()); return Cl::CL_PRValue; } @@ -422,8 +425,8 @@ case Expr::MaterializeTemporaryExprClass: return cast(E)->isBoundToLvalueReference() - ? Cl::CL_LValue - : Cl::CL_XValue; + ? Cl::CL_LValue + : Cl::CL_XValue; case Expr::InitListExprClass: // An init list can be an lvalue if it is bound to a reference and @@ -438,7 +441,8 @@ case Expr::CoawaitExprClass: case Expr::CoyieldExprClass: - return ClassifyInternal(Ctx, cast(E)->getResumeExpr()); + return ClassifyInternal(Ctx, + cast(E)->getResumeExpr()); case Expr::SYCLUniqueStableNameExprClass: return Cl::CL_PRValue; break; @@ -449,7 +453,7 @@ /// ClassifyDecl - Return the classification of an expression referencing the /// given declaration. -static Cl::Kinds ClassifyDecl(ASTContext &Ctx, const Decl *D) { +static Cl::Kinds ClassifyDecl(ASTContext &Ctx, Decl const *D) { // C++ [expr.prim.general]p6: The result is an lvalue if the entity is a // function, variable, or data member and a prvalue otherwise. // In C, functions are not lvalues. @@ -461,15 +465,13 @@ return Cl::CL_MemberFunction; bool islvalue; - if (const auto *NTTParm = dyn_cast(D)) + if (auto const *NTTParm = dyn_cast(D)) islvalue = NTTParm->getType()->isReferenceType() || NTTParm->getType()->isRecordType(); else islvalue = isa(D) || isa(D) || - isa(D) || - isa(D) || - isa(D) || - isa(D) || + isa(D) || isa(D) || + isa(D) || isa(D) || (Ctx.getLangOpts().CPlusPlus && (isa(D) || isa(D) || isa(D))); @@ -482,7 +484,8 @@ /// calls and casts. static Cl::Kinds ClassifyUnnamed(ASTContext &Ctx, QualType T) { // In C, function calls are always rvalues. - if (!Ctx.getLangOpts().CPlusPlus) return Cl::CL_PRValue; + if (!Ctx.getLangOpts().CPlusPlus) + return Cl::CL_PRValue; // C++ [expr.call]p10: A function call is an lvalue if the result type is an // lvalue reference type or an rvalue reference to function type, an xvalue @@ -490,17 +493,17 @@ // otherwise. if (T->isLValueReferenceType()) return Cl::CL_LValue; - const auto *RV = T->getAs(); + auto const *RV = T->getAs(); if (!RV) // Could still be a class temporary, though. return ClassifyTemporary(T); return RV->getPointeeType()->isFunctionType() ? Cl::CL_LValue : Cl::CL_XValue; } -static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, const MemberExpr *E) { +static Cl::Kinds ClassifyMemberExpr(ASTContext &Ctx, MemberExpr const *E) { if (E->getType() == Ctx.UnknownAnyTy) - return (isa(E->getMemberDecl()) - ? Cl::CL_PRValue : Cl::CL_LValue); + return (isa(E->getMemberDecl()) ? Cl::CL_PRValue + : Cl::CL_LValue); // Handle C first, it's easier. if (!Ctx.getLangOpts().CPlusPlus) { @@ -520,7 +523,7 @@ // C++ [expr.ref]p3: E1->E2 is converted to the equivalent form (*(E1)).E2. // C++ [expr.ref]p4: If E2 is declared to have type "reference to T", then // E1.E2 is an lvalue. - if (const auto *Value = dyn_cast(Member)) + if (auto const *Value = dyn_cast(Member)) if (Value->getType()->isReferenceType()) return Cl::CL_LValue; @@ -546,7 +549,7 @@ // -- If it refers to a static member function [...], then E1.E2 is an // lvalue; [...] // -- Otherwise [...] E1.E2 is a prvalue. - if (const auto *Method = dyn_cast(Member)) + if (auto const *Method = dyn_cast(Member)) return Method->isStatic() ? Cl::CL_LValue : Cl::CL_MemberFunction; // -- If E2 is a member enumerator [...], the expression E1.E2 is a prvalue. @@ -554,14 +557,13 @@ return Cl::CL_PRValue; } -static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, const BinaryOperator *E) { - assert(Ctx.getLangOpts().CPlusPlus && - "This is only relevant for C++."); +static Cl::Kinds ClassifyBinaryOp(ASTContext &Ctx, BinaryOperator const *E) { + assert(Ctx.getLangOpts().CPlusPlus && "This is only relevant for C++."); // C++ [expr.ass]p1: All [...] return an lvalue referring to the left operand. // Except we override this for writes to ObjC properties. if (E->isAssignmentOp()) - return (E->getLHS()->getObjectKind() == OK_ObjCProperty - ? Cl::CL_PRValue : Cl::CL_LValue); + return (E->getLHS()->getObjectKind() == OK_ObjCProperty ? Cl::CL_PRValue + : Cl::CL_LValue); // C++ [expr.comma]p1: the result is of the same value category as its right // operand, [...]. @@ -574,25 +576,24 @@ if (E->getOpcode() == BO_PtrMemD) return (E->getType()->isFunctionType() || E->hasPlaceholderType(BuiltinType::BoundMember)) - ? Cl::CL_MemberFunction - : ClassifyInternal(Ctx, E->getLHS()); + ? Cl::CL_MemberFunction + : ClassifyInternal(Ctx, E->getLHS()); // C++ [expr.mptr.oper]p6: The result of an ->* expression is an lvalue if its // second operand is a pointer to data member and a prvalue otherwise. if (E->getOpcode() == BO_PtrMemI) return (E->getType()->isFunctionType() || E->hasPlaceholderType(BuiltinType::BoundMember)) - ? Cl::CL_MemberFunction - : Cl::CL_LValue; + ? Cl::CL_MemberFunction + : Cl::CL_LValue; // All other binary operations are prvalues. return Cl::CL_PRValue; } -static Cl::Kinds ClassifyConditional(ASTContext &Ctx, const Expr *True, - const Expr *False) { - assert(Ctx.getLangOpts().CPlusPlus && - "This is only relevant for C++."); +static Cl::Kinds ClassifyConditional(ASTContext &Ctx, Expr const *True, + Expr const *False) { + assert(Ctx.getLangOpts().CPlusPlus && "This is only relevant for C++."); // C++ [expr.cond]p2 // If either the second or the third operand has type (cv) void, @@ -603,7 +604,7 @@ // category of the other. bool TrueIsThrow = isa(True->IgnoreParenImpCasts()); bool FalseIsThrow = isa(False->IgnoreParenImpCasts()); - if (const Expr *NonThrow = TrueIsThrow ? (FalseIsThrow ? nullptr : False) + if (Expr const *NonThrow = TrueIsThrow ? (FalseIsThrow ? nullptr : False) : (FalseIsThrow ? True : nullptr)) return ClassifyInternal(Ctx, NonThrow); @@ -621,14 +622,14 @@ return LCl == RCl ? LCl : Cl::CL_PRValue; } -static Cl::ModifiableType IsModifiable(ASTContext &Ctx, const Expr *E, +static Cl::ModifiableType IsModifiable(ASTContext &Ctx, Expr const *E, Cl::Kinds Kind, SourceLocation &Loc) { // As a general rule, we only care about lvalues. But there are some rvalues // for which we want to generate special results. if (Kind == Cl::CL_PRValue) { // For the sake of better diagnostics, we want to specifically recognize // use of the GCC cast-as-lvalue extension. - if (const auto *CE = dyn_cast(E->IgnoreParens())) { + if (auto const *CE = dyn_cast(E->IgnoreParens())) { if (CE->getSubExpr()->IgnoreParenImpCasts()->isLValue()) { Loc = CE->getExprLoc(); return Cl::CM_LValueCast; @@ -645,7 +646,7 @@ // Assignment to a property in ObjC is an implicit setter access. But a // setter might not exist. - if (const auto *Expr = dyn_cast(E)) { + if (auto const *Expr = dyn_cast(E)) { if (Expr->isImplicitProperty() && Expr->getImplicitPropertySetter() == nullptr) return Cl::CM_NoSetterProperty; @@ -667,7 +668,7 @@ return Cl::CM_IncompleteType; // Records with any const fields (recursively) are not modifiable. - if (const RecordType *R = CT->getAs()) + if (RecordType const *R = CT->getAs()) if (R->hasConstFields()) return Cl::CM_ConstQualifiedField; @@ -677,18 +678,30 @@ Expr::LValueClassification Expr::ClassifyLValue(ASTContext &Ctx) const { Classification VC = Classify(Ctx); switch (VC.getKind()) { - case Cl::CL_LValue: return LV_Valid; - case Cl::CL_XValue: return LV_InvalidExpression; - case Cl::CL_Function: return LV_NotObjectType; - case Cl::CL_Void: return LV_InvalidExpression; - case Cl::CL_AddressableVoid: return LV_IncompleteVoidType; - case Cl::CL_DuplicateVectorComponents: return LV_DuplicateVectorComponents; - case Cl::CL_MemberFunction: return LV_MemberFunction; - case Cl::CL_SubObjCPropertySetting: return LV_SubObjCPropertySetting; - case Cl::CL_ClassTemporary: return LV_ClassTemporary; - case Cl::CL_ArrayTemporary: return LV_ArrayTemporary; - case Cl::CL_ObjCMessageRValue: return LV_InvalidMessageExpression; - case Cl::CL_PRValue: return LV_InvalidExpression; + case Cl::CL_LValue: + return LV_Valid; + case Cl::CL_XValue: + return LV_InvalidExpression; + case Cl::CL_Function: + return LV_NotObjectType; + case Cl::CL_Void: + return LV_InvalidExpression; + case Cl::CL_AddressableVoid: + return LV_IncompleteVoidType; + case Cl::CL_DuplicateVectorComponents: + return LV_DuplicateVectorComponents; + case Cl::CL_MemberFunction: + return LV_MemberFunction; + case Cl::CL_SubObjCPropertySetting: + return LV_SubObjCPropertySetting; + case Cl::CL_ClassTemporary: + return LV_ClassTemporary; + case Cl::CL_ArrayTemporary: + return LV_ArrayTemporary; + case Cl::CL_ObjCMessageRValue: + return LV_InvalidMessageExpression; + case Cl::CL_PRValue: + return LV_InvalidExpression; } llvm_unreachable("Unhandled kind"); } @@ -698,35 +711,56 @@ SourceLocation dummy; Classification VC = ClassifyModifiable(Ctx, Loc ? *Loc : dummy); switch (VC.getKind()) { - case Cl::CL_LValue: break; - case Cl::CL_XValue: return MLV_InvalidExpression; - case Cl::CL_Function: return MLV_NotObjectType; - case Cl::CL_Void: return MLV_InvalidExpression; - case Cl::CL_AddressableVoid: return MLV_IncompleteVoidType; - case Cl::CL_DuplicateVectorComponents: return MLV_DuplicateVectorComponents; - case Cl::CL_MemberFunction: return MLV_MemberFunction; - case Cl::CL_SubObjCPropertySetting: return MLV_SubObjCPropertySetting; - case Cl::CL_ClassTemporary: return MLV_ClassTemporary; - case Cl::CL_ArrayTemporary: return MLV_ArrayTemporary; - case Cl::CL_ObjCMessageRValue: return MLV_InvalidMessageExpression; + case Cl::CL_LValue: + break; + case Cl::CL_XValue: + return MLV_InvalidExpression; + case Cl::CL_Function: + return MLV_NotObjectType; + case Cl::CL_Void: + return MLV_InvalidExpression; + case Cl::CL_AddressableVoid: + return MLV_IncompleteVoidType; + case Cl::CL_DuplicateVectorComponents: + return MLV_DuplicateVectorComponents; + case Cl::CL_MemberFunction: + return MLV_MemberFunction; + case Cl::CL_SubObjCPropertySetting: + return MLV_SubObjCPropertySetting; + case Cl::CL_ClassTemporary: + return MLV_ClassTemporary; + case Cl::CL_ArrayTemporary: + return MLV_ArrayTemporary; + case Cl::CL_ObjCMessageRValue: + return MLV_InvalidMessageExpression; case Cl::CL_PRValue: - return VC.getModifiable() == Cl::CM_LValueCast ? - MLV_LValueCast : MLV_InvalidExpression; + return VC.getModifiable() == Cl::CM_LValueCast ? MLV_LValueCast + : MLV_InvalidExpression; } assert(VC.getKind() == Cl::CL_LValue && "Unhandled kind"); switch (VC.getModifiable()) { - case Cl::CM_Untested: llvm_unreachable("Did not test modifiability"); - case Cl::CM_Modifiable: return MLV_Valid; - case Cl::CM_RValue: llvm_unreachable("CM_RValue and CL_LValue don't match"); - case Cl::CM_Function: return MLV_NotObjectType; + case Cl::CM_Untested: + llvm_unreachable("Did not test modifiability"); + case Cl::CM_Modifiable: + return MLV_Valid; + case Cl::CM_RValue: + llvm_unreachable("CM_RValue and CL_LValue don't match"); + case Cl::CM_Function: + return MLV_NotObjectType; case Cl::CM_LValueCast: llvm_unreachable("CM_LValueCast and CL_LValue don't match"); - case Cl::CM_NoSetterProperty: return MLV_NoSetterProperty; - case Cl::CM_ConstQualified: return MLV_ConstQualified; - case Cl::CM_ConstQualifiedField: return MLV_ConstQualifiedField; - case Cl::CM_ConstAddrSpace: return MLV_ConstAddrSpace; - case Cl::CM_ArrayType: return MLV_ArrayType; - case Cl::CM_IncompleteType: return MLV_IncompleteType; + case Cl::CM_NoSetterProperty: + return MLV_NoSetterProperty; + case Cl::CM_ConstQualified: + return MLV_ConstQualified; + case Cl::CM_ConstQualifiedField: + return MLV_ConstQualifiedField; + case Cl::CM_ConstAddrSpace: + return MLV_ConstAddrSpace; + case Cl::CM_ArrayType: + return MLV_ArrayType; + case Cl::CM_IncompleteType: + return MLV_IncompleteType; } llvm_unreachable("Unhandled modifiable type"); } Index: clang/lib/AST/ExprConcepts.cpp =================================================================== --- clang/lib/AST/ExprConcepts.cpp +++ clang/lib/AST/ExprConcepts.cpp @@ -31,12 +31,12 @@ using namespace clang; ConceptSpecializationExpr::ConceptSpecializationExpr( - const ASTContext &C, NestedNameSpecifierLoc NNS, + ASTContext const &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, - const ASTTemplateArgumentListInfo *ArgsAsWritten, + ASTTemplateArgumentListInfo const *ArgsAsWritten, ArrayRef ConvertedArgs, - const ConstraintSatisfaction *Satisfaction) + ConstraintSatisfaction const *Satisfaction) : Expr(ConceptSpecializationExprClass, C.BoolTy, VK_PRValue, OK_Ordinary), ConceptReference(NNS, TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept, ArgsAsWritten), @@ -48,18 +48,19 @@ setDependence(computeDependence(this, /*ValueDependent=*/!Satisfaction)); // Currently guaranteed by the fact concepts can only be at namespace-scope. - assert(!NestedNameSpec || - (!NestedNameSpec.getNestedNameSpecifier()->isInstantiationDependent() && - !NestedNameSpec.getNestedNameSpecifier() - ->containsUnexpandedParameterPack())); + assert( + !NestedNameSpec || + (!NestedNameSpec.getNestedNameSpecifier()->isInstantiationDependent() && + !NestedNameSpec.getNestedNameSpecifier() + ->containsUnexpandedParameterPack())); assert((!isValueDependent() || isInstantiationDependent()) && "should not be value-dependent"); } ConceptSpecializationExpr::ConceptSpecializationExpr(EmptyShell Empty, - unsigned NumTemplateArgs) + unsigned NumTemplateArgs) : Expr(ConceptSpecializationExprClass, Empty), ConceptReference(), - NumTemplateArgs(NumTemplateArgs) { } + NumTemplateArgs(NumTemplateArgs) {} void ConceptSpecializationExpr::setTemplateArguments( ArrayRef Converted) { @@ -68,28 +69,24 @@ getTrailingObjects()); } -ConceptSpecializationExpr * -ConceptSpecializationExpr::Create(const ASTContext &C, - NestedNameSpecifierLoc NNS, - SourceLocation TemplateKWLoc, - DeclarationNameInfo ConceptNameInfo, - NamedDecl *FoundDecl, - ConceptDecl *NamedConcept, - const ASTTemplateArgumentListInfo *ArgsAsWritten, - ArrayRef ConvertedArgs, - const ConstraintSatisfaction *Satisfaction) { - void *Buffer = C.Allocate(totalSizeToAlloc( - ConvertedArgs.size())); - return new (Buffer) ConceptSpecializationExpr(C, NNS, TemplateKWLoc, - ConceptNameInfo, FoundDecl, - NamedConcept, ArgsAsWritten, - ConvertedArgs, Satisfaction); +ConceptSpecializationExpr *ConceptSpecializationExpr::Create( + ASTContext const &C, NestedNameSpecifierLoc NNS, + SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, + NamedDecl *FoundDecl, ConceptDecl *NamedConcept, + ASTTemplateArgumentListInfo const *ArgsAsWritten, + ArrayRef ConvertedArgs, + ConstraintSatisfaction const *Satisfaction) { + void *Buffer = + C.Allocate(totalSizeToAlloc(ConvertedArgs.size())); + return new (Buffer) ConceptSpecializationExpr( + C, NNS, TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept, + ArgsAsWritten, ConvertedArgs, Satisfaction); } ConceptSpecializationExpr::ConceptSpecializationExpr( - const ASTContext &C, ConceptDecl *NamedConcept, + ASTContext const &C, ConceptDecl *NamedConcept, ArrayRef ConvertedArgs, - const ConstraintSatisfaction *Satisfaction, bool Dependent, + ConstraintSatisfaction const *Satisfaction, bool Dependent, bool ContainsUnexpandedParameterPack) : Expr(ConceptSpecializationExprClass, C.BoolTy, VK_PRValue, OK_Ordinary), ConceptReference(NestedNameSpecifierLoc(), SourceLocation(), @@ -110,35 +107,31 @@ setDependence(D); } -ConceptSpecializationExpr * -ConceptSpecializationExpr::Create(const ASTContext &C, - ConceptDecl *NamedConcept, - ArrayRef ConvertedArgs, - const ConstraintSatisfaction *Satisfaction, - bool Dependent, - bool ContainsUnexpandedParameterPack) { - void *Buffer = C.Allocate(totalSizeToAlloc( - ConvertedArgs.size())); - return new (Buffer) ConceptSpecializationExpr( - C, NamedConcept, ConvertedArgs, Satisfaction, Dependent, - ContainsUnexpandedParameterPack); +ConceptSpecializationExpr *ConceptSpecializationExpr::Create( + ASTContext const &C, ConceptDecl *NamedConcept, + ArrayRef ConvertedArgs, + ConstraintSatisfaction const *Satisfaction, bool Dependent, + bool ContainsUnexpandedParameterPack) { + void *Buffer = + C.Allocate(totalSizeToAlloc(ConvertedArgs.size())); + return new (Buffer) + ConceptSpecializationExpr(C, NamedConcept, ConvertedArgs, Satisfaction, + Dependent, ContainsUnexpandedParameterPack); } ConceptSpecializationExpr * ConceptSpecializationExpr::Create(ASTContext &C, EmptyShell Empty, unsigned NumTemplateArgs) { - void *Buffer = C.Allocate(totalSizeToAlloc( - NumTemplateArgs)); + void *Buffer = + C.Allocate(totalSizeToAlloc(NumTemplateArgs)); return new (Buffer) ConceptSpecializationExpr(Empty, NumTemplateArgs); } -const TypeConstraint * +TypeConstraint const * concepts::ExprRequirement::ReturnTypeRequirement::getTypeConstraint() const { assert(isTypeConstraint()); - auto TPL = - TypeConstraintInfo.getPointer().get(); - return cast(TPL->getParam(0)) - ->getTypeConstraint(); + auto TPL = TypeConstraintInfo.getPointer().get(); + return cast(TPL->getParam(0))->getTypeConstraint(); } RequiresExpr::RequiresExpr(ASTContext &C, SourceLocation RequiresKWLoc, @@ -187,15 +180,13 @@ RequiresExpr::RequiresExpr(ASTContext &C, EmptyShell Empty, unsigned NumLocalParameters, unsigned NumRequirements) - : Expr(RequiresExprClass, Empty), NumLocalParameters(NumLocalParameters), - NumRequirements(NumRequirements) { } + : Expr(RequiresExprClass, Empty), NumLocalParameters(NumLocalParameters), + NumRequirements(NumRequirements) {} -RequiresExpr * -RequiresExpr::Create(ASTContext &C, SourceLocation RequiresKWLoc, - RequiresExprBodyDecl *Body, - ArrayRef LocalParameters, - ArrayRef Requirements, - SourceLocation RBraceLoc) { +RequiresExpr *RequiresExpr::Create( + ASTContext &C, SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, + ArrayRef LocalParameters, + ArrayRef Requirements, SourceLocation RBraceLoc) { void *Mem = C.Allocate(totalSizeToAlloc( LocalParameters.size(), Requirements.size()), @@ -204,9 +195,9 @@ Requirements, RBraceLoc); } -RequiresExpr * -RequiresExpr::Create(ASTContext &C, EmptyShell Empty, - unsigned NumLocalParameters, unsigned NumRequirements) { +RequiresExpr *RequiresExpr::Create(ASTContext &C, EmptyShell Empty, + unsigned NumLocalParameters, + unsigned NumRequirements) { void *Mem = C.Allocate(totalSizeToAlloc( NumLocalParameters, NumRequirements), Index: clang/lib/AST/ExprConstant.cpp =================================================================== --- clang/lib/AST/ExprConstant.cpp +++ clang/lib/AST/ExprConstant.cpp @@ -64,1345 +64,1318 @@ using namespace clang; using llvm::APFixedPoint; +using llvm::APFloat; using llvm::APInt; using llvm::APSInt; -using llvm::APFloat; using llvm::FixedPointSemantics; using llvm::Optional; namespace { - struct LValue; - class CallStackFrame; - class EvalInfo; +struct LValue; +class CallStackFrame; +class EvalInfo; - using SourceLocExprScopeGuard = - CurrentSourceLocExprScope::SourceLocExprScopeGuard; +using SourceLocExprScopeGuard = + CurrentSourceLocExprScope::SourceLocExprScopeGuard; - static QualType getType(APValue::LValueBase B) { - return B.getType(); - } +static QualType getType(APValue::LValueBase B) { return B.getType(); } - /// Get an LValue path entry, which is known to not be an array index, as a - /// field declaration. - static const FieldDecl *getAsField(APValue::LValuePathEntry E) { - return dyn_cast_or_null(E.getAsBaseOrMember().getPointer()); - } - /// Get an LValue path entry, which is known to not be an array index, as a - /// base class declaration. - static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) { - return dyn_cast_or_null(E.getAsBaseOrMember().getPointer()); - } - /// Determine whether this LValue path entry for a base class names a virtual - /// base class. - static bool isVirtualBaseClass(APValue::LValuePathEntry E) { - return E.getAsBaseOrMember().getInt(); - } +/// Get an LValue path entry, which is known to not be an array index, as a +/// field declaration. +static FieldDecl const *getAsField(APValue::LValuePathEntry E) { + return dyn_cast_or_null(E.getAsBaseOrMember().getPointer()); +} +/// Get an LValue path entry, which is known to not be an array index, as a +/// base class declaration. +static CXXRecordDecl const *getAsBaseClass(APValue::LValuePathEntry E) { + return dyn_cast_or_null(E.getAsBaseOrMember().getPointer()); +} +/// Determine whether this LValue path entry for a base class names a virtual +/// base class. +static bool isVirtualBaseClass(APValue::LValuePathEntry E) { + return E.getAsBaseOrMember().getInt(); +} - /// Given an expression, determine the type used to store the result of - /// evaluating that expression. - static QualType getStorageType(const ASTContext &Ctx, const Expr *E) { - if (E->isPRValue()) - return E->getType(); - return Ctx.getLValueReferenceType(E->getType()); - } +/// Given an expression, determine the type used to store the result of +/// evaluating that expression. +static QualType getStorageType(ASTContext const &Ctx, Expr const *E) { + if (E->isPRValue()) + return E->getType(); + return Ctx.getLValueReferenceType(E->getType()); +} - /// Given a CallExpr, try to get the alloc_size attribute. May return null. - static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) { - if (const FunctionDecl *DirectCallee = CE->getDirectCallee()) - return DirectCallee->getAttr(); - if (const Decl *IndirectCallee = CE->getCalleeDecl()) - return IndirectCallee->getAttr(); +/// Given a CallExpr, try to get the alloc_size attribute. May return null. +static AllocSizeAttr const *getAllocSizeAttr(CallExpr const *CE) { + if (FunctionDecl const *DirectCallee = CE->getDirectCallee()) + return DirectCallee->getAttr(); + if (Decl const *IndirectCallee = CE->getCalleeDecl()) + return IndirectCallee->getAttr(); + return nullptr; +} + +/// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. +/// This will look through a single cast. +/// +/// Returns null if we couldn't unwrap a function with alloc_size. +static CallExpr const *tryUnwrapAllocSizeCall(Expr const *E) { + if (!E->getType()->isPointerType()) return nullptr; - } - /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr. - /// This will look through a single cast. - /// - /// Returns null if we couldn't unwrap a function with alloc_size. - static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) { - if (!E->getType()->isPointerType()) - return nullptr; + E = E->IgnoreParens(); + // If we're doing a variable assignment from e.g. malloc(N), there will + // probably be a cast of some kind. In exotic cases, we might also see a + // top-level ExprWithCleanups. Ignore them either way. + if (auto const *FE = dyn_cast(E)) + E = FE->getSubExpr()->IgnoreParens(); - E = E->IgnoreParens(); - // If we're doing a variable assignment from e.g. malloc(N), there will - // probably be a cast of some kind. In exotic cases, we might also see a - // top-level ExprWithCleanups. Ignore them either way. - if (const auto *FE = dyn_cast(E)) - E = FE->getSubExpr()->IgnoreParens(); + if (auto const *Cast = dyn_cast(E)) + E = Cast->getSubExpr()->IgnoreParens(); - if (const auto *Cast = dyn_cast(E)) - E = Cast->getSubExpr()->IgnoreParens(); + if (auto const *CE = dyn_cast(E)) + return getAllocSizeAttr(CE) ? CE : nullptr; + return nullptr; +} - if (const auto *CE = dyn_cast(E)) - return getAllocSizeAttr(CE) ? CE : nullptr; - return nullptr; - } +/// Determines whether or not the given Base contains a call to a function +/// with the alloc_size attribute. +static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { + auto const *E = Base.dyn_cast(); + return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); +} - /// Determines whether or not the given Base contains a call to a function - /// with the alloc_size attribute. - static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) { - const auto *E = Base.dyn_cast(); - return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E); +/// Determines whether the given kind of constant expression is only ever +/// used for name mangling. If so, it's permitted to reference things that we +/// can't generate code for (in particular, dllimported functions). +static bool isForManglingOnly(ConstantExprKind Kind) { + switch (Kind) { + case ConstantExprKind::Normal: + case ConstantExprKind::ClassTemplateArgument: + case ConstantExprKind::ImmediateInvocation: + // Note that non-type template arguments of class type are emitted as + // template parameter objects. + return false; + + case ConstantExprKind::NonClassTemplateArgument: + return true; } + llvm_unreachable("unknown ConstantExprKind"); +} - /// Determines whether the given kind of constant expression is only ever - /// used for name mangling. If so, it's permitted to reference things that we - /// can't generate code for (in particular, dllimported functions). - static bool isForManglingOnly(ConstantExprKind Kind) { - switch (Kind) { - case ConstantExprKind::Normal: - case ConstantExprKind::ClassTemplateArgument: - case ConstantExprKind::ImmediateInvocation: - // Note that non-type template arguments of class type are emitted as - // template parameter objects. - return false; +static bool isTemplateArgument(ConstantExprKind Kind) { + switch (Kind) { + case ConstantExprKind::Normal: + case ConstantExprKind::ImmediateInvocation: + return false; - case ConstantExprKind::NonClassTemplateArgument: - return true; - } - llvm_unreachable("unknown ConstantExprKind"); + case ConstantExprKind::ClassTemplateArgument: + case ConstantExprKind::NonClassTemplateArgument: + return true; } + llvm_unreachable("unknown ConstantExprKind"); +} - static bool isTemplateArgument(ConstantExprKind Kind) { - switch (Kind) { - case ConstantExprKind::Normal: - case ConstantExprKind::ImmediateInvocation: - return false; +/// The bound to claim that an array of unknown bound has. +/// The value in MostDerivedArraySize is undefined in this case. So, set it +/// to an arbitrary value that's likely to loudly break things if it's used. +static const uint64_t AssumedSizeForUnsizedArray = + std::numeric_limits::max() / 2; - case ConstantExprKind::ClassTemplateArgument: - case ConstantExprKind::NonClassTemplateArgument: - return true; - } - llvm_unreachable("unknown ConstantExprKind"); - } - - /// The bound to claim that an array of unknown bound has. - /// The value in MostDerivedArraySize is undefined in this case. So, set it - /// to an arbitrary value that's likely to loudly break things if it's used. - static const uint64_t AssumedSizeForUnsizedArray = - std::numeric_limits::max() / 2; - - /// Determines if an LValue with the given LValueBase will have an unsized - /// array in its designator. - /// Find the path length and type of the most-derived subobject in the given - /// path, and find the size of the containing array, if any. - static unsigned - findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, - ArrayRef Path, - uint64_t &ArraySize, QualType &Type, bool &IsArray, - bool &FirstEntryIsUnsizedArray) { - // This only accepts LValueBases from APValues, and APValues don't support - // arrays that lack size info. - assert(!isBaseAnAllocSizeCall(Base) && - "Unsized arrays shouldn't appear here"); - unsigned MostDerivedLength = 0; - Type = getType(Base); - - for (unsigned I = 0, N = Path.size(); I != N; ++I) { - if (Type->isArrayType()) { - const ArrayType *AT = Ctx.getAsArrayType(Type); - Type = AT->getElementType(); - MostDerivedLength = I + 1; - IsArray = true; - - if (auto *CAT = dyn_cast(AT)) { - ArraySize = CAT->getSize().getZExtValue(); - } else { - assert(I == 0 && "unexpected unsized array designator"); - FirstEntryIsUnsizedArray = true; - ArraySize = AssumedSizeForUnsizedArray; - } - } else if (Type->isAnyComplexType()) { - const ComplexType *CT = Type->castAs(); - Type = CT->getElementType(); - ArraySize = 2; - MostDerivedLength = I + 1; - IsArray = true; - } else if (const FieldDecl *FD = getAsField(Path[I])) { - Type = FD->getType(); - ArraySize = 0; - MostDerivedLength = I + 1; - IsArray = false; +/// Determines if an LValue with the given LValueBase will have an unsized +/// array in its designator. +/// Find the path length and type of the most-derived subobject in the given +/// path, and find the size of the containing array, if any. +static unsigned +findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base, + ArrayRef Path, + uint64_t &ArraySize, QualType &Type, bool &IsArray, + bool &FirstEntryIsUnsizedArray) { + // This only accepts LValueBases from APValues, and APValues don't support + // arrays that lack size info. + assert(!isBaseAnAllocSizeCall(Base) && + "Unsized arrays shouldn't appear here"); + unsigned MostDerivedLength = 0; + Type = getType(Base); + + for (unsigned I = 0, N = Path.size(); I != N; ++I) { + if (Type->isArrayType()) { + ArrayType const *AT = Ctx.getAsArrayType(Type); + Type = AT->getElementType(); + MostDerivedLength = I + 1; + IsArray = true; + + if (auto *CAT = dyn_cast(AT)) { + ArraySize = CAT->getSize().getZExtValue(); } else { - // Path[I] describes a base class. - ArraySize = 0; - IsArray = false; - } - } - return MostDerivedLength; - } - - /// A path from a glvalue to a subobject of that glvalue. - struct SubobjectDesignator { - /// True if the subobject was named in a manner not supported by C++11. Such - /// lvalues can still be folded, but they are not core constant expressions - /// and we cannot perform lvalue-to-rvalue conversions on them. - unsigned Invalid : 1; - - /// Is this a pointer one past the end of an object? - unsigned IsOnePastTheEnd : 1; - - /// Indicator of whether the first entry is an unsized array. - unsigned FirstEntryIsAnUnsizedArray : 1; - - /// Indicator of whether the most-derived object is an array element. - unsigned MostDerivedIsArrayElement : 1; - - /// The length of the path to the most-derived object of which this is a - /// subobject. - unsigned MostDerivedPathLength : 28; - - /// The size of the array of which the most-derived object is an element. - /// This will always be 0 if the most-derived object is not an array - /// element. 0 is not an indicator of whether or not the most-derived object - /// is an array, however, because 0-length arrays are allowed. - /// - /// If the current array is an unsized array, the value of this is - /// undefined. - uint64_t MostDerivedArraySize; - - /// The type of the most derived object referred to by this address. - QualType MostDerivedType; - - typedef APValue::LValuePathEntry PathEntry; - - /// The entries on the path from the glvalue to the designated subobject. - SmallVector Entries; - - SubobjectDesignator() : Invalid(true) {} - - explicit SubobjectDesignator(QualType T) - : Invalid(false), IsOnePastTheEnd(false), - FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), - MostDerivedPathLength(0), MostDerivedArraySize(0), - MostDerivedType(T) {} - - SubobjectDesignator(ASTContext &Ctx, const APValue &V) - : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), - FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), - MostDerivedPathLength(0), MostDerivedArraySize(0) { - assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); - if (!Invalid) { - IsOnePastTheEnd = V.isLValueOnePastTheEnd(); - ArrayRef VEntries = V.getLValuePath(); - Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); - if (V.getLValueBase()) { - bool IsArray = false; - bool FirstIsUnsizedArray = false; - MostDerivedPathLength = findMostDerivedSubobject( - Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, - MostDerivedType, IsArray, FirstIsUnsizedArray); - MostDerivedIsArrayElement = IsArray; - FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; - } - } + assert(I == 0 && "unexpected unsized array designator"); + FirstEntryIsUnsizedArray = true; + ArraySize = AssumedSizeForUnsizedArray; + } + } else if (Type->isAnyComplexType()) { + ComplexType const *CT = Type->castAs(); + Type = CT->getElementType(); + ArraySize = 2; + MostDerivedLength = I + 1; + IsArray = true; + } else if (FieldDecl const *FD = getAsField(Path[I])) { + Type = FD->getType(); + ArraySize = 0; + MostDerivedLength = I + 1; + IsArray = false; + } else { + // Path[I] describes a base class. + ArraySize = 0; + IsArray = false; } + } + return MostDerivedLength; +} - void truncate(ASTContext &Ctx, APValue::LValueBase Base, - unsigned NewLength) { - if (Invalid) - return; +/// A path from a glvalue to a subobject of that glvalue. +struct SubobjectDesignator { + /// True if the subobject was named in a manner not supported by C++11. Such + /// lvalues can still be folded, but they are not core constant expressions + /// and we cannot perform lvalue-to-rvalue conversions on them. + unsigned Invalid : 1; - assert(Base && "cannot truncate path for null pointer"); - assert(NewLength <= Entries.size() && "not a truncation"); + /// Is this a pointer one past the end of an object? + unsigned IsOnePastTheEnd : 1; - if (NewLength == Entries.size()) - return; - Entries.resize(NewLength); + /// Indicator of whether the first entry is an unsized array. + unsigned FirstEntryIsAnUnsizedArray : 1; - bool IsArray = false; - bool FirstIsUnsizedArray = false; - MostDerivedPathLength = findMostDerivedSubobject( - Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray, - FirstIsUnsizedArray); - MostDerivedIsArrayElement = IsArray; - FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; - } + /// Indicator of whether the most-derived object is an array element. + unsigned MostDerivedIsArrayElement : 1; - void setInvalid() { - Invalid = true; - Entries.clear(); - } + /// The length of the path to the most-derived object of which this is a + /// subobject. + unsigned MostDerivedPathLength : 28; - /// Determine whether the most derived subobject is an array without a - /// known bound. - bool isMostDerivedAnUnsizedArray() const { - assert(!Invalid && "Calling this makes no sense on invalid designators"); - return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; - } + /// The size of the array of which the most-derived object is an element. + /// This will always be 0 if the most-derived object is not an array + /// element. 0 is not an indicator of whether or not the most-derived object + /// is an array, however, because 0-length arrays are allowed. + /// + /// If the current array is an unsized array, the value of this is + /// undefined. + uint64_t MostDerivedArraySize; - /// Determine what the most derived array's size is. Results in an assertion - /// failure if the most derived array lacks a size. - uint64_t getMostDerivedArraySize() const { - assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); - return MostDerivedArraySize; - } + /// The type of the most derived object referred to by this address. + QualType MostDerivedType; - /// Determine whether this is a one-past-the-end pointer. - bool isOnePastTheEnd() const { - assert(!Invalid); - if (IsOnePastTheEnd) - return true; - if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && - Entries[MostDerivedPathLength - 1].getAsArrayIndex() == - MostDerivedArraySize) - return true; - return false; - } + typedef APValue::LValuePathEntry PathEntry; - /// Get the range of valid index adjustments in the form - /// {maximum value that can be subtracted from this pointer, - /// maximum value that can be added to this pointer} - std::pair validIndexAdjustments() { - if (Invalid || isMostDerivedAnUnsizedArray()) - return {0, 0}; + /// The entries on the path from the glvalue to the designated subobject. + SmallVector Entries; - // [expr.add]p4: For the purposes of these operators, a pointer to a - // nonarray object behaves the same as a pointer to the first element of - // an array of length one with the type of the object as its element type. - bool IsArray = MostDerivedPathLength == Entries.size() && - MostDerivedIsArrayElement; - uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() - : (uint64_t)IsOnePastTheEnd; - uint64_t ArraySize = - IsArray ? getMostDerivedArraySize() : (uint64_t)1; - return {ArrayIndex, ArraySize - ArrayIndex}; - } + SubobjectDesignator() : Invalid(true) {} - /// Check that this refers to a valid subobject. - bool isValidSubobject() const { - if (Invalid) - return false; - return !isOnePastTheEnd(); - } - /// Check that this refers to a valid subobject, and if not, produce a - /// relevant diagnostic and set the designator as invalid. - bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK); + explicit SubobjectDesignator(QualType T) + : Invalid(false), IsOnePastTheEnd(false), + FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), + MostDerivedPathLength(0), MostDerivedArraySize(0), MostDerivedType(T) {} - /// Get the type of the designated object. - QualType getType(ASTContext &Ctx) const { - assert(!Invalid && "invalid designator has no subobject type"); - return MostDerivedPathLength == Entries.size() - ? MostDerivedType - : Ctx.getRecordType(getAsBaseClass(Entries.back())); + SubobjectDesignator(ASTContext &Ctx, APValue const &V) + : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false), + FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false), + MostDerivedPathLength(0), MostDerivedArraySize(0) { + assert(V.isLValue() && "Non-LValue used to make an LValue designator?"); + if (!Invalid) { + IsOnePastTheEnd = V.isLValueOnePastTheEnd(); + ArrayRef VEntries = V.getLValuePath(); + Entries.insert(Entries.end(), VEntries.begin(), VEntries.end()); + if (V.getLValueBase()) { + bool IsArray = false; + bool FirstIsUnsizedArray = false; + MostDerivedPathLength = findMostDerivedSubobject( + Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize, + MostDerivedType, IsArray, FirstIsUnsizedArray); + MostDerivedIsArrayElement = IsArray; + FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; + } } + } - /// Update this designator to refer to the first element within this array. - void addArrayUnchecked(const ConstantArrayType *CAT) { - Entries.push_back(PathEntry::ArrayIndex(0)); + void truncate(ASTContext &Ctx, APValue::LValueBase Base, unsigned NewLength) { + if (Invalid) + return; - // This is a most-derived object. - MostDerivedType = CAT->getElementType(); - MostDerivedIsArrayElement = true; - MostDerivedArraySize = CAT->getSize().getZExtValue(); - MostDerivedPathLength = Entries.size(); - } - /// Update this designator to refer to the first element within the array of - /// elements of type T. This is an array of unknown size. - void addUnsizedArrayUnchecked(QualType ElemTy) { - Entries.push_back(PathEntry::ArrayIndex(0)); - - MostDerivedType = ElemTy; - MostDerivedIsArrayElement = true; - // The value in MostDerivedArraySize is undefined in this case. So, set it - // to an arbitrary value that's likely to loudly break things if it's - // used. - MostDerivedArraySize = AssumedSizeForUnsizedArray; + assert(Base && "cannot truncate path for null pointer"); + assert(NewLength <= Entries.size() && "not a truncation"); + + if (NewLength == Entries.size()) + return; + Entries.resize(NewLength); + + bool IsArray = false; + bool FirstIsUnsizedArray = false; + MostDerivedPathLength = + findMostDerivedSubobject(Ctx, Base, Entries, MostDerivedArraySize, + MostDerivedType, IsArray, FirstIsUnsizedArray); + MostDerivedIsArrayElement = IsArray; + FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray; + } + + void setInvalid() { + Invalid = true; + Entries.clear(); + } + + /// Determine whether the most derived subobject is an array without a + /// known bound. + bool isMostDerivedAnUnsizedArray() const { + assert(!Invalid && "Calling this makes no sense on invalid designators"); + return Entries.size() == 1 && FirstEntryIsAnUnsizedArray; + } + + /// Determine what the most derived array's size is. Results in an assertion + /// failure if the most derived array lacks a size. + uint64_t getMostDerivedArraySize() const { + assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size"); + return MostDerivedArraySize; + } + + /// Determine whether this is a one-past-the-end pointer. + bool isOnePastTheEnd() const { + assert(!Invalid); + if (IsOnePastTheEnd) + return true; + if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement && + Entries[MostDerivedPathLength - 1].getAsArrayIndex() == + MostDerivedArraySize) + return true; + return false; + } + + /// Get the range of valid index adjustments in the form + /// {maximum value that can be subtracted from this pointer, + /// maximum value that can be added to this pointer} + std::pair validIndexAdjustments() { + if (Invalid || isMostDerivedAnUnsizedArray()) + return {0, 0}; + + // [expr.add]p4: For the purposes of these operators, a pointer to a + // nonarray object behaves the same as a pointer to the first element of + // an array of length one with the type of the object as its element type. + bool IsArray = + MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement; + uint64_t ArrayIndex = + IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd; + uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1; + return {ArrayIndex, ArraySize - ArrayIndex}; + } + + /// Check that this refers to a valid subobject. + bool isValidSubobject() const { + if (Invalid) + return false; + return !isOnePastTheEnd(); + } + /// Check that this refers to a valid subobject, and if not, produce a + /// relevant diagnostic and set the designator as invalid. + bool checkSubobject(EvalInfo &Info, Expr const *E, CheckSubobjectKind CSK); + + /// Get the type of the designated object. + QualType getType(ASTContext &Ctx) const { + assert(!Invalid && "invalid designator has no subobject type"); + return MostDerivedPathLength == Entries.size() + ? MostDerivedType + : Ctx.getRecordType(getAsBaseClass(Entries.back())); + } + + /// Update this designator to refer to the first element within this array. + void addArrayUnchecked(ConstantArrayType const *CAT) { + Entries.push_back(PathEntry::ArrayIndex(0)); + + // This is a most-derived object. + MostDerivedType = CAT->getElementType(); + MostDerivedIsArrayElement = true; + MostDerivedArraySize = CAT->getSize().getZExtValue(); + MostDerivedPathLength = Entries.size(); + } + /// Update this designator to refer to the first element within the array of + /// elements of type T. This is an array of unknown size. + void addUnsizedArrayUnchecked(QualType ElemTy) { + Entries.push_back(PathEntry::ArrayIndex(0)); + + MostDerivedType = ElemTy; + MostDerivedIsArrayElement = true; + // The value in MostDerivedArraySize is undefined in this case. So, set it + // to an arbitrary value that's likely to loudly break things if it's + // used. + MostDerivedArraySize = AssumedSizeForUnsizedArray; + MostDerivedPathLength = Entries.size(); + } + /// Update this designator to refer to the given base or member of this + /// object. + void addDeclUnchecked(Decl const *D, bool Virtual = false) { + Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); + + // If this isn't a base class, it's a new most-derived object. + if (FieldDecl const *FD = dyn_cast(D)) { + MostDerivedType = FD->getType(); + MostDerivedIsArrayElement = false; + MostDerivedArraySize = 0; MostDerivedPathLength = Entries.size(); } - /// Update this designator to refer to the given base or member of this - /// object. - void addDeclUnchecked(const Decl *D, bool Virtual = false) { - Entries.push_back(APValue::BaseOrMemberType(D, Virtual)); - - // If this isn't a base class, it's a new most-derived object. - if (const FieldDecl *FD = dyn_cast(D)) { - MostDerivedType = FD->getType(); - MostDerivedIsArrayElement = false; - MostDerivedArraySize = 0; - MostDerivedPathLength = Entries.size(); - } - } - /// Update this designator to refer to the given complex component. - void addComplexUnchecked(QualType EltTy, bool Imag) { - Entries.push_back(PathEntry::ArrayIndex(Imag)); + } + /// Update this designator to refer to the given complex component. + void addComplexUnchecked(QualType EltTy, bool Imag) { + Entries.push_back(PathEntry::ArrayIndex(Imag)); - // This is technically a most-derived object, though in practice this - // is unlikely to matter. - MostDerivedType = EltTy; - MostDerivedIsArrayElement = true; - MostDerivedArraySize = 2; - MostDerivedPathLength = Entries.size(); + // This is technically a most-derived object, though in practice this + // is unlikely to matter. + MostDerivedType = EltTy; + MostDerivedIsArrayElement = true; + MostDerivedArraySize = 2; + MostDerivedPathLength = Entries.size(); + } + void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, Expr const *E); + void diagnosePointerArithmetic(EvalInfo &Info, Expr const *E, + APSInt const &N); + /// Add N to the address of this subobject. + void adjustIndex(EvalInfo &Info, Expr const *E, APSInt N) { + if (Invalid || !N) + return; + uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); + if (isMostDerivedAnUnsizedArray()) { + diagnoseUnsizedArrayPointerArithmetic(Info, E); + // Can't verify -- trust that the user is doing the right thing (or if + // not, trust that the caller will catch the bad behavior). + // FIXME: Should we reject if this overflows, at least? + Entries.back() = + PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN); + return; } - void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E); - void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, - const APSInt &N); - /// Add N to the address of this subobject. - void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) { - if (Invalid || !N) return; - uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue(); - if (isMostDerivedAnUnsizedArray()) { - diagnoseUnsizedArrayPointerArithmetic(Info, E); - // Can't verify -- trust that the user is doing the right thing (or if - // not, trust that the caller will catch the bad behavior). - // FIXME: Should we reject if this overflows, at least? - Entries.back() = PathEntry::ArrayIndex( - Entries.back().getAsArrayIndex() + TruncatedN); - return; - } - // [expr.add]p4: For the purposes of these operators, a pointer to a - // nonarray object behaves the same as a pointer to the first element of - // an array of length one with the type of the object as its element type. - bool IsArray = MostDerivedPathLength == Entries.size() && - MostDerivedIsArrayElement; - uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex() - : (uint64_t)IsOnePastTheEnd; - uint64_t ArraySize = - IsArray ? getMostDerivedArraySize() : (uint64_t)1; - - if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { - // Calculate the actual index in a wide enough type, so we can include - // it in the note. - N = N.extend(std::max(N.getBitWidth() + 1, 65)); - (llvm::APInt&)N += ArrayIndex; - assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); - diagnosePointerArithmetic(Info, E, N); - setInvalid(); - return; - } + // [expr.add]p4: For the purposes of these operators, a pointer to a + // nonarray object behaves the same as a pointer to the first element of + // an array of length one with the type of the object as its element type. + bool IsArray = + MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement; + uint64_t ArrayIndex = + IsArray ? Entries.back().getAsArrayIndex() : (uint64_t)IsOnePastTheEnd; + uint64_t ArraySize = IsArray ? getMostDerivedArraySize() : (uint64_t)1; + + if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) { + // Calculate the actual index in a wide enough type, so we can include + // it in the note. + N = N.extend(std::max(N.getBitWidth() + 1, 65)); + (llvm::APInt &)N += ArrayIndex; + assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index"); + diagnosePointerArithmetic(Info, E, N); + setInvalid(); + return; + } - ArrayIndex += TruncatedN; - assert(ArrayIndex <= ArraySize && - "bounds check succeeded for out-of-bounds index"); + ArrayIndex += TruncatedN; + assert(ArrayIndex <= ArraySize && + "bounds check succeeded for out-of-bounds index"); - if (IsArray) - Entries.back() = PathEntry::ArrayIndex(ArrayIndex); - else - IsOnePastTheEnd = (ArrayIndex != 0); - } - }; + if (IsArray) + Entries.back() = PathEntry::ArrayIndex(ArrayIndex); + else + IsOnePastTheEnd = (ArrayIndex != 0); + } +}; - /// A scope at the end of which an object can need to be destroyed. - enum class ScopeKind { - Block, - FullExpression, - Call - }; +/// A scope at the end of which an object can need to be destroyed. +enum class ScopeKind { Block, FullExpression, Call }; + +/// A reference to a particular call and its arguments. +struct CallRef { + CallRef() : OrigCallee(), CallIndex(0), Version() {} + CallRef(FunctionDecl const *Callee, unsigned CallIndex, unsigned Version) + : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} + + explicit operator bool() const { return OrigCallee; } + + /// Get the parameter that the caller initialized, corresponding to the + /// given parameter in the callee. + ParmVarDecl const *getOrigParam(ParmVarDecl const *PVD) const { + return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) + : PVD; + } + + /// The callee at the point where the arguments were evaluated. This might + /// be different from the actual callee (a different redeclaration, or a + /// virtual override), but this function's parameters are the ones that + /// appear in the parameter map. + FunctionDecl const *OrigCallee; + /// The call index of the frame that holds the argument values. + unsigned CallIndex; + /// The version of the parameters corresponding to this call. + unsigned Version; +}; - /// A reference to a particular call and its arguments. - struct CallRef { - CallRef() : OrigCallee(), CallIndex(0), Version() {} - CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version) - : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {} - - explicit operator bool() const { return OrigCallee; } - - /// Get the parameter that the caller initialized, corresponding to the - /// given parameter in the callee. - const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const { - return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex()) - : PVD; - } - - /// The callee at the point where the arguments were evaluated. This might - /// be different from the actual callee (a different redeclaration, or a - /// virtual override), but this function's parameters are the ones that - /// appear in the parameter map. - const FunctionDecl *OrigCallee; - /// The call index of the frame that holds the argument values. - unsigned CallIndex; - /// The version of the parameters corresponding to this call. - unsigned Version; - }; +/// A stack frame in the constexpr call stack. +class CallStackFrame : public interp::Frame { +public: + EvalInfo &Info; - /// A stack frame in the constexpr call stack. - class CallStackFrame : public interp::Frame { - public: - EvalInfo &Info; + /// Parent - The caller of this stack frame. + CallStackFrame *Caller; - /// Parent - The caller of this stack frame. - CallStackFrame *Caller; + /// Callee - The function which was called. + FunctionDecl const *Callee; - /// Callee - The function which was called. - const FunctionDecl *Callee; + /// This - The binding for the this pointer in this call, if any. + LValue const *This; - /// This - The binding for the this pointer in this call, if any. - const LValue *This; + /// Information on how to find the arguments to this call. Our arguments + /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a + /// key and this value as the version. + CallRef Arguments; - /// Information on how to find the arguments to this call. Our arguments - /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a - /// key and this value as the version. - CallRef Arguments; + /// Source location information about the default argument or default + /// initializer expression we're evaluating, if any. + CurrentSourceLocExprScope CurSourceLocExprScope; - /// Source location information about the default argument or default - /// initializer expression we're evaluating, if any. - CurrentSourceLocExprScope CurSourceLocExprScope; + // Note that we intentionally use std::map here so that references to + // values are stable. + typedef std::pair MapKeyTy; + typedef std::map MapTy; + /// Temporaries - Temporary lvalues materialized within this stack frame. + MapTy Temporaries; - // Note that we intentionally use std::map here so that references to - // values are stable. - typedef std::pair MapKeyTy; - typedef std::map MapTy; - /// Temporaries - Temporary lvalues materialized within this stack frame. - MapTy Temporaries; + /// CallLoc - The location of the call expression for this call. + SourceLocation CallLoc; - /// CallLoc - The location of the call expression for this call. - SourceLocation CallLoc; + /// Index - The call index of this call. + unsigned Index; - /// Index - The call index of this call. - unsigned Index; + /// The stack of integers for tracking version numbers for temporaries. + SmallVector TempVersionStack = {1}; + unsigned CurTempVersion = TempVersionStack.back(); - /// The stack of integers for tracking version numbers for temporaries. - SmallVector TempVersionStack = {1}; - unsigned CurTempVersion = TempVersionStack.back(); + unsigned getTempVersion() const { return TempVersionStack.back(); } - unsigned getTempVersion() const { return TempVersionStack.back(); } + void pushTempVersion() { TempVersionStack.push_back(++CurTempVersion); } - void pushTempVersion() { - TempVersionStack.push_back(++CurTempVersion); - } + void popTempVersion() { TempVersionStack.pop_back(); } - void popTempVersion() { - TempVersionStack.pop_back(); - } + CallRef createCall(FunctionDecl const *Callee) { + return {Callee, Index, ++CurTempVersion}; + } - CallRef createCall(const FunctionDecl *Callee) { - return {Callee, Index, ++CurTempVersion}; - } + // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact + // on the overall stack usage of deeply-recursing constexpr evaluations. + // (We should cache this map rather than recomputing it repeatedly.) + // But let's try this and see how it goes; we can look into caching the map + // as a later change. - // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact - // on the overall stack usage of deeply-recursing constexpr evaluations. - // (We should cache this map rather than recomputing it repeatedly.) - // But let's try this and see how it goes; we can look into caching the map - // as a later change. + /// LambdaCaptureFields - Mapping from captured variables/this to + /// corresponding data members in the closure class. + llvm::DenseMap LambdaCaptureFields; + FieldDecl *LambdaThisCaptureField; - /// LambdaCaptureFields - Mapping from captured variables/this to - /// corresponding data members in the closure class. - llvm::DenseMap LambdaCaptureFields; - FieldDecl *LambdaThisCaptureField; + CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, + FunctionDecl const *Callee, LValue const *This, + CallRef Arguments); + ~CallStackFrame(); - CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, - const FunctionDecl *Callee, const LValue *This, - CallRef Arguments); - ~CallStackFrame(); + // Return the temporary for Key whose version number is Version. + APValue *getTemporary(void const *Key, unsigned Version) { + MapKeyTy KV(Key, Version); + auto LB = Temporaries.lower_bound(KV); + if (LB != Temporaries.end() && LB->first == KV) + return &LB->second; + // Pair (Key,Version) wasn't found in the map. Check that no elements + // in the map have 'Key' as their key. + assert((LB == Temporaries.end() || LB->first.first != Key) && + (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && + "Element with key 'Key' found in map"); + return nullptr; + } - // Return the temporary for Key whose version number is Version. - APValue *getTemporary(const void *Key, unsigned Version) { - MapKeyTy KV(Key, Version); - auto LB = Temporaries.lower_bound(KV); - if (LB != Temporaries.end() && LB->first == KV) - return &LB->second; - // Pair (Key,Version) wasn't found in the map. Check that no elements - // in the map have 'Key' as their key. - assert((LB == Temporaries.end() || LB->first.first != Key) && - (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) && - "Element with key 'Key' found in map"); - return nullptr; - } + // Return the current temporary for Key in the map. + APValue *getCurrentTemporary(void const *Key) { + auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); + if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) + return &std::prev(UB)->second; + return nullptr; + } - // Return the current temporary for Key in the map. - APValue *getCurrentTemporary(const void *Key) { - auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); - if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) - return &std::prev(UB)->second; - return nullptr; - } + // Return the version number of the current temporary for Key. + unsigned getCurrentTemporaryVersion(void const *Key) const { + auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); + if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) + return std::prev(UB)->first.second; + return 0; + } - // Return the version number of the current temporary for Key. - unsigned getCurrentTemporaryVersion(const void *Key) const { - auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX)); - if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key) - return std::prev(UB)->first.second; - return 0; - } + /// Allocate storage for an object of type T in this stack frame. + /// Populates LV with a handle to the created object. Key identifies + /// the temporary within the stack frame, and must not be reused without + /// bumping the temporary version number. + template + APValue &createTemporary(KeyT const *Key, QualType T, ScopeKind Scope, + LValue &LV); - /// Allocate storage for an object of type T in this stack frame. - /// Populates LV with a handle to the created object. Key identifies - /// the temporary within the stack frame, and must not be reused without - /// bumping the temporary version number. - template - APValue &createTemporary(const KeyT *Key, QualType T, - ScopeKind Scope, LValue &LV); + /// Allocate storage for a parameter of a function call made in this frame. + APValue &createParam(CallRef Args, ParmVarDecl const *PVD, LValue &LV); - /// Allocate storage for a parameter of a function call made in this frame. - APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV); + void describe(llvm::raw_ostream &OS) override; - void describe(llvm::raw_ostream &OS) override; + Frame *getCaller() const override { return Caller; } + SourceLocation getCallLocation() const override { return CallLoc; } + FunctionDecl const *getCallee() const override { return Callee; } - Frame *getCaller() const override { return Caller; } - SourceLocation getCallLocation() const override { return CallLoc; } - const FunctionDecl *getCallee() const override { return Callee; } + bool isStdFunction() const { + for (DeclContext const *DC = Callee; DC; DC = DC->getParent()) + if (DC->isStdNamespace()) + return true; + return false; + } - bool isStdFunction() const { - for (const DeclContext *DC = Callee; DC; DC = DC->getParent()) - if (DC->isStdNamespace()) - return true; - return false; - } +private: + APValue &createLocal(APValue::LValueBase Base, void const *Key, QualType T, + ScopeKind Scope); +}; - private: - APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T, - ScopeKind Scope); - }; +/// Temporarily override 'this'. +class ThisOverrideRAII { +public: + ThisOverrideRAII(CallStackFrame &Frame, LValue const *NewThis, bool Enable) + : Frame(Frame), OldThis(Frame.This) { + if (Enable) + Frame.This = NewThis; + } + ~ThisOverrideRAII() { Frame.This = OldThis; } - /// Temporarily override 'this'. - class ThisOverrideRAII { - public: - ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable) - : Frame(Frame), OldThis(Frame.This) { - if (Enable) - Frame.This = NewThis; - } - ~ThisOverrideRAII() { - Frame.This = OldThis; - } - private: - CallStackFrame &Frame; - const LValue *OldThis; - }; -} +private: + CallStackFrame &Frame; + LValue const *OldThis; +}; +} // namespace -static bool HandleDestruction(EvalInfo &Info, const Expr *E, - const LValue &This, QualType ThisType); +static bool HandleDestruction(EvalInfo &Info, Expr const *E, LValue const &This, + QualType ThisType); static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc, APValue::LValueBase LVBase, APValue &Value, QualType T); namespace { - /// A cleanup, and a flag indicating whether it is lifetime-extended. - class Cleanup { - llvm::PointerIntPair Value; - APValue::LValueBase Base; - QualType T; +/// A cleanup, and a flag indicating whether it is lifetime-extended. +class Cleanup { + llvm::PointerIntPair Value; + APValue::LValueBase Base; + QualType T; - public: - Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, - ScopeKind Scope) - : Value(Val, Scope), Base(Base), T(T) {} - - /// Determine whether this cleanup should be performed at the end of the - /// given kind of scope. - bool isDestroyedAtEndOf(ScopeKind K) const { - return (int)Value.getInt() >= (int)K; - } - bool endLifetime(EvalInfo &Info, bool RunDestructors) { - if (RunDestructors) { - SourceLocation Loc; - if (const ValueDecl *VD = Base.dyn_cast()) - Loc = VD->getLocation(); - else if (const Expr *E = Base.dyn_cast()) - Loc = E->getExprLoc(); - return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); - } - *Value.getPointer() = APValue(); - return true; - } +public: + Cleanup(APValue *Val, APValue::LValueBase Base, QualType T, ScopeKind Scope) + : Value(Val, Scope), Base(Base), T(T) {} - bool hasSideEffect() { - return T.isDestructedType(); + /// Determine whether this cleanup should be performed at the end of the + /// given kind of scope. + bool isDestroyedAtEndOf(ScopeKind K) const { + return (int)Value.getInt() >= (int)K; + } + bool endLifetime(EvalInfo &Info, bool RunDestructors) { + if (RunDestructors) { + SourceLocation Loc; + if (ValueDecl const *VD = Base.dyn_cast()) + Loc = VD->getLocation(); + else if (Expr const *E = Base.dyn_cast()) + Loc = E->getExprLoc(); + return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T); } - }; + *Value.getPointer() = APValue(); + return true; + } - /// A reference to an object whose construction we are currently evaluating. - struct ObjectUnderConstruction { - APValue::LValueBase Base; - ArrayRef Path; - friend bool operator==(const ObjectUnderConstruction &LHS, - const ObjectUnderConstruction &RHS) { - return LHS.Base == RHS.Base && LHS.Path == RHS.Path; - } - friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) { - return llvm::hash_combine(Obj.Base, Obj.Path); - } - }; - enum class ConstructionPhase { - None, - Bases, - AfterBases, - AfterFields, - Destroying, - DestroyingBases - }; -} + bool hasSideEffect() { return T.isDestructedType(); } +}; + +/// A reference to an object whose construction we are currently evaluating. +struct ObjectUnderConstruction { + APValue::LValueBase Base; + ArrayRef Path; + friend bool operator==(ObjectUnderConstruction const &LHS, + ObjectUnderConstruction const &RHS) { + return LHS.Base == RHS.Base && LHS.Path == RHS.Path; + } + friend llvm::hash_code hash_value(ObjectUnderConstruction const &Obj) { + return llvm::hash_combine(Obj.Base, Obj.Path); + } +}; +enum class ConstructionPhase { + None, + Bases, + AfterBases, + AfterFields, + Destroying, + DestroyingBases +}; +} // namespace namespace llvm { -template<> struct DenseMapInfo { +template <> struct DenseMapInfo { using Base = DenseMapInfo; static ObjectUnderConstruction getEmptyKey() { - return {Base::getEmptyKey(), {}}; } + return {Base::getEmptyKey(), {}}; + } static ObjectUnderConstruction getTombstoneKey() { return {Base::getTombstoneKey(), {}}; } - static unsigned getHashValue(const ObjectUnderConstruction &Object) { + static unsigned getHashValue(ObjectUnderConstruction const &Object) { return hash_value(Object); } - static bool isEqual(const ObjectUnderConstruction &LHS, - const ObjectUnderConstruction &RHS) { + static bool isEqual(ObjectUnderConstruction const &LHS, + ObjectUnderConstruction const &RHS) { return LHS == RHS; } }; -} +} // namespace llvm namespace { - /// A dynamically-allocated heap object. - struct DynAlloc { - /// The value of this heap-allocated object. - APValue Value; - /// The allocating expression; used for diagnostics. Either a CXXNewExpr - /// or a CallExpr (the latter is for direct calls to operator new inside - /// std::allocator::allocate). - const Expr *AllocExpr = nullptr; - - enum Kind { - New, - ArrayNew, - StdAllocator - }; - - /// Get the kind of the allocation. This must match between allocation - /// and deallocation. - Kind getKind() const { - if (auto *NE = dyn_cast(AllocExpr)) - return NE->isArray() ? ArrayNew : New; - assert(isa(AllocExpr)); - return StdAllocator; - } - }; - - struct DynAllocOrder { - bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { - return L.getIndex() < R.getIndex(); - } - }; - - /// EvalInfo - This is a private struct used by the evaluator to capture - /// information about a subexpression as it is folded. It retains information - /// about the AST context, but also maintains information about the folded - /// expression. - /// - /// If an expression could be evaluated, it is still possible it is not a C - /// "integer constant expression" or constant expression. If not, this struct - /// captures information about how and why not. - /// - /// One bit of information passed *into* the request for constant folding - /// indicates whether the subexpression is "evaluated" or not according to C - /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can - /// evaluate the expression regardless of what the RHS is, but C only allows - /// certain things in certain situations. - class EvalInfo : public interp::State { - public: - ASTContext &Ctx; +/// A dynamically-allocated heap object. +struct DynAlloc { + /// The value of this heap-allocated object. + APValue Value; + /// The allocating expression; used for diagnostics. Either a CXXNewExpr + /// or a CallExpr (the latter is for direct calls to operator new inside + /// std::allocator::allocate). + Expr const *AllocExpr = nullptr; + + enum Kind { New, ArrayNew, StdAllocator }; + + /// Get the kind of the allocation. This must match between allocation + /// and deallocation. + Kind getKind() const { + if (auto *NE = dyn_cast(AllocExpr)) + return NE->isArray() ? ArrayNew : New; + assert(isa(AllocExpr)); + return StdAllocator; + } +}; - /// EvalStatus - Contains information about the evaluation. - Expr::EvalStatus &EvalStatus; +struct DynAllocOrder { + bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const { + return L.getIndex() < R.getIndex(); + } +}; - /// CurrentCall - The top of the constexpr call stack. - CallStackFrame *CurrentCall; +/// EvalInfo - This is a private struct used by the evaluator to capture +/// information about a subexpression as it is folded. It retains information +/// about the AST context, but also maintains information about the folded +/// expression. +/// +/// If an expression could be evaluated, it is still possible it is not a C +/// "integer constant expression" or constant expression. If not, this struct +/// captures information about how and why not. +/// +/// One bit of information passed *into* the request for constant folding +/// indicates whether the subexpression is "evaluated" or not according to C +/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can +/// evaluate the expression regardless of what the RHS is, but C only allows +/// certain things in certain situations. +class EvalInfo : public interp::State { +public: + ASTContext &Ctx; - /// CallStackDepth - The number of calls in the call stack right now. - unsigned CallStackDepth; + /// EvalStatus - Contains information about the evaluation. + Expr::EvalStatus &EvalStatus; - /// NextCallIndex - The next call index to assign. - unsigned NextCallIndex; + /// CurrentCall - The top of the constexpr call stack. + CallStackFrame *CurrentCall; - /// StepsLeft - The remaining number of evaluation steps we're permitted - /// to perform. This is essentially a limit for the number of statements - /// we will evaluate. - unsigned StepsLeft; + /// CallStackDepth - The number of calls in the call stack right now. + unsigned CallStackDepth; - /// Enable the experimental new constant interpreter. If an expression is - /// not supported by the interpreter, an error is triggered. - bool EnableNewConstInterp; + /// NextCallIndex - The next call index to assign. + unsigned NextCallIndex; - /// BottomFrame - The frame in which evaluation started. This must be - /// initialized after CurrentCall and CallStackDepth. - CallStackFrame BottomFrame; + /// StepsLeft - The remaining number of evaluation steps we're permitted + /// to perform. This is essentially a limit for the number of statements + /// we will evaluate. + unsigned StepsLeft; - /// A stack of values whose lifetimes end at the end of some surrounding - /// evaluation frame. - llvm::SmallVector CleanupStack; + /// Enable the experimental new constant interpreter. If an expression is + /// not supported by the interpreter, an error is triggered. + bool EnableNewConstInterp; - /// EvaluatingDecl - This is the declaration whose initializer is being - /// evaluated, if any. - APValue::LValueBase EvaluatingDecl; + /// BottomFrame - The frame in which evaluation started. This must be + /// initialized after CurrentCall and CallStackDepth. + CallStackFrame BottomFrame; - enum class EvaluatingDeclKind { - None, - /// We're evaluating the construction of EvaluatingDecl. - Ctor, - /// We're evaluating the destruction of EvaluatingDecl. - Dtor, - }; - EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; - - /// EvaluatingDeclValue - This is the value being constructed for the - /// declaration whose initializer is being evaluated, if any. - APValue *EvaluatingDeclValue; - - /// Set of objects that are currently being constructed. - llvm::DenseMap - ObjectsUnderConstruction; - - /// Current heap allocations, along with the location where each was - /// allocated. We use std::map here because we need stable addresses - /// for the stored APValues. - std::map HeapAllocs; - - /// The number of heap allocations performed so far in this evaluation. - unsigned NumHeapAllocs = 0; - - struct EvaluatingConstructorRAII { - EvalInfo &EI; - ObjectUnderConstruction Object; - bool DidInsert; - EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, - bool HasBases) - : EI(EI), Object(Object) { - DidInsert = - EI.ObjectsUnderConstruction - .insert({Object, HasBases ? ConstructionPhase::Bases - : ConstructionPhase::AfterBases}) - .second; - } - void finishedConstructingBases() { - EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; - } - void finishedConstructingFields() { - EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; - } - ~EvaluatingConstructorRAII() { - if (DidInsert) EI.ObjectsUnderConstruction.erase(Object); - } - }; + /// A stack of values whose lifetimes end at the end of some surrounding + /// evaluation frame. + llvm::SmallVector CleanupStack; - struct EvaluatingDestructorRAII { - EvalInfo &EI; - ObjectUnderConstruction Object; - bool DidInsert; - EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) - : EI(EI), Object(Object) { - DidInsert = EI.ObjectsUnderConstruction - .insert({Object, ConstructionPhase::Destroying}) - .second; - } - void startedDestroyingBases() { - EI.ObjectsUnderConstruction[Object] = - ConstructionPhase::DestroyingBases; - } - ~EvaluatingDestructorRAII() { - if (DidInsert) - EI.ObjectsUnderConstruction.erase(Object); - } - }; + /// EvaluatingDecl - This is the declaration whose initializer is being + /// evaluated, if any. + APValue::LValueBase EvaluatingDecl; - ConstructionPhase - isEvaluatingCtorDtor(APValue::LValueBase Base, - ArrayRef Path) { - return ObjectsUnderConstruction.lookup({Base, Path}); - } - - /// If we're currently speculatively evaluating, the outermost call stack - /// depth at which we can mutate state, otherwise 0. - unsigned SpeculativeEvaluationDepth = 0; - - /// The current array initialization index, if we're performing array - /// initialization. - uint64_t ArrayInitIndex = -1; - - /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further - /// notes attached to it will also be stored, otherwise they will not be. - bool HasActiveDiagnostic; - - /// Have we emitted a diagnostic explaining why we couldn't constant - /// fold (not just why it's not strictly a constant expression)? - bool HasFoldFailureDiagnostic; - - /// Whether or not we're in a context where the front end requires a - /// constant value. - bool InConstantContext; - - /// Whether we're checking that an expression is a potential constant - /// expression. If so, do not fail on constructs that could become constant - /// later on (such as a use of an undefined global). - bool CheckingPotentialConstantExpression = false; - - /// Whether we're checking for an expression that has undefined behavior. - /// If so, we will produce warnings if we encounter an operation that is - /// always undefined. - /// - /// Note that we still need to evaluate the expression normally when this - /// is set; this is used when evaluating ICEs in C. - bool CheckingForUndefinedBehavior = false; - - enum EvaluationMode { - /// Evaluate as a constant expression. Stop if we find that the expression - /// is not a constant expression. - EM_ConstantExpression, - - /// Evaluate as a constant expression. Stop if we find that the expression - /// is not a constant expression. Some expressions can be retried in the - /// optimizer if we don't constant fold them here, but in an unevaluated - /// context we try to fold them immediately since the optimizer never - /// gets a chance to look at it. - EM_ConstantExpressionUnevaluated, - - /// Fold the expression to a constant. Stop if we hit a side-effect that - /// we can't model. - EM_ConstantFold, - - /// Evaluate in any way we know how. Don't worry about side-effects that - /// can't be modeled. - EM_IgnoreSideEffects, - } EvalMode; - - /// Are we checking whether the expression is a potential constant - /// expression? - bool checkingPotentialConstantExpression() const override { - return CheckingPotentialConstantExpression; - } - - /// Are we checking an expression for overflow? - // FIXME: We should check for any kind of undefined or suspicious behavior - // in such constructs, not just overflow. - bool checkingForUndefinedBehavior() const override { - return CheckingForUndefinedBehavior; - } - - EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode) - : Ctx(const_cast(C)), EvalStatus(S), CurrentCall(nullptr), - CallStackDepth(0), NextCallIndex(1), - StepsLeft(C.getLangOpts().ConstexprStepLimit), - EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), - BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), - EvaluatingDecl((const ValueDecl *)nullptr), - EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), - HasFoldFailureDiagnostic(false), InConstantContext(false), - EvalMode(Mode) {} - - ~EvalInfo() { - discardCleanups(); - } - - void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, - EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { - EvaluatingDecl = Base; - IsEvaluatingDecl = EDK; - EvaluatingDeclValue = &Value; - } - - bool CheckCallLimit(SourceLocation Loc) { - // Don't perform any constexpr calls (other than the call we're checking) - // when checking a potential constant expression. - if (checkingPotentialConstantExpression() && CallStackDepth > 1) - return false; - if (NextCallIndex == 0) { - // NextCallIndex has wrapped around. - FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); - return false; - } - if (CallStackDepth <= getLangOpts().ConstexprCallDepth) - return true; - FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) - << getLangOpts().ConstexprCallDepth; - return false; + enum class EvaluatingDeclKind { + None, + /// We're evaluating the construction of EvaluatingDecl. + Ctor, + /// We're evaluating the destruction of EvaluatingDecl. + Dtor, + }; + EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None; + + /// EvaluatingDeclValue - This is the value being constructed for the + /// declaration whose initializer is being evaluated, if any. + APValue *EvaluatingDeclValue; + + /// Set of objects that are currently being constructed. + llvm::DenseMap + ObjectsUnderConstruction; + + /// Current heap allocations, along with the location where each was + /// allocated. We use std::map here because we need stable addresses + /// for the stored APValues. + std::map HeapAllocs; + + /// The number of heap allocations performed so far in this evaluation. + unsigned NumHeapAllocs = 0; + + struct EvaluatingConstructorRAII { + EvalInfo &EI; + ObjectUnderConstruction Object; + bool DidInsert; + EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object, + bool HasBases) + : EI(EI), Object(Object) { + DidInsert = + EI.ObjectsUnderConstruction + .insert({Object, HasBases ? ConstructionPhase::Bases + : ConstructionPhase::AfterBases}) + .second; + } + void finishedConstructingBases() { + EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases; + } + void finishedConstructingFields() { + EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields; + } + ~EvaluatingConstructorRAII() { + if (DidInsert) + EI.ObjectsUnderConstruction.erase(Object); } + }; - std::pair - getCallFrameAndDepth(unsigned CallIndex) { - assert(CallIndex && "no call index in getCallFrameAndDepth"); - // We will eventually hit BottomFrame, which has Index 1, so Frame can't - // be null in this loop. - unsigned Depth = CallStackDepth; - CallStackFrame *Frame = CurrentCall; - while (Frame->Index > CallIndex) { - Frame = Frame->Caller; - --Depth; - } - if (Frame->Index == CallIndex) - return {Frame, Depth}; - return {nullptr, 0}; + struct EvaluatingDestructorRAII { + EvalInfo &EI; + ObjectUnderConstruction Object; + bool DidInsert; + EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object) + : EI(EI), Object(Object) { + DidInsert = EI.ObjectsUnderConstruction + .insert({Object, ConstructionPhase::Destroying}) + .second; } - - bool nextStep(const Stmt *S) { - if (!StepsLeft) { - FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); - return false; - } - --StepsLeft; - return true; + void startedDestroyingBases() { + EI.ObjectsUnderConstruction[Object] = ConstructionPhase::DestroyingBases; } + ~EvaluatingDestructorRAII() { + if (DidInsert) + EI.ObjectsUnderConstruction.erase(Object); + } + }; - APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV); + ConstructionPhase + isEvaluatingCtorDtor(APValue::LValueBase Base, + ArrayRef Path) { + return ObjectsUnderConstruction.lookup({Base, Path}); + } - Optional lookupDynamicAlloc(DynamicAllocLValue DA) { - Optional Result; - auto It = HeapAllocs.find(DA); - if (It != HeapAllocs.end()) - Result = &It->second; - return Result; - } + /// If we're currently speculatively evaluating, the outermost call stack + /// depth at which we can mutate state, otherwise 0. + unsigned SpeculativeEvaluationDepth = 0; - /// Get the allocated storage for the given parameter of the given call. - APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) { - CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; - return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) - : nullptr; - } + /// The current array initialization index, if we're performing array + /// initialization. + uint64_t ArrayInitIndex = -1; - /// Information about a stack frame for std::allocator::[de]allocate. - struct StdAllocatorCaller { - unsigned FrameIndex; - QualType ElemType; - explicit operator bool() const { return FrameIndex != 0; }; - }; + /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further + /// notes attached to it will also be stored, otherwise they will not be. + bool HasActiveDiagnostic; - StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { - for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame; - Call = Call->Caller) { - const auto *MD = dyn_cast_or_null(Call->Callee); - if (!MD) - continue; - const IdentifierInfo *FnII = MD->getIdentifier(); - if (!FnII || !FnII->isStr(FnName)) - continue; + /// Have we emitted a diagnostic explaining why we couldn't constant + /// fold (not just why it's not strictly a constant expression)? + bool HasFoldFailureDiagnostic; - const auto *CTSD = - dyn_cast(MD->getParent()); - if (!CTSD) - continue; + /// Whether or not we're in a context where the front end requires a + /// constant value. + bool InConstantContext; - const IdentifierInfo *ClassII = CTSD->getIdentifier(); - const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); - if (CTSD->isInStdNamespace() && ClassII && - ClassII->isStr("allocator") && TAL.size() >= 1 && - TAL[0].getKind() == TemplateArgument::Type) - return {Call->Index, TAL[0].getAsType()}; - } + /// Whether we're checking that an expression is a potential constant + /// expression. If so, do not fail on constructs that could become constant + /// later on (such as a use of an undefined global). + bool CheckingPotentialConstantExpression = false; - return {}; - } - - void performLifetimeExtension() { - // Disable the cleanups for lifetime-extended temporaries. - CleanupStack.erase(std::remove_if(CleanupStack.begin(), - CleanupStack.end(), - [](Cleanup &C) { - return !C.isDestroyedAtEndOf( - ScopeKind::FullExpression); - }), - CleanupStack.end()); - } - - /// Throw away any remaining cleanups at the end of evaluation. If any - /// cleanups would have had a side-effect, note that as an unmodeled - /// side-effect and return false. Otherwise, return true. - bool discardCleanups() { - for (Cleanup &C : CleanupStack) { - if (C.hasSideEffect() && !noteSideEffect()) { - CleanupStack.clear(); - return false; - } - } - CleanupStack.clear(); + /// Whether we're checking for an expression that has undefined behavior. + /// If so, we will produce warnings if we encounter an operation that is + /// always undefined. + /// + /// Note that we still need to evaluate the expression normally when this + /// is set; this is used when evaluating ICEs in C. + bool CheckingForUndefinedBehavior = false; + + enum EvaluationMode { + /// Evaluate as a constant expression. Stop if we find that the expression + /// is not a constant expression. + EM_ConstantExpression, + + /// Evaluate as a constant expression. Stop if we find that the expression + /// is not a constant expression. Some expressions can be retried in the + /// optimizer if we don't constant fold them here, but in an unevaluated + /// context we try to fold them immediately since the optimizer never + /// gets a chance to look at it. + EM_ConstantExpressionUnevaluated, + + /// Fold the expression to a constant. Stop if we hit a side-effect that + /// we can't model. + EM_ConstantFold, + + /// Evaluate in any way we know how. Don't worry about side-effects that + /// can't be modeled. + EM_IgnoreSideEffects, + } EvalMode; + + /// Are we checking whether the expression is a potential constant + /// expression? + bool checkingPotentialConstantExpression() const override { + return CheckingPotentialConstantExpression; + } + + /// Are we checking an expression for overflow? + // FIXME: We should check for any kind of undefined or suspicious behavior + // in such constructs, not just overflow. + bool checkingForUndefinedBehavior() const override { + return CheckingForUndefinedBehavior; + } + + EvalInfo(ASTContext const &C, Expr::EvalStatus &S, EvaluationMode Mode) + : Ctx(const_cast(C)), EvalStatus(S), CurrentCall(nullptr), + CallStackDepth(0), NextCallIndex(1), + StepsLeft(C.getLangOpts().ConstexprStepLimit), + EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp), + BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()), + EvaluatingDecl((ValueDecl const *)nullptr), + EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false), + HasFoldFailureDiagnostic(false), InConstantContext(false), + EvalMode(Mode) {} + + ~EvalInfo() { discardCleanups(); } + + void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value, + EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) { + EvaluatingDecl = Base; + IsEvaluatingDecl = EDK; + EvaluatingDeclValue = &Value; + } + + bool CheckCallLimit(SourceLocation Loc) { + // Don't perform any constexpr calls (other than the call we're checking) + // when checking a potential constant expression. + if (checkingPotentialConstantExpression() && CallStackDepth > 1) + return false; + if (NextCallIndex == 0) { + // NextCallIndex has wrapped around. + FFDiag(Loc, diag::note_constexpr_call_limit_exceeded); + return false; + } + if (CallStackDepth <= getLangOpts().ConstexprCallDepth) return true; + FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded) + << getLangOpts().ConstexprCallDepth; + return false; + } + + std::pair + getCallFrameAndDepth(unsigned CallIndex) { + assert(CallIndex && "no call index in getCallFrameAndDepth"); + // We will eventually hit BottomFrame, which has Index 1, so Frame can't + // be null in this loop. + unsigned Depth = CallStackDepth; + CallStackFrame *Frame = CurrentCall; + while (Frame->Index > CallIndex) { + Frame = Frame->Caller; + --Depth; } + if (Frame->Index == CallIndex) + return {Frame, Depth}; + return {nullptr, 0}; + } - private: - interp::Frame *getCurrentFrame() override { return CurrentCall; } - const interp::Frame *getBottomFrame() const override { return &BottomFrame; } + bool nextStep(Stmt const *S) { + if (!StepsLeft) { + FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded); + return false; + } + --StepsLeft; + return true; + } - bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } - void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } + APValue *createHeapAlloc(Expr const *E, QualType T, LValue &LV); - void setFoldFailureDiagnostic(bool Flag) override { - HasFoldFailureDiagnostic = Flag; - } + Optional lookupDynamicAlloc(DynamicAllocLValue DA) { + Optional Result; + auto It = HeapAllocs.find(DA); + if (It != HeapAllocs.end()) + Result = &It->second; + return Result; + } - Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } + /// Get the allocated storage for the given parameter of the given call. + APValue *getParamSlot(CallRef Call, ParmVarDecl const *PVD) { + CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first; + return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version) + : nullptr; + } - ASTContext &getCtx() const override { return Ctx; } + /// Information about a stack frame for std::allocator::[de]allocate. + struct StdAllocatorCaller { + unsigned FrameIndex; + QualType ElemType; + explicit operator bool() const { return FrameIndex != 0; }; + }; - // If we have a prior diagnostic, it will be noting that the expression - // isn't a constant expression. This diagnostic is more important, - // unless we require this evaluation to produce a constant expression. - // - // FIXME: We might want to show both diagnostics to the user in - // EM_ConstantFold mode. - bool hasPriorDiagnostic() override { - if (!EvalStatus.Diag->empty()) { - switch (EvalMode) { - case EM_ConstantFold: - case EM_IgnoreSideEffects: - if (!HasFoldFailureDiagnostic) - break; - // We've already failed to fold something. Keep that diagnostic. - LLVM_FALLTHROUGH; - case EM_ConstantExpression: - case EM_ConstantExpressionUnevaluated: - setActiveDiagnostic(false); - return true; - } - } - return false; + StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const { + for (CallStackFrame const *Call = CurrentCall; Call != &BottomFrame; + Call = Call->Caller) { + auto const *MD = dyn_cast_or_null(Call->Callee); + if (!MD) + continue; + IdentifierInfo const *FnII = MD->getIdentifier(); + if (!FnII || !FnII->isStr(FnName)) + continue; + + auto const *CTSD = + dyn_cast(MD->getParent()); + if (!CTSD) + continue; + + IdentifierInfo const *ClassII = CTSD->getIdentifier(); + TemplateArgumentList const &TAL = CTSD->getTemplateArgs(); + if (CTSD->isInStdNamespace() && ClassII && ClassII->isStr("allocator") && + TAL.size() >= 1 && TAL[0].getKind() == TemplateArgument::Type) + return {Call->Index, TAL[0].getAsType()}; } - unsigned getCallStackDepth() override { return CallStackDepth; } + return {}; + } - public: - /// Should we continue evaluation after encountering a side-effect that we - /// couldn't model? - bool keepEvaluatingAfterSideEffect() { - switch (EvalMode) { - case EM_IgnoreSideEffects: - return true; + void performLifetimeExtension() { + // Disable the cleanups for lifetime-extended temporaries. + CleanupStack.erase(std::remove_if(CleanupStack.begin(), CleanupStack.end(), + [](Cleanup &C) { + return !C.isDestroyedAtEndOf( + ScopeKind::FullExpression); + }), + CleanupStack.end()); + } - case EM_ConstantExpression: - case EM_ConstantExpressionUnevaluated: - case EM_ConstantFold: - // By default, assume any side effect might be valid in some other - // evaluation of this expression from a different context. - return checkingPotentialConstantExpression() || - checkingForUndefinedBehavior(); + /// Throw away any remaining cleanups at the end of evaluation. If any + /// cleanups would have had a side-effect, note that as an unmodeled + /// side-effect and return false. Otherwise, return true. + bool discardCleanups() { + for (Cleanup &C : CleanupStack) { + if (C.hasSideEffect() && !noteSideEffect()) { + CleanupStack.clear(); + return false; } - llvm_unreachable("Missed EvalMode case"); } + CleanupStack.clear(); + return true; + } - /// Note that we have had a side-effect, and determine whether we should - /// keep evaluating. - bool noteSideEffect() { - EvalStatus.HasSideEffects = true; - return keepEvaluatingAfterSideEffect(); - } +private: + interp::Frame *getCurrentFrame() override { return CurrentCall; } + interp::Frame const *getBottomFrame() const override { return &BottomFrame; } + + bool hasActiveDiagnostic() override { return HasActiveDiagnostic; } + void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; } - /// Should we continue evaluation after encountering undefined behavior? - bool keepEvaluatingAfterUndefinedBehavior() { + void setFoldFailureDiagnostic(bool Flag) override { + HasFoldFailureDiagnostic = Flag; + } + + Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; } + + ASTContext &getCtx() const override { return Ctx; } + + // If we have a prior diagnostic, it will be noting that the expression + // isn't a constant expression. This diagnostic is more important, + // unless we require this evaluation to produce a constant expression. + // + // FIXME: We might want to show both diagnostics to the user in + // EM_ConstantFold mode. + bool hasPriorDiagnostic() override { + if (!EvalStatus.Diag->empty()) { switch (EvalMode) { - case EM_IgnoreSideEffects: case EM_ConstantFold: - return true; - + case EM_IgnoreSideEffects: + if (!HasFoldFailureDiagnostic) + break; + // We've already failed to fold something. Keep that diagnostic. + LLVM_FALLTHROUGH; case EM_ConstantExpression: case EM_ConstantExpressionUnevaluated: - return checkingForUndefinedBehavior(); + setActiveDiagnostic(false); + return true; } - llvm_unreachable("Missed EvalMode case"); } + return false; + } + + unsigned getCallStackDepth() override { return CallStackDepth; } - /// Note that we hit something that was technically undefined behavior, but - /// that we can evaluate past it (such as signed overflow or floating-point - /// division by zero.) - bool noteUndefinedBehavior() override { - EvalStatus.HasUndefinedBehavior = true; - return keepEvaluatingAfterUndefinedBehavior(); +public: + /// Should we continue evaluation after encountering a side-effect that we + /// couldn't model? + bool keepEvaluatingAfterSideEffect() { + switch (EvalMode) { + case EM_IgnoreSideEffects: + return true; + + case EM_ConstantExpression: + case EM_ConstantExpressionUnevaluated: + case EM_ConstantFold: + // By default, assume any side effect might be valid in some other + // evaluation of this expression from a different context. + return checkingPotentialConstantExpression() || + checkingForUndefinedBehavior(); } + llvm_unreachable("Missed EvalMode case"); + } - /// Should we continue evaluation as much as possible after encountering a - /// construct which can't be reduced to a value? - bool keepEvaluatingAfterFailure() const override { - if (!StepsLeft) - return false; + /// Note that we have had a side-effect, and determine whether we should + /// keep evaluating. + bool noteSideEffect() { + EvalStatus.HasSideEffects = true; + return keepEvaluatingAfterSideEffect(); + } - switch (EvalMode) { - case EM_ConstantExpression: - case EM_ConstantExpressionUnevaluated: - case EM_ConstantFold: - case EM_IgnoreSideEffects: - return checkingPotentialConstantExpression() || - checkingForUndefinedBehavior(); - } - llvm_unreachable("Missed EvalMode case"); - } - - /// Notes that we failed to evaluate an expression that other expressions - /// directly depend on, and determine if we should keep evaluating. This - /// should only be called if we actually intend to keep evaluating. - /// - /// Call noteSideEffect() instead if we may be able to ignore the value that - /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: - /// - /// (Foo(), 1) // use noteSideEffect - /// (Foo() || true) // use noteSideEffect - /// Foo() + 1 // use noteFailure - LLVM_NODISCARD bool noteFailure() { - // Failure when evaluating some expression often means there is some - // subexpression whose evaluation was skipped. Therefore, (because we - // don't track whether we skipped an expression when unwinding after an - // evaluation failure) every evaluation failure that bubbles up from a - // subexpression implies that a side-effect has potentially happened. We - // skip setting the HasSideEffects flag to true until we decide to - // continue evaluating after that point, which happens here. - bool KeepGoing = keepEvaluatingAfterFailure(); - EvalStatus.HasSideEffects |= KeepGoing; - return KeepGoing; - } - - class ArrayInitLoopIndex { - EvalInfo &Info; - uint64_t OuterIndex; + /// Should we continue evaluation after encountering undefined behavior? + bool keepEvaluatingAfterUndefinedBehavior() { + switch (EvalMode) { + case EM_IgnoreSideEffects: + case EM_ConstantFold: + return true; - public: - ArrayInitLoopIndex(EvalInfo &Info) - : Info(Info), OuterIndex(Info.ArrayInitIndex) { - Info.ArrayInitIndex = 0; - } - ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } + case EM_ConstantExpression: + case EM_ConstantExpressionUnevaluated: + return checkingForUndefinedBehavior(); + } + llvm_unreachable("Missed EvalMode case"); + } - operator uint64_t&() { return Info.ArrayInitIndex; } - }; - }; + /// Note that we hit something that was technically undefined behavior, but + /// that we can evaluate past it (such as signed overflow or floating-point + /// division by zero.) + bool noteUndefinedBehavior() override { + EvalStatus.HasUndefinedBehavior = true; + return keepEvaluatingAfterUndefinedBehavior(); + } - /// Object used to treat all foldable expressions as constant expressions. - struct FoldConstant { - EvalInfo &Info; - bool Enabled; - bool HadNoPriorDiags; - EvalInfo::EvaluationMode OldMode; + /// Should we continue evaluation as much as possible after encountering a + /// construct which can't be reduced to a value? + bool keepEvaluatingAfterFailure() const override { + if (!StepsLeft) + return false; - explicit FoldConstant(EvalInfo &Info, bool Enabled) - : Info(Info), - Enabled(Enabled), - HadNoPriorDiags(Info.EvalStatus.Diag && - Info.EvalStatus.Diag->empty() && - !Info.EvalStatus.HasSideEffects), - OldMode(Info.EvalMode) { - if (Enabled) - Info.EvalMode = EvalInfo::EM_ConstantFold; - } - void keepDiagnostics() { Enabled = false; } - ~FoldConstant() { - if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && - !Info.EvalStatus.HasSideEffects) - Info.EvalStatus.Diag->clear(); - Info.EvalMode = OldMode; + switch (EvalMode) { + case EM_ConstantExpression: + case EM_ConstantExpressionUnevaluated: + case EM_ConstantFold: + case EM_IgnoreSideEffects: + return checkingPotentialConstantExpression() || + checkingForUndefinedBehavior(); } - }; + llvm_unreachable("Missed EvalMode case"); + } - /// RAII object used to set the current evaluation mode to ignore - /// side-effects. - struct IgnoreSideEffectsRAII { + /// Notes that we failed to evaluate an expression that other expressions + /// directly depend on, and determine if we should keep evaluating. This + /// should only be called if we actually intend to keep evaluating. + /// + /// Call noteSideEffect() instead if we may be able to ignore the value that + /// we failed to evaluate, e.g. if we failed to evaluate Foo() in: + /// + /// (Foo(), 1) // use noteSideEffect + /// (Foo() || true) // use noteSideEffect + /// Foo() + 1 // use noteFailure + LLVM_NODISCARD bool noteFailure() { + // Failure when evaluating some expression often means there is some + // subexpression whose evaluation was skipped. Therefore, (because we + // don't track whether we skipped an expression when unwinding after an + // evaluation failure) every evaluation failure that bubbles up from a + // subexpression implies that a side-effect has potentially happened. We + // skip setting the HasSideEffects flag to true until we decide to + // continue evaluating after that point, which happens here. + bool KeepGoing = keepEvaluatingAfterFailure(); + EvalStatus.HasSideEffects |= KeepGoing; + return KeepGoing; + } + + class ArrayInitLoopIndex { EvalInfo &Info; - EvalInfo::EvaluationMode OldMode; - explicit IgnoreSideEffectsRAII(EvalInfo &Info) - : Info(Info), OldMode(Info.EvalMode) { - Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; + uint64_t OuterIndex; + + public: + ArrayInitLoopIndex(EvalInfo &Info) + : Info(Info), OuterIndex(Info.ArrayInitIndex) { + Info.ArrayInitIndex = 0; } + ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; } - ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } + operator uint64_t &() { return Info.ArrayInitIndex; } }; +}; - /// RAII object used to optionally suppress diagnostics and side-effects from - /// a speculative evaluation. - class SpeculativeEvaluationRAII { - EvalInfo *Info = nullptr; - Expr::EvalStatus OldStatus; - unsigned OldSpeculativeEvaluationDepth; +/// Object used to treat all foldable expressions as constant expressions. +struct FoldConstant { + EvalInfo &Info; + bool Enabled; + bool HadNoPriorDiags; + EvalInfo::EvaluationMode OldMode; - void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { - Info = Other.Info; - OldStatus = Other.OldStatus; - OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; - Other.Info = nullptr; - } + explicit FoldConstant(EvalInfo &Info, bool Enabled) + : Info(Info), Enabled(Enabled), + HadNoPriorDiags(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() && + !Info.EvalStatus.HasSideEffects), + OldMode(Info.EvalMode) { + if (Enabled) + Info.EvalMode = EvalInfo::EM_ConstantFold; + } + void keepDiagnostics() { Enabled = false; } + ~FoldConstant() { + if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() && + !Info.EvalStatus.HasSideEffects) + Info.EvalStatus.Diag->clear(); + Info.EvalMode = OldMode; + } +}; - void maybeRestoreState() { - if (!Info) - return; +/// RAII object used to set the current evaluation mode to ignore +/// side-effects. +struct IgnoreSideEffectsRAII { + EvalInfo &Info; + EvalInfo::EvaluationMode OldMode; + explicit IgnoreSideEffectsRAII(EvalInfo &Info) + : Info(Info), OldMode(Info.EvalMode) { + Info.EvalMode = EvalInfo::EM_IgnoreSideEffects; + } - Info->EvalStatus = OldStatus; - Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; - } + ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; } +}; - public: - SpeculativeEvaluationRAII() = default; +/// RAII object used to optionally suppress diagnostics and side-effects from +/// a speculative evaluation. +class SpeculativeEvaluationRAII { + EvalInfo *Info = nullptr; + Expr::EvalStatus OldStatus; + unsigned OldSpeculativeEvaluationDepth; - SpeculativeEvaluationRAII( - EvalInfo &Info, SmallVectorImpl *NewDiag = nullptr) - : Info(&Info), OldStatus(Info.EvalStatus), - OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { - Info.EvalStatus.Diag = NewDiag; - Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; - } + void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) { + Info = Other.Info; + OldStatus = Other.OldStatus; + OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth; + Other.Info = nullptr; + } - SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete; - SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { - moveFromAndCancel(std::move(Other)); - } + void maybeRestoreState() { + if (!Info) + return; - SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { - maybeRestoreState(); - moveFromAndCancel(std::move(Other)); - return *this; - } + Info->EvalStatus = OldStatus; + Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth; + } - ~SpeculativeEvaluationRAII() { maybeRestoreState(); } - }; +public: + SpeculativeEvaluationRAII() = default; - /// RAII object wrapping a full-expression or block scope, and handling - /// the ending of the lifetime of temporaries created within it. - template - class ScopeRAII { - EvalInfo &Info; - unsigned OldStackSize; - public: - ScopeRAII(EvalInfo &Info) - : Info(Info), OldStackSize(Info.CleanupStack.size()) { - // Push a new temporary version. This is needed to distinguish between - // temporaries created in different iterations of a loop. - Info.CurrentCall->pushTempVersion(); - } - bool destroy(bool RunDestructors = true) { - bool OK = cleanup(Info, RunDestructors, OldStackSize); - OldStackSize = -1U; - return OK; - } - ~ScopeRAII() { - if (OldStackSize != -1U) - destroy(false); - // Body moved to a static method to encourage the compiler to inline away - // instances of this class. - Info.CurrentCall->popTempVersion(); - } - private: - static bool cleanup(EvalInfo &Info, bool RunDestructors, - unsigned OldStackSize) { - assert(OldStackSize <= Info.CleanupStack.size() && - "running cleanups out of order?"); + SpeculativeEvaluationRAII( + EvalInfo &Info, SmallVectorImpl *NewDiag = nullptr) + : Info(&Info), OldStatus(Info.EvalStatus), + OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) { + Info.EvalStatus.Diag = NewDiag; + Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1; + } - // Run all cleanups for a block scope, and non-lifetime-extended cleanups - // for a full-expression scope. - bool Success = true; - for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { - if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { - if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { - Success = false; - break; - } + SpeculativeEvaluationRAII(SpeculativeEvaluationRAII const &Other) = delete; + SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) { + moveFromAndCancel(std::move(Other)); + } + + SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) { + maybeRestoreState(); + moveFromAndCancel(std::move(Other)); + return *this; + } + + ~SpeculativeEvaluationRAII() { maybeRestoreState(); } +}; + +/// RAII object wrapping a full-expression or block scope, and handling +/// the ending of the lifetime of temporaries created within it. +template class ScopeRAII { + EvalInfo &Info; + unsigned OldStackSize; + +public: + ScopeRAII(EvalInfo &Info) + : Info(Info), OldStackSize(Info.CleanupStack.size()) { + // Push a new temporary version. This is needed to distinguish between + // temporaries created in different iterations of a loop. + Info.CurrentCall->pushTempVersion(); + } + bool destroy(bool RunDestructors = true) { + bool OK = cleanup(Info, RunDestructors, OldStackSize); + OldStackSize = -1U; + return OK; + } + ~ScopeRAII() { + if (OldStackSize != -1U) + destroy(false); + // Body moved to a static method to encourage the compiler to inline away + // instances of this class. + Info.CurrentCall->popTempVersion(); + } + +private: + static bool cleanup(EvalInfo &Info, bool RunDestructors, + unsigned OldStackSize) { + assert(OldStackSize <= Info.CleanupStack.size() && + "running cleanups out of order?"); + + // Run all cleanups for a block scope, and non-lifetime-extended cleanups + // for a full-expression scope. + bool Success = true; + for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) { + if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) { + if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) { + Success = false; + break; } } - - // Compact any retained cleanups. - auto NewEnd = Info.CleanupStack.begin() + OldStackSize; - if (Kind != ScopeKind::Block) - NewEnd = - std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { - return C.isDestroyedAtEndOf(Kind); - }); - Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); - return Success; } - }; - typedef ScopeRAII BlockScopeRAII; - typedef ScopeRAII FullExpressionRAII; - typedef ScopeRAII CallScopeRAII; -} -bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E, + // Compact any retained cleanups. + auto NewEnd = Info.CleanupStack.begin() + OldStackSize; + if (Kind != ScopeKind::Block) + NewEnd = std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) { + return C.isDestroyedAtEndOf(Kind); + }); + Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end()); + return Success; + } +}; +typedef ScopeRAII BlockScopeRAII; +typedef ScopeRAII FullExpressionRAII; +typedef ScopeRAII CallScopeRAII; +} // namespace + +bool SubobjectDesignator::checkSubobject(EvalInfo &Info, Expr const *E, CheckSubobjectKind CSK) { if (Invalid) return false; if (isOnePastTheEnd()) { - Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) - << CSK; + Info.CCEDiag(E, diag::note_constexpr_past_end_subobject) << CSK; setInvalid(); return false; } @@ -1413,29 +1386,27 @@ } void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, - const Expr *E) { + Expr const *E) { Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed); // Do not set the designator as invalid: we can represent this situation, // and correct handling of __builtin_object_size requires us to do so. } void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info, - const Expr *E, - const APSInt &N) { + Expr const *E, + APSInt const &N) { // If we're complaining, we must be able to statically determine the size of // the most derived array. if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement) Info.CCEDiag(E, diag::note_constexpr_array_index) - << N << /*array*/ 0 - << static_cast(getMostDerivedArraySize()); + << N << /*array*/ 0 << static_cast(getMostDerivedArraySize()); else - Info.CCEDiag(E, diag::note_constexpr_array_index) - << N << /*non-array*/ 1; + Info.CCEDiag(E, diag::note_constexpr_array_index) << N << /*non-array*/ 1; setInvalid(); } CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc, - const FunctionDecl *Callee, const LValue *This, + FunctionDecl const *Callee, LValue const *This, CallRef Call) : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This), Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) { @@ -1506,335 +1477,326 @@ } namespace { - struct ComplexValue { - private: - bool IsInt; +struct ComplexValue { +private: + bool IsInt; - public: - APSInt IntReal, IntImag; - APFloat FloatReal, FloatImag; +public: + APSInt IntReal, IntImag; + APFloat FloatReal, FloatImag; - ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} + ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {} - void makeComplexFloat() { IsInt = false; } - bool isComplexFloat() const { return !IsInt; } - APFloat &getComplexFloatReal() { return FloatReal; } - APFloat &getComplexFloatImag() { return FloatImag; } + void makeComplexFloat() { IsInt = false; } + bool isComplexFloat() const { return !IsInt; } + APFloat &getComplexFloatReal() { return FloatReal; } + APFloat &getComplexFloatImag() { return FloatImag; } - void makeComplexInt() { IsInt = true; } - bool isComplexInt() const { return IsInt; } - APSInt &getComplexIntReal() { return IntReal; } - APSInt &getComplexIntImag() { return IntImag; } + void makeComplexInt() { IsInt = true; } + bool isComplexInt() const { return IsInt; } + APSInt &getComplexIntReal() { return IntReal; } + APSInt &getComplexIntImag() { return IntImag; } - void moveInto(APValue &v) const { - if (isComplexFloat()) - v = APValue(FloatReal, FloatImag); - else - v = APValue(IntReal, IntImag); - } - void setFrom(const APValue &v) { - assert(v.isComplexFloat() || v.isComplexInt()); - if (v.isComplexFloat()) { - makeComplexFloat(); - FloatReal = v.getComplexFloatReal(); - FloatImag = v.getComplexFloatImag(); - } else { - makeComplexInt(); - IntReal = v.getComplexIntReal(); - IntImag = v.getComplexIntImag(); - } + void moveInto(APValue &v) const { + if (isComplexFloat()) + v = APValue(FloatReal, FloatImag); + else + v = APValue(IntReal, IntImag); + } + void setFrom(APValue const &v) { + assert(v.isComplexFloat() || v.isComplexInt()); + if (v.isComplexFloat()) { + makeComplexFloat(); + FloatReal = v.getComplexFloatReal(); + FloatImag = v.getComplexFloatImag(); + } else { + makeComplexInt(); + IntReal = v.getComplexIntReal(); + IntImag = v.getComplexIntImag(); } - }; + } +}; - struct LValue { - APValue::LValueBase Base; - CharUnits Offset; - SubobjectDesignator Designator; - bool IsNullPtr : 1; - bool InvalidBase : 1; - - const APValue::LValueBase getLValueBase() const { return Base; } - CharUnits &getLValueOffset() { return Offset; } - const CharUnits &getLValueOffset() const { return Offset; } - SubobjectDesignator &getLValueDesignator() { return Designator; } - const SubobjectDesignator &getLValueDesignator() const { return Designator;} - bool isNullPointer() const { return IsNullPtr;} - - unsigned getLValueCallIndex() const { return Base.getCallIndex(); } - unsigned getLValueVersion() const { return Base.getVersion(); } - - void moveInto(APValue &V) const { - if (Designator.Invalid) - V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); - else { - assert(!InvalidBase && "APValues can't handle invalid LValue bases"); - V = APValue(Base, Offset, Designator.Entries, - Designator.IsOnePastTheEnd, IsNullPtr); - } - } - void setFrom(ASTContext &Ctx, const APValue &V) { - assert(V.isLValue() && "Setting LValue from a non-LValue?"); - Base = V.getLValueBase(); - Offset = V.getLValueOffset(); - InvalidBase = false; - Designator = SubobjectDesignator(Ctx, V); - IsNullPtr = V.isNullPointer(); +struct LValue { + APValue::LValueBase Base; + CharUnits Offset; + SubobjectDesignator Designator; + bool IsNullPtr : 1; + bool InvalidBase : 1; + + const APValue::LValueBase getLValueBase() const { return Base; } + CharUnits &getLValueOffset() { return Offset; } + CharUnits const &getLValueOffset() const { return Offset; } + SubobjectDesignator &getLValueDesignator() { return Designator; } + SubobjectDesignator const &getLValueDesignator() const { return Designator; } + bool isNullPointer() const { return IsNullPtr; } + + unsigned getLValueCallIndex() const { return Base.getCallIndex(); } + unsigned getLValueVersion() const { return Base.getVersion(); } + + void moveInto(APValue &V) const { + if (Designator.Invalid) + V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr); + else { + assert(!InvalidBase && "APValues can't handle invalid LValue bases"); + V = APValue(Base, Offset, Designator.Entries, Designator.IsOnePastTheEnd, + IsNullPtr); } + } + void setFrom(ASTContext &Ctx, APValue const &V) { + assert(V.isLValue() && "Setting LValue from a non-LValue?"); + Base = V.getLValueBase(); + Offset = V.getLValueOffset(); + InvalidBase = false; + Designator = SubobjectDesignator(Ctx, V); + IsNullPtr = V.isNullPointer(); + } - void set(APValue::LValueBase B, bool BInvalid = false) { + void set(APValue::LValueBase B, bool BInvalid = false) { #ifndef NDEBUG - // We only allow a few types of invalid bases. Enforce that here. - if (BInvalid) { - const auto *E = B.get(); - assert((isa(E) || tryUnwrapAllocSizeCall(E)) && - "Unexpected type of invalid base"); - } -#endif - - Base = B; - Offset = CharUnits::fromQuantity(0); - InvalidBase = BInvalid; - Designator = SubobjectDesignator(getType(B)); - IsNullPtr = false; - } - - void setNull(ASTContext &Ctx, QualType PointerTy) { - Base = (const ValueDecl *)nullptr; - Offset = - CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); - InvalidBase = false; - Designator = SubobjectDesignator(PointerTy->getPointeeType()); - IsNullPtr = true; + // We only allow a few types of invalid bases. Enforce that here. + if (BInvalid) { + auto const *E = B.get(); + assert((isa(E) || tryUnwrapAllocSizeCall(E)) && + "Unexpected type of invalid base"); } +#endif - void setInvalid(APValue::LValueBase B, unsigned I = 0) { - set(B, true); - } + Base = B; + Offset = CharUnits::fromQuantity(0); + InvalidBase = BInvalid; + Designator = SubobjectDesignator(getType(B)); + IsNullPtr = false; + } - std::string toString(ASTContext &Ctx, QualType T) const { - APValue Printable; - moveInto(Printable); - return Printable.getAsString(Ctx, T); - } + void setNull(ASTContext &Ctx, QualType PointerTy) { + Base = (ValueDecl const *)nullptr; + Offset = CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy)); + InvalidBase = false; + Designator = SubobjectDesignator(PointerTy->getPointeeType()); + IsNullPtr = true; + } - private: - // Check that this LValue is not based on a null pointer. If it is, produce - // a diagnostic and mark the designator as invalid. - template - bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) { - if (Designator.Invalid) - return false; - if (IsNullPtr) { - GenDiag(); - Designator.setInvalid(); - return false; - } - return true; - } + void setInvalid(APValue::LValueBase B, unsigned I = 0) { set(B, true); } - public: - bool checkNullPointer(EvalInfo &Info, const Expr *E, - CheckSubobjectKind CSK) { - return checkNullPointerDiagnosingWith([&Info, E, CSK] { - Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; - }); - } + std::string toString(ASTContext &Ctx, QualType T) const { + APValue Printable; + moveInto(Printable); + return Printable.getAsString(Ctx, T); + } - bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E, - AccessKinds AK) { - return checkNullPointerDiagnosingWith([&Info, E, AK] { - Info.FFDiag(E, diag::note_constexpr_access_null) << AK; - }); +private: + // Check that this LValue is not based on a null pointer. If it is, produce + // a diagnostic and mark the designator as invalid. + template + bool checkNullPointerDiagnosingWith(GenDiagType const &GenDiag) { + if (Designator.Invalid) + return false; + if (IsNullPtr) { + GenDiag(); + Designator.setInvalid(); + return false; } + return true; + } - // Check this LValue refers to an object. If not, set the designator to be - // invalid and emit a diagnostic. - bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) { - return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && - Designator.checkSubobject(Info, E, CSK); - } +public: + bool checkNullPointer(EvalInfo &Info, Expr const *E, CheckSubobjectKind CSK) { + return checkNullPointerDiagnosingWith([&Info, E, CSK] { + Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK; + }); + } - void addDecl(EvalInfo &Info, const Expr *E, - const Decl *D, bool Virtual = false) { - if (checkSubobject(Info, E, isa(D) ? CSK_Field : CSK_Base)) - Designator.addDeclUnchecked(D, Virtual); - } - void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) { - if (!Designator.Entries.empty()) { - Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); - Designator.setInvalid(); - return; - } - if (checkSubobject(Info, E, CSK_ArrayToPointer)) { - assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); - Designator.FirstEntryIsAnUnsizedArray = true; - Designator.addUnsizedArrayUnchecked(ElemTy); - } - } - void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) { - if (checkSubobject(Info, E, CSK_ArrayToPointer)) - Designator.addArrayUnchecked(CAT); - } - void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) { - if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) - Designator.addComplexUnchecked(EltTy, Imag); - } - void clearIsNullPointer() { - IsNullPtr = false; - } - void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, - const APSInt &Index, CharUnits ElementSize) { - // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, - // but we're not required to diagnose it and it's valid in C++.) - if (!Index) - return; + bool checkNullPointerForFoldAccess(EvalInfo &Info, Expr const *E, + AccessKinds AK) { + return checkNullPointerDiagnosingWith([&Info, E, AK] { + Info.FFDiag(E, diag::note_constexpr_access_null) << AK; + }); + } - // Compute the new offset in the appropriate width, wrapping at 64 bits. - // FIXME: When compiling for a 32-bit target, we should use 32-bit - // offsets. - uint64_t Offset64 = Offset.getQuantity(); - uint64_t ElemSize64 = ElementSize.getQuantity(); - uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); - Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); + // Check this LValue refers to an object. If not, set the designator to be + // invalid and emit a diagnostic. + bool checkSubobject(EvalInfo &Info, Expr const *E, CheckSubobjectKind CSK) { + return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) && + Designator.checkSubobject(Info, E, CSK); + } - if (checkNullPointer(Info, E, CSK_ArrayIndex)) - Designator.adjustIndex(Info, E, Index); - clearIsNullPointer(); + void addDecl(EvalInfo &Info, Expr const *E, Decl const *D, + bool Virtual = false) { + if (checkSubobject(Info, E, isa(D) ? CSK_Field : CSK_Base)) + Designator.addDeclUnchecked(D, Virtual); + } + void addUnsizedArray(EvalInfo &Info, Expr const *E, QualType ElemTy) { + if (!Designator.Entries.empty()) { + Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array); + Designator.setInvalid(); + return; } - void adjustOffset(CharUnits N) { - Offset += N; - if (N.getQuantity()) - clearIsNullPointer(); + if (checkSubobject(Info, E, CSK_ArrayToPointer)) { + assert(getType(Base)->isPointerType() || getType(Base)->isArrayType()); + Designator.FirstEntryIsAnUnsizedArray = true; + Designator.addUnsizedArrayUnchecked(ElemTy); } - }; + } + void addArray(EvalInfo &Info, Expr const *E, ConstantArrayType const *CAT) { + if (checkSubobject(Info, E, CSK_ArrayToPointer)) + Designator.addArrayUnchecked(CAT); + } + void addComplex(EvalInfo &Info, Expr const *E, QualType EltTy, bool Imag) { + if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real)) + Designator.addComplexUnchecked(EltTy, Imag); + } + void clearIsNullPointer() { IsNullPtr = false; } + void adjustOffsetAndIndex(EvalInfo &Info, Expr const *E, APSInt const &Index, + CharUnits ElementSize) { + // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB, + // but we're not required to diagnose it and it's valid in C++.) + if (!Index) + return; - struct MemberPtr { - MemberPtr() {} - explicit MemberPtr(const ValueDecl *Decl) : - DeclAndIsDerivedMember(Decl, false), Path() {} - - /// The member or (direct or indirect) field referred to by this member - /// pointer, or 0 if this is a null member pointer. - const ValueDecl *getDecl() const { - return DeclAndIsDerivedMember.getPointer(); - } - /// Is this actually a member of some type derived from the relevant class? - bool isDerivedMember() const { - return DeclAndIsDerivedMember.getInt(); - } - /// Get the class which the declaration actually lives in. - const CXXRecordDecl *getContainingRecord() const { - return cast( - DeclAndIsDerivedMember.getPointer()->getDeclContext()); - } - - void moveInto(APValue &V) const { - V = APValue(getDecl(), isDerivedMember(), Path); - } - void setFrom(const APValue &V) { - assert(V.isMemberPointer()); - DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); - DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); - Path.clear(); - ArrayRef P = V.getMemberPointerPath(); - Path.insert(Path.end(), P.begin(), P.end()); - } - - /// DeclAndIsDerivedMember - The member declaration, and a flag indicating - /// whether the member is a member of some class derived from the class type - /// of the member pointer. - llvm::PointerIntPair DeclAndIsDerivedMember; - /// Path - The path of base/derived classes from the member declaration's - /// class (exclusive) to the class type of the member pointer (inclusive). - SmallVector Path; - - /// Perform a cast towards the class of the Decl (either up or down the - /// hierarchy). - bool castBack(const CXXRecordDecl *Class) { - assert(!Path.empty()); - const CXXRecordDecl *Expected; - if (Path.size() >= 2) - Expected = Path[Path.size() - 2]; - else - Expected = getContainingRecord(); - if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { - // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), - // if B does not contain the original member and is not a base or - // derived class of the class containing the original member, the result - // of the cast is undefined. - // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to - // (D::*). We consider that to be a language defect. - return false; - } - Path.pop_back(); - return true; + // Compute the new offset in the appropriate width, wrapping at 64 bits. + // FIXME: When compiling for a 32-bit target, we should use 32-bit + // offsets. + uint64_t Offset64 = Offset.getQuantity(); + uint64_t ElemSize64 = ElementSize.getQuantity(); + uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); + Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64); + + if (checkNullPointer(Info, E, CSK_ArrayIndex)) + Designator.adjustIndex(Info, E, Index); + clearIsNullPointer(); + } + void adjustOffset(CharUnits N) { + Offset += N; + if (N.getQuantity()) + clearIsNullPointer(); + } +}; + +struct MemberPtr { + MemberPtr() {} + explicit MemberPtr(ValueDecl const *Decl) + : DeclAndIsDerivedMember(Decl, false), Path() {} + + /// The member or (direct or indirect) field referred to by this member + /// pointer, or 0 if this is a null member pointer. + ValueDecl const *getDecl() const { + return DeclAndIsDerivedMember.getPointer(); + } + /// Is this actually a member of some type derived from the relevant class? + bool isDerivedMember() const { return DeclAndIsDerivedMember.getInt(); } + /// Get the class which the declaration actually lives in. + CXXRecordDecl const *getContainingRecord() const { + return cast( + DeclAndIsDerivedMember.getPointer()->getDeclContext()); + } + + void moveInto(APValue &V) const { + V = APValue(getDecl(), isDerivedMember(), Path); + } + void setFrom(APValue const &V) { + assert(V.isMemberPointer()); + DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl()); + DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember()); + Path.clear(); + ArrayRef P = V.getMemberPointerPath(); + Path.insert(Path.end(), P.begin(), P.end()); + } + + /// DeclAndIsDerivedMember - The member declaration, and a flag indicating + /// whether the member is a member of some class derived from the class type + /// of the member pointer. + llvm::PointerIntPair DeclAndIsDerivedMember; + /// Path - The path of base/derived classes from the member declaration's + /// class (exclusive) to the class type of the member pointer (inclusive). + SmallVector Path; + + /// Perform a cast towards the class of the Decl (either up or down the + /// hierarchy). + bool castBack(CXXRecordDecl const *Class) { + assert(!Path.empty()); + CXXRecordDecl const *Expected; + if (Path.size() >= 2) + Expected = Path[Path.size() - 2]; + else + Expected = getContainingRecord(); + if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) { + // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*), + // if B does not contain the original member and is not a base or + // derived class of the class containing the original member, the result + // of the cast is undefined. + // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to + // (D::*). We consider that to be a language defect. + return false; } - /// Perform a base-to-derived member pointer cast. - bool castToDerived(const CXXRecordDecl *Derived) { - if (!getDecl()) - return true; - if (!isDerivedMember()) { - Path.push_back(Derived); - return true; - } - if (!castBack(Derived)) - return false; - if (Path.empty()) - DeclAndIsDerivedMember.setInt(false); + Path.pop_back(); + return true; + } + /// Perform a base-to-derived member pointer cast. + bool castToDerived(CXXRecordDecl const *Derived) { + if (!getDecl()) + return true; + if (!isDerivedMember()) { + Path.push_back(Derived); return true; } - /// Perform a derived-to-base member pointer cast. - bool castToBase(const CXXRecordDecl *Base) { - if (!getDecl()) - return true; - if (Path.empty()) - DeclAndIsDerivedMember.setInt(true); - if (isDerivedMember()) { - Path.push_back(Base); - return true; - } - return castBack(Base); - } - }; - - /// Compare two member pointers, which are assumed to be of the same type. - static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) { - if (!LHS.getDecl() || !RHS.getDecl()) - return !LHS.getDecl() && !RHS.getDecl(); - if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) + if (!castBack(Derived)) return false; - return LHS.Path == RHS.Path; + if (Path.empty()) + DeclAndIsDerivedMember.setInt(false); + return true; + } + /// Perform a derived-to-base member pointer cast. + bool castToBase(CXXRecordDecl const *Base) { + if (!getDecl()) + return true; + if (Path.empty()) + DeclAndIsDerivedMember.setInt(true); + if (isDerivedMember()) { + Path.push_back(Base); + return true; + } + return castBack(Base); } +}; + +/// Compare two member pointers, which are assumed to be of the same type. +static bool operator==(MemberPtr const &LHS, MemberPtr const &RHS) { + if (!LHS.getDecl() || !RHS.getDecl()) + return !LHS.getDecl() && !RHS.getDecl(); + if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl()) + return false; + return LHS.Path == RHS.Path; } +} // namespace -static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E); -static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, - const LValue &This, const Expr *E, - bool AllowNonLiteralTypes = false); -static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, +static bool Evaluate(APValue &Result, EvalInfo &Info, Expr const *E); +static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, LValue const &This, + Expr const *E, bool AllowNonLiteralTypes = false); +static bool EvaluateLValue(Expr const *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK = false); -static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, +static bool EvaluatePointer(Expr const *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK = false); -static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, +static bool EvaluateMemberPointer(Expr const *E, MemberPtr &Result, EvalInfo &Info); -static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info); -static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info); -static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, +static bool EvaluateTemporary(Expr const *E, LValue &Result, EvalInfo &Info); +static bool EvaluateInteger(Expr const *E, APSInt &Result, EvalInfo &Info); +static bool EvaluateIntegerOrLValue(Expr const *E, APValue &Result, EvalInfo &Info); -static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info); -static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info); -static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, +static bool EvaluateFloat(Expr const *E, APFloat &Result, EvalInfo &Info); +static bool EvaluateComplex(Expr const *E, ComplexValue &Res, EvalInfo &Info); +static bool EvaluateAtomic(Expr const *E, LValue const *This, APValue &Result, EvalInfo &Info); -static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result); -static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, +static bool EvaluateAsRValue(EvalInfo &Info, Expr const *E, APValue &Result); +static bool EvaluateBuiltinStrLen(Expr const *E, uint64_t &Result, EvalInfo &Info); /// Evaluate an integer or fixed point expression into an APResult. -static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, +static bool EvaluateFixedPointOrInteger(Expr const *E, APFixedPoint &Result, EvalInfo &Info); /// Evaluate only a fixed point expression into an APResult. -static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, +static bool EvaluateFixedPoint(Expr const *E, APFixedPoint &Result, EvalInfo &Info); //===----------------------------------------------------------------------===// @@ -1851,8 +1813,8 @@ Int = -Int; } -template -APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T, +template +APValue &CallStackFrame::createTemporary(KeyT const *Key, QualType T, ScopeKind Scope, LValue &LV) { unsigned Version = getTempVersion(); APValue::LValueBase Base(Key, Index, Version); @@ -1861,7 +1823,7 @@ } /// Allocate storage for a parameter of a function call made in this frame. -APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD, +APValue &CallStackFrame::createParam(CallRef Args, ParmVarDecl const *PVD, LValue &LV) { assert(Args.CallIndex == Index && "creating parameter in wrong frame"); APValue::LValueBase Base(PVD, Index, Args.Version); @@ -1872,7 +1834,7 @@ return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call); } -APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key, +APValue &CallStackFrame::createLocal(APValue::LValueBase Base, void const *Key, QualType T, ScopeKind Scope) { assert(Base.getCallIndex() == Index && "lvalue for wrong frame"); unsigned Version = Base.getVersion(); @@ -1892,7 +1854,7 @@ return Result; } -APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) { +APValue *EvalInfo::createHeapAlloc(Expr const *E, QualType T, LValue &LV) { if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) { FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded); return nullptr; @@ -1920,19 +1882,19 @@ if (This && IsMemberCall) { APValue Val; This->moveInto(Val); - Val.printPretty(Out, Info.Ctx, - This->Designator.MostDerivedType); + Val.printPretty(Out, Info.Ctx, This->Designator.MostDerivedType); // FIXME: Add parens around Val if needed. Out << "->" << *Callee << '('; IsMemberCall = false; } for (FunctionDecl::param_const_iterator I = Callee->param_begin(), - E = Callee->param_end(); I != E; ++I, ++ArgIndex) { + E = Callee->param_end(); + I != E; ++I, ++ArgIndex) { if (ArgIndex > (unsigned)IsMemberCall) Out << ", "; - const ParmVarDecl *Param = *I; + ParmVarDecl const *Param = *I; APValue *V = Info.getParamSlot(Arguments, Param); if (V) V->printPretty(Out, Info.Ctx, Param->getType()); @@ -1949,7 +1911,7 @@ /// Evaluate an expression to see if it had side-effects, and discard its /// result. /// \return \c true if the caller should keep evaluating. -static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) { +static bool EvaluateIgnoredValue(EvalInfo &Info, Expr const *E) { assert(!E->isValueDependent()); APValue Scratch; if (!Evaluate(Scratch, Info, E)) @@ -1959,7 +1921,7 @@ } /// Should this call expression be treated as a string literal? -static bool IsStringLiteralCall(const CallExpr *E) { +static bool IsStringLiteralCall(CallExpr const *E) { unsigned Builtin = E->getBuiltinCallee(); return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || Builtin == Builtin::BI__builtin___NSStringMakeConstantString); @@ -1971,11 +1933,12 @@ // ... a null pointer value, or a prvalue core constant expression of type // std::nullptr_t. - if (!B) return true; + if (!B) + return true; - if (const ValueDecl *D = B.dyn_cast()) { + if (ValueDecl const *D = B.dyn_cast()) { // ... the address of an object with static storage duration, - if (const VarDecl *VD = dyn_cast(D)) + if (VarDecl const *VD = dyn_cast(D)) return VD->hasGlobalStorage(); if (isa(D)) return true; @@ -1987,12 +1950,12 @@ if (B.is() || B.is()) return true; - const Expr *E = B.get(); + Expr const *E = B.get(); switch (E->getStmtClass()) { default: return false; case Expr::CompoundLiteralExprClass: { - const CompoundLiteralExpr *CLE = cast(E); + CompoundLiteralExpr const *CLE = cast(E); return CLE->isFileScope() && CLE->isLValue(); } case Expr::MaterializeTemporaryExprClass: @@ -2027,24 +1990,24 @@ } } -static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) { - return LVal.Base.dyn_cast(); +static ValueDecl const *GetLValueBaseDecl(LValue const &LVal) { + return LVal.Base.dyn_cast(); } -static bool IsLiteralLValue(const LValue &Value) { +static bool IsLiteralLValue(LValue const &Value) { if (Value.getLValueCallIndex()) return false; - const Expr *E = Value.Base.dyn_cast(); + Expr const *E = Value.Base.dyn_cast(); return E && !isa(E); } -static bool IsWeakLValue(const LValue &Value) { - const ValueDecl *Decl = GetLValueBaseDecl(Value); +static bool IsWeakLValue(LValue const &Value) { + ValueDecl const *Decl = GetLValueBaseDecl(Value); return Decl && Decl->isWeak(); } -static bool isZeroSized(const LValue &Value) { - const ValueDecl *Decl = GetLValueBaseDecl(Value); +static bool isZeroSized(LValue const &Value) { + ValueDecl const *Decl = GetLValueBaseDecl(Value); if (Decl && isa(Decl)) { QualType Ty = Decl->getType(); if (Ty->isArrayType()) @@ -2054,14 +2017,13 @@ return false; } -static bool HasSameBase(const LValue &A, const LValue &B) { +static bool HasSameBase(LValue const &A, LValue const &B) { if (!A.getLValueBase()) return !B.getLValueBase(); if (!B.getLValueBase()) return false; - if (A.getLValueBase().getOpaqueValue() != - B.getLValueBase().getOpaqueValue()) + if (A.getLValueBase().getOpaqueValue() != B.getLValueBase().getOpaqueValue()) return false; return A.getLValueCallIndex() == B.getLValueCallIndex() && @@ -2070,7 +2032,7 @@ static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) { assert(Base && "no location for a null lvalue"); - const ValueDecl *VD = Base.dyn_cast(); + ValueDecl const *VD = Base.dyn_cast(); // For a parameter, find the corresponding call stack frame (if it still // exists), and point at the parameter of the function definition we actually @@ -2089,11 +2051,11 @@ if (VD) Info.Note(VD->getLocation(), diag::note_declared_at); - else if (const Expr *E = Base.dyn_cast()) + else if (Expr const *E = Base.dyn_cast()) Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here); else if (DynamicAllocLValue DA = Base.dyn_cast()) { // FIXME: Produce a note for dangling pointers too. - if (Optional Alloc = Info.lookupDynamicAlloc(DA)) + if (Optional Alloc = Info.lookupDynamicAlloc(DA)) Info.Note((*Alloc)->AllocExpr->getExprLoc(), diag::note_constexpr_dynamic_alloc_here); } @@ -2108,11 +2070,11 @@ /// Materialized temporaries that we've already checked to determine if they're /// initializsed by a constant expression. using CheckedTemporaries = - llvm::SmallPtrSet; + llvm::SmallPtrSet; static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, - QualType Type, const APValue &Value, + QualType Type, APValue const &Value, ConstantExprKind Kind, SourceLocation SubobjectLoc, CheckedTemporaries &CheckedTemps); @@ -2121,16 +2083,16 @@ /// value for an address or reference constant expression. Return true if we /// can fold this expression, whether or not it's a constant expression. static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, - QualType Type, const LValue &LVal, + QualType Type, LValue const &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps) { bool IsReferenceType = Type->isReferenceType(); APValue::LValueBase Base = LVal.getLValueBase(); - const SubobjectDesignator &Designator = LVal.getLValueDesignator(); + SubobjectDesignator const &Designator = LVal.getLValueDesignator(); - const Expr *BaseE = Base.dyn_cast(); - const ValueDecl *BaseVD = Base.dyn_cast(); + Expr const *BaseE = Base.dyn_cast(); + ValueDecl const *BaseVD = Base.dyn_cast(); // Additional restrictions apply in a template argument. We only enforce the // C++20 restrictions here; additional syntactic and semantic restrictions @@ -2172,10 +2134,9 @@ // assumed to be global here. if (!IsGlobalLValue(Base)) { if (Info.getLangOpts().CPlusPlus11) { - const ValueDecl *VD = Base.dyn_cast(); + ValueDecl const *VD = Base.dyn_cast(); Info.FFDiag(Loc, diag::note_constexpr_non_global, 1) - << IsReferenceType << !Designator.Entries.empty() - << !!VD << VD; + << IsReferenceType << !Designator.Entries.empty() << !!VD << VD; auto *VarD = dyn_cast_or_null(VD); if (VarD && VarD->isConstexpr()) { @@ -2208,7 +2169,7 @@ } if (BaseVD) { - if (const VarDecl *Var = dyn_cast(BaseVD)) { + if (VarDecl const *Var = dyn_cast(BaseVD)) { // Check if this is a thread-local variable. if (Var->getTLSKind()) // FIXME: Diagnostic! @@ -2220,7 +2181,7 @@ // FIXME: Diagnostic! return false; } - if (const auto *FD = dyn_cast(BaseVD)) { + if (auto const *FD = dyn_cast(BaseVD)) { // __declspec(dllimport) must be handled very carefully: // We must never initialize an expression with the thunk in C++. // Doing otherwise would allow the same id-expression to yield @@ -2236,7 +2197,7 @@ // FIXME: Diagnostic! return false; } - } else if (const auto *MTE = + } else if (auto const *MTE = dyn_cast_or_null(BaseE)) { if (CheckedTemps.insert(MTE).second) { QualType TempType = getType(Base); @@ -2250,8 +2211,8 @@ APValue *V = MTE->getOrCreateValue(false); assert(V && "evasluation result refers to uninitialised temporary"); if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression, - Info, MTE->getExprLoc(), TempType, *V, - Kind, SourceLocation(), CheckedTemps)) + Info, MTE->getExprLoc(), TempType, *V, Kind, + SourceLocation(), CheckedTemps)) return false; } } @@ -2271,7 +2232,7 @@ // Does this refer one past the end of some object? if (!Designator.Invalid && Designator.isOnePastTheEnd()) { Info.FFDiag(Loc, diag::note_constexpr_past_end, 1) - << !Designator.Entries.empty() << !!BaseVD << BaseVD; + << !Designator.Entries.empty() << !!BaseVD << BaseVD; NoteLValueLocation(Info, Base); } @@ -2283,10 +2244,10 @@ static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, - const APValue &Value, + APValue const &Value, ConstantExprKind Kind) { - const ValueDecl *Member = Value.getMemberPointerDecl(); - const auto *FD = dyn_cast_or_null(Member); + ValueDecl const *Member = Value.getMemberPointerDecl(); + auto const *FD = dyn_cast_or_null(Member); if (!FD) return true; if (FD->isConsteval()) { @@ -2300,8 +2261,8 @@ /// Check that this core constant expression is of literal type, and if not, /// produce an appropriate diagnostic. -static bool CheckLiteralType(EvalInfo &Info, const Expr *E, - const LValue *This = nullptr) { +static bool CheckLiteralType(EvalInfo &Info, Expr const *E, + LValue const *This = nullptr) { if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx)) return true; @@ -2323,8 +2284,7 @@ // Prvalue constant expressions must be of literal types. if (Info.getLangOpts().CPlusPlus11) - Info.FFDiag(E, diag::note_constexpr_nonliteral) - << E->getType(); + Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType(); else Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); return false; @@ -2332,13 +2292,12 @@ static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, - QualType Type, const APValue &Value, + QualType Type, APValue const &Value, ConstantExprKind Kind, SourceLocation SubobjectLoc, CheckedTemporaries &CheckedTemps) { if (!Value.hasValue()) { - Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) - << true << Type; + Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized) << true << Type; if (SubobjectLoc.isValid()) Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here); return false; @@ -2346,7 +2305,7 @@ // We allow _Atomic(T) to be initialized from anything that T can be // initialized from. - if (const AtomicType *AT = Type->getAs()) + if (AtomicType const *AT = Type->getAs()) Type = AT->getValueType(); // Core issue 1454: For a literal constant expression of array or class type, @@ -2374,9 +2333,9 @@ } if (Value.isStruct()) { RecordDecl *RD = Type->castAs()->getDecl(); - if (const CXXRecordDecl *CD = dyn_cast(RD)) { + if (CXXRecordDecl const *CD = dyn_cast(RD)) { unsigned BaseIndex = 0; - for (const CXXBaseSpecifier &BS : CD->bases()) { + for (CXXBaseSpecifier const &BS : CD->bases()) { if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), Value.getStructBase(BaseIndex), Kind, BS.getBeginLoc(), CheckedTemps)) @@ -2384,13 +2343,13 @@ ++BaseIndex; } } - for (const auto *I : RD->fields()) { + for (auto const *I : RD->fields()) { if (I->isUnnamedBitfield()) continue; if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(), - Value.getStructField(I->getFieldIndex()), - Kind, I->getLocation(), CheckedTemps)) + Value.getStructField(I->getFieldIndex()), Kind, + I->getLocation(), CheckedTemps)) return false; } } @@ -2405,7 +2364,8 @@ if (Value.isMemberPointer() && CERK == CheckEvaluationResultKind::ConstantExpression) - return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind); + return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, + Kind); // Everything else is fine. return true; @@ -2415,7 +2375,7 @@ /// constant expression. If not, report an appropriate diagnostic. Does not /// check that the expression is of literal type. static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, - QualType Type, const APValue &Value, + QualType Type, APValue const &Value, ConstantExprKind Kind) { // Nothing to check for a constant expression of type 'cv void'. if (Type->isVoidType()) @@ -2430,7 +2390,7 @@ /// Check that this evaluated value is fully-initialized and can be loaded by /// an lvalue-to-rvalue conversion. static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, - QualType Type, const APValue &Value) { + QualType Type, APValue const &Value) { CheckedTemporaries CheckedTemps; return CheckEvaluationResult( CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value, @@ -2451,7 +2411,7 @@ return true; } -static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) { +static bool EvalPointerValueAsBool(APValue const &Value, bool &Result) { // A null base expression indicates a null pointer. These are always // evaluatable, and they are false unless the offset is zero. if (!Value.getLValueBase()) { @@ -2462,11 +2422,11 @@ // We have a non-null base. These are generally known to be true, but if it's // a weak declaration it can be null at runtime. Result = true; - const ValueDecl *Decl = Value.getLValueBase().dyn_cast(); + ValueDecl const *Decl = Value.getLValueBase().dyn_cast(); return !Decl || !Decl->isWeak(); } -static bool HandleConversionToBool(const APValue &Val, bool &Result) { +static bool HandleConversionToBool(APValue const &Val, bool &Result) { switch (Val.getKind()) { case APValue::None: case APValue::Indeterminate: @@ -2504,7 +2464,7 @@ llvm_unreachable("unknown APValue kind"); } -static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, +static bool EvaluateAsBooleanCondition(Expr const *E, bool &Result, EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition"); @@ -2514,16 +2474,15 @@ return HandleConversionToBool(Val, Result); } -template -static bool HandleOverflow(EvalInfo &Info, const Expr *E, - const T &SrcValue, QualType DestType) { - Info.CCEDiag(E, diag::note_constexpr_overflow) - << SrcValue << DestType; +template +static bool HandleOverflow(EvalInfo &Info, Expr const *E, const T &SrcValue, + QualType DestType) { + Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType; return Info.noteUndefinedBehavior(); } -static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, - QualType SrcType, const APFloat &Value, +static bool HandleFloatToIntCast(EvalInfo &Info, Expr const *E, + QualType SrcType, APFloat const &Value, QualType DestType, APSInt &Result) { unsigned DestWidth = Info.Ctx.getIntWidth(DestType); // Determine whether we are converting to unsigned or signed. @@ -2531,8 +2490,8 @@ Result = APSInt(DestWidth, !DestSigned); bool ignored; - if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) - & APFloat::opInvalidOp) + if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored) & + APFloat::opInvalidOp) return HandleOverflow(Info, E, Value, DestType); return true; } @@ -2543,7 +2502,7 @@ /// If rounding mode is unknown at compile time, still try to evaluate the /// expression. If the result is exact, it does not depend on rounding mode. /// So return "tonearest" mode instead of "dynamic". -static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E, +static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, Expr const *E, bool &DynamicRM) { llvm::RoundingMode RM = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode(); @@ -2554,7 +2513,7 @@ } /// Check if the given evaluation result is allowed for constant evaluation. -static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, +static bool checkFloatingPointResult(EvalInfo &Info, Expr const *E, APFloat::opStatus St) { // In a constant context, assume that any dynamic rounding mode or FP // exception state matches the default floating-point environment. @@ -2594,7 +2553,7 @@ return true; } -static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, +static bool HandleFloatToFloatCast(EvalInfo &Info, Expr const *E, QualType SrcType, QualType DestType, APFloat &Result) { assert(isa(E) || isa(E)); @@ -2607,9 +2566,9 @@ return checkFloatingPointResult(Info, E, St); } -static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, +static APSInt HandleIntToIntCast(EvalInfo &Info, Expr const *E, QualType DestType, QualType SrcType, - const APSInt &Value) { + APSInt const &Value) { unsigned DestWidth = Info.Ctx.getIntWidth(DestType); // Figure out if this is a truncate, extend or noop cast. // If the input is signed, do a sign extend, noop, or truncate. @@ -2620,13 +2579,13 @@ return Result; } -static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, - const FPOptions FPO, - QualType SrcType, const APSInt &Value, - QualType DestType, APFloat &Result) { +static bool HandleIntToFloatCast(EvalInfo &Info, Expr const *E, + const FPOptions FPO, QualType SrcType, + APSInt const &Value, QualType DestType, + APFloat &Result) { Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1); APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), - APFloat::rmNearestTiesToEven); + APFloat::rmNearestTiesToEven); if (!Info.InConstantContext && St != llvm::APFloatBase::opOK && FPO.isFPConstrained()) { Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); @@ -2635,8 +2594,8 @@ return true; } -static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, - APValue &Value, const FieldDecl *FD) { +static bool truncateBitfieldValue(EvalInfo &Info, Expr const *E, APValue &Value, + FieldDecl const *FD) { assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield"); if (!Value.isInt()) { @@ -2656,7 +2615,7 @@ return true; } -static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E, +static bool EvalAndBitcastToAPInt(EvalInfo &Info, Expr const *E, llvm::APInt &Res) { APValue SVal; if (!Evaluate(SVal, Info, E)) @@ -2691,9 +2650,9 @@ } unsigned BaseEltSize = EltAsInt.getBitWidth(); if (BigEndian) - Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize); + Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i * EltSize + BaseEltSize); else - Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize); + Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i * EltSize); } return true; } @@ -2706,9 +2665,9 @@ /// Perform the given integer operation, which is known to need at most BitWidth /// bits, and check for overflow in the original type (if that type was not an /// unsigned type). -template -static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, - const APSInt &LHS, const APSInt &RHS, +template +static bool CheckedIntArithmetic(EvalInfo &Info, Expr const *E, + APSInt const &LHS, APSInt const &RHS, unsigned BitWidth, Operation Op, APSInt &Result) { if (LHS.isUnsigned()) { @@ -2729,7 +2688,7 @@ } /// Perform the given binary integer operation. -static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS, +static bool handleIntIntBinOp(EvalInfo &Info, Expr const *E, APSInt const &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result) { switch (Opcode) { @@ -2745,9 +2704,15 @@ case BO_Sub: return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1, std::minus(), Result); - case BO_And: Result = LHS & RHS; return true; - case BO_Xor: Result = LHS ^ RHS; return true; - case BO_Or: Result = LHS | RHS; return true; + case BO_And: + Result = LHS & RHS; + return true; + case BO_Xor: + Result = LHS ^ RHS; + return true; + case BO_Or: + Result = LHS | RHS; + return true; case BO_Div: case BO_Rem: if (RHS == 0) { @@ -2757,8 +2722,8 @@ Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS); // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports // this operation and gives the two's complement result. - if (RHS.isNegative() && RHS.isAllOnesValue() && - LHS.isSigned() && LHS.isMinSignedValue()) + if (RHS.isNegative() && RHS.isAllOnesValue() && LHS.isSigned() && + LHS.isMinSignedValue()) return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType()); return true; @@ -2766,7 +2731,7 @@ if (Info.getLangOpts().OpenCL) // OpenCL 6.3j: shift values are effectively % word size of LHS. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), - static_cast(LHS.getBitWidth() - 1)), + static_cast(LHS.getBitWidth() - 1)), RHS.isUnsigned()); else if (RHS.isSigned() && RHS.isNegative()) { // During constant-folding, a negative shift is an opposite shift. Such @@ -2778,10 +2743,10 @@ shift_left: // C++11 [expr.shift]p1: Shift width must be less than the bit width of // the shifted type. - unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); + unsigned SA = (unsigned)RHS.getLimitedValue(LHS.getBitWidth() - 1); if (SA != RHS) { Info.CCEDiag(E, diag::note_constexpr_large_shift) - << RHS << E->getType() << LHS.getBitWidth(); + << RHS << E->getType() << LHS.getBitWidth(); } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) { // C++11 [expr.shift]p2: A signed left shift must have a non-negative // operand, and must not overflow the corresponding unsigned type. @@ -2799,7 +2764,7 @@ if (Info.getLangOpts().OpenCL) // OpenCL 6.3j: shift values are effectively % word size of LHS. RHS &= APSInt(llvm::APInt(RHS.getBitWidth(), - static_cast(LHS.getBitWidth() - 1)), + static_cast(LHS.getBitWidth() - 1)), RHS.isUnsigned()); else if (RHS.isSigned() && RHS.isNegative()) { // During constant-folding, a negative shift is an opposite shift. Such a @@ -2811,29 +2776,41 @@ shift_right: // C++11 [expr.shift]p1: Shift width must be less than the bit width of the // shifted type. - unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1); + unsigned SA = (unsigned)RHS.getLimitedValue(LHS.getBitWidth() - 1); if (SA != RHS) Info.CCEDiag(E, diag::note_constexpr_large_shift) - << RHS << E->getType() << LHS.getBitWidth(); + << RHS << E->getType() << LHS.getBitWidth(); Result = LHS >> SA; return true; } - case BO_LT: Result = LHS < RHS; return true; - case BO_GT: Result = LHS > RHS; return true; - case BO_LE: Result = LHS <= RHS; return true; - case BO_GE: Result = LHS >= RHS; return true; - case BO_EQ: Result = LHS == RHS; return true; - case BO_NE: Result = LHS != RHS; return true; + case BO_LT: + Result = LHS < RHS; + return true; + case BO_GT: + Result = LHS > RHS; + return true; + case BO_LE: + Result = LHS <= RHS; + return true; + case BO_GE: + Result = LHS >= RHS; + return true; + case BO_EQ: + Result = LHS == RHS; + return true; + case BO_NE: + Result = LHS != RHS; + return true; case BO_Cmp: llvm_unreachable("BO_Cmp should be handled elsewhere"); } } /// Perform the given binary floating-point operation, in-place, on LHS. -static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, +static bool handleFloatFloatBinOp(EvalInfo &Info, BinaryOperator const *E, APFloat &LHS, BinaryOperatorKind Opcode, - const APFloat &RHS) { + APFloat const &RHS) { bool DynamicRM; llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM); APFloat::opStatus St; @@ -2871,9 +2848,9 @@ return checkFloatingPointResult(Info, E, St); } -static bool handleLogicalOpForVector(const APInt &LHSValue, +static bool handleLogicalOpForVector(APInt const &LHSValue, BinaryOperatorKind Opcode, - const APInt &RHSValue, APInt &Result) { + APInt const &RHSValue, APInt &Result) { bool LHS = (LHSValue != 0); bool RHS = (RHSValue != 0); @@ -2883,9 +2860,9 @@ Result = LHS || RHS; return true; } -static bool handleLogicalOpForVector(const APFloat &LHSValue, +static bool handleLogicalOpForVector(APFloat const &LHSValue, BinaryOperatorKind Opcode, - const APFloat &RHSValue, APInt &Result) { + APFloat const &RHSValue, APInt &Result) { bool LHS = !LHSValue.isZero(); bool RHS = !RHSValue.isZero(); @@ -2896,9 +2873,9 @@ return true; } -static bool handleLogicalOpForVector(const APValue &LHSValue, +static bool handleLogicalOpForVector(APValue const &LHSValue, BinaryOperatorKind Opcode, - const APValue &RHSValue, APInt &Result) { + APValue const &RHSValue, APInt &Result) { // The result is always an int type, however operands match the first. if (LHSValue.getKind() == APValue::Int) return handleLogicalOpForVector(LHSValue.getInt(), Opcode, @@ -2910,8 +2887,8 @@ template static bool -handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, - const APTy &RHSValue, APInt &Result) { +handleCompareOpForVectorHelper(APTy const &LHSValue, BinaryOperatorKind Opcode, + APTy const &RHSValue, APInt &Result) { switch (Opcode) { default: llvm_unreachable("unsupported binary operator"); @@ -2938,9 +2915,9 @@ return true; } -static bool handleCompareOpForVector(const APValue &LHSValue, +static bool handleCompareOpForVector(APValue const &LHSValue, BinaryOperatorKind Opcode, - const APValue &RHSValue, APInt &Result) { + APValue const &RHSValue, APInt &Result) { // The result is always an int type, however operands match the first. if (LHSValue.getKind() == APValue::Int) return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode, @@ -2951,14 +2928,14 @@ } // Perform binary operations for vector types, in place on the LHS. -static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, +static bool handleVectorVectorBinOp(EvalInfo &Info, BinaryOperator const *E, BinaryOperatorKind Opcode, APValue &LHSValue, - const APValue &RHSValue) { + APValue const &RHSValue) { assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI && "Operation not supported on vector types"); - const auto *VT = E->getType()->castAs(); + auto const *VT = E->getType()->castAs(); unsigned NumElements = VT->getNumElements(); QualType EltTy = VT->getElementType(); @@ -3022,8 +2999,8 @@ /// Cast an lvalue referring to a base subobject to a derived class, by /// truncating the lvalue's path to the given length. -static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, - const RecordDecl *TruncatedType, +static bool CastToDerivedClass(EvalInfo &Info, Expr const *E, LValue &Result, + RecordDecl const *TruncatedType, unsigned TruncatedElements) { SubobjectDesignator &D = Result.Designator; @@ -3036,11 +3013,12 @@ return false; // Truncate the path to the subobject, and remove any derived-to-base offsets. - const RecordDecl *RD = TruncatedType; + RecordDecl const *RD = TruncatedType; for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) { - if (RD->isInvalidDecl()) return false; - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); - const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]); + if (RD->isInvalidDecl()) + return false; + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(RD); + CXXRecordDecl const *Base = getAsBaseClass(D.Entries[I]); if (isVirtualBaseClass(D.Entries[I])) Result.Offset -= Layout.getVBaseClassOffset(Base); else @@ -3051,12 +3029,13 @@ return true; } -static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, - const CXXRecordDecl *Derived, - const CXXRecordDecl *Base, - const ASTRecordLayout *RL = nullptr) { +static bool HandleLValueDirectBase(EvalInfo &Info, Expr const *E, LValue &Obj, + CXXRecordDecl const *Derived, + CXXRecordDecl const *Base, + ASTRecordLayout const *RL = nullptr) { if (!RL) { - if (Derived->isInvalidDecl()) return false; + if (Derived->isInvalidDecl()) + return false; RL = &Info.Ctx.getASTRecordLayout(Derived); } @@ -3065,10 +3044,10 @@ return true; } -static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, - const CXXRecordDecl *DerivedDecl, - const CXXBaseSpecifier *Base) { - const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); +static bool HandleLValueBase(EvalInfo &Info, Expr const *E, LValue &Obj, + CXXRecordDecl const *DerivedDecl, + CXXBaseSpecifier const *Base) { + CXXRecordDecl const *BaseDecl = Base->getType()->getAsCXXRecordDecl(); if (!Base->isVirtual()) return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl); @@ -3083,20 +3062,20 @@ return false; // Find the virtual base class. - if (DerivedDecl->isInvalidDecl()) return false; - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); + if (DerivedDecl->isInvalidDecl()) + return false; + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl); Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl); Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true); return true; } -static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, +static bool HandleLValueBasePath(EvalInfo &Info, CastExpr const *E, QualType Type, LValue &Result) { for (CastExpr::path_const_iterator PathI = E->path_begin(), PathE = E->path_end(); PathI != PathE; ++PathI) { - if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), - *PathI)) + if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(), *PathI)) return false; Type = (*PathI)->getType(); } @@ -3104,9 +3083,9 @@ } /// Cast an lvalue referring to a derived class to a known base subobject. -static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, - const CXXRecordDecl *DerivedRD, - const CXXRecordDecl *BaseRD) { +static bool CastToBaseClass(EvalInfo &Info, Expr const *E, LValue &Result, + CXXRecordDecl const *DerivedRD, + CXXRecordDecl const *BaseRD) { CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/true, /*DetectVirtual=*/false); if (!DerivedRD->isDerivedFrom(BaseRD, Paths)) @@ -3120,11 +3099,12 @@ /// Update LVal to refer to the given field, which must be a member of the type /// currently described by LVal. -static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, - const FieldDecl *FD, - const ASTRecordLayout *RL = nullptr) { +static bool HandleLValueMember(EvalInfo &Info, Expr const *E, LValue &LVal, + FieldDecl const *FD, + ASTRecordLayout const *RL = nullptr) { if (!RL) { - if (FD->getParent()->isInvalidDecl()) return false; + if (FD->getParent()->isInvalidDecl()) + return false; RL = &Info.Ctx.getASTRecordLayout(FD->getParent()); } @@ -3135,18 +3115,18 @@ } /// Update LVal to refer to the given indirect field. -static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, +static bool HandleLValueIndirectMember(EvalInfo &Info, Expr const *E, LValue &LVal, - const IndirectFieldDecl *IFD) { - for (const auto *C : IFD->chain()) + IndirectFieldDecl const *IFD) { + for (auto const *C : IFD->chain()) if (!HandleLValueMember(Info, E, LVal, cast(C))) return false; return true; } /// Get the size of the given type in char units. -static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, - QualType Type, CharUnits &Size) { +static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, + CharUnits &Size) { // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc // extension. if (Type->isVoidType() || Type->isFunctionType()) { @@ -3176,7 +3156,7 @@ /// \param LVal - The pointer value to be updated. /// \param EltTy - The pointee type represented by LVal. /// \param Adjustment - The adjustment, in objects of type EltTy, to add. -static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, +static bool HandleLValueArrayAdjustment(EvalInfo &Info, Expr const *E, LValue &LVal, QualType EltTy, APSInt Adjustment) { CharUnits SizeOfPointee; @@ -3187,7 +3167,7 @@ return true; } -static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, +static bool HandleLValueArrayAdjustment(EvalInfo &Info, Expr const *E, LValue &LVal, QualType EltTy, int64_t Adjustment) { return HandleLValueArrayAdjustment(Info, E, LVal, EltTy, @@ -3199,7 +3179,7 @@ /// \param LVal - The lvalue to be updated. /// \param EltTy - The complex number's component type. /// \param Imag - False for the real component, true for the imaginary. -static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, +static bool HandleLValueComplexElement(EvalInfo &Info, Expr const *E, LValue &LVal, QualType EltTy, bool Imag) { if (Imag) { @@ -3221,8 +3201,8 @@ /// \param Frame The frame in which the variable was created. Must be null /// if this variable is not local to the evaluation. /// \param Result Filled in with a pointer to the value of the variable. -static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, - const VarDecl *VD, CallStackFrame *Frame, +static bool evaluateVarDeclInit(EvalInfo &Info, Expr const *E, + VarDecl const *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result) { APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version); @@ -3265,8 +3245,7 @@ !Info.CurrentCall->Callee || !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) { if (Info.getLangOpts().CPlusPlus11) { - Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) - << VD; + Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD; NoteLValueLocation(Info, Base); } else { Info.FFDiag(E); @@ -3278,13 +3257,12 @@ // Dig out the initializer, and use the declaration which it's attached to. // FIXME: We should eventually check whether the variable has a reachable // initializing declaration. - const Expr *Init = VD->getAnyInitializer(VD); + Expr const *Init = VD->getAnyInitializer(VD); if (!Init) { // Don't diagnose during potential constant expression checking; an // initializer might be added later. if (!Info.checkingPotentialConstantExpression()) { - Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) - << VD; + Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) << VD; NoteLValueLocation(Info, Base); } return false; @@ -3298,9 +3276,11 @@ // have been value-dependent too), so diagnose that. assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx)); if (!Info.checkingPotentialConstantExpression()) { - Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 - ? diag::note_constexpr_ltor_non_constexpr - : diag::note_constexpr_ltor_non_integral, 1) + Info.FFDiag(E, + Info.getLangOpts().CPlusPlus11 + ? diag::note_constexpr_ltor_non_constexpr + : diag::note_constexpr_ltor_non_integral, + 1) << VD << VD->getType(); NoteLValueLocation(Info, Base); } @@ -3346,12 +3326,13 @@ /// Get the base index of the given base class within an APValue representing /// the given derived class. -static unsigned getBaseIndex(const CXXRecordDecl *Derived, - const CXXRecordDecl *Base) { +static unsigned getBaseIndex(CXXRecordDecl const *Derived, + CXXRecordDecl const *Base) { Base = Base->getCanonicalDecl(); unsigned Index = 0; for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(), - E = Derived->bases_end(); I != E; ++I, ++Index) { + E = Derived->bases_end(); + I != E; ++I, ++Index) { if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base) return Index; } @@ -3360,13 +3341,13 @@ } /// Extract the value of a character from a string literal. -static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, +static APSInt extractStringLiteralCharacter(EvalInfo &Info, Expr const *Lit, uint64_t Index) { assert(!isa(Lit) && "SourceLocExpr should have already been converted to a StringLiteral"); // FIXME: Support MakeStringConstant - if (const auto *ObjCEnc = dyn_cast(Lit)) { + if (auto const *ObjCEnc = dyn_cast(Lit)) { std::string Str; Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str); assert(Index <= Str.size() && "Index too large"); @@ -3375,9 +3356,8 @@ if (auto PE = dyn_cast(Lit)) Lit = PE->getFunctionName(); - const StringLiteral *S = cast(Lit); - const ConstantArrayType *CAT = - Info.Ctx.getAsConstantArrayType(S->getType()); + StringLiteral const *S = cast(Lit); + ConstantArrayType const *CAT = Info.Ctx.getAsConstantArrayType(S->getType()); assert(CAT && "string literal isn't an array"); QualType CharType = CAT->getElementType(); assert(CharType->isIntegerType() && "unexpected character type"); @@ -3393,18 +3373,18 @@ // // FIXME: This is inefficient; we should probably introduce something similar // to the LLVM ConstantDataArray to make this cheaper. -static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, +static void expandStringLiteral(EvalInfo &Info, StringLiteral const *S, APValue &Result, QualType AllocType = QualType()) { - const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( + ConstantArrayType const *CAT = Info.Ctx.getAsConstantArrayType( AllocType.isNull() ? S->getType() : AllocType); assert(CAT && "string literal isn't an array"); QualType CharType = CAT->getElementType(); assert(CharType->isIntegerType() && "unexpected character type"); unsigned Elts = CAT->getSize().getZExtValue(); - Result = APValue(APValue::UninitArray(), - std::min(S->getLength(), Elts), Elts); + Result = + APValue(APValue::UninitArray(), std::min(S->getLength(), Elts), Elts); APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(), CharType->isUnsignedIntegerType()); if (Result.hasArrayFiller()) @@ -3422,7 +3402,7 @@ // Always at least double the number of elements for which we store a value. unsigned OldElts = Array.getArrayInitializedElts(); - unsigned NewElts = std::max(Index+1, OldElts * 2); + unsigned NewElts = std::max(Index + 1, OldElts * 2); NewElts = std::min(Size, std::max(NewElts, 8u)); // Copy the data across. @@ -3441,12 +3421,12 @@ /// is trivial. Note that this is never true for a union type with fields /// (because the copy always "reads" the active member) and always true for /// a non-class type. -static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD); +static bool isReadByLvalueToRvalueConversion(CXXRecordDecl const *RD); static bool isReadByLvalueToRvalueConversion(QualType T) { CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); return !RD || isReadByLvalueToRvalueConversion(RD); } -static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) { +static bool isReadByLvalueToRvalueConversion(CXXRecordDecl const *RD) { // FIXME: A trivial copy of a union copies the object representation, even if // the union is empty. if (RD->isUnion()) @@ -3468,7 +3448,7 @@ /// Diagnose an attempt to read from any unreadable field within the specified /// type, which might be a class type. -static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, +static bool diagnoseMutableFields(EvalInfo &Info, Expr const *E, AccessKinds AK, QualType T) { CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); if (!RD) @@ -3519,7 +3499,7 @@ // A temporary lifetime-extended by the variable whose initializer we're // evaluating. - if (auto *BaseE = Base.dyn_cast()) + if (auto *BaseE = Base.dyn_cast()) if (auto *BaseMTE = dyn_cast(BaseE)) return Info.EvaluatingDecl == BaseMTE->getExtendingDecl(); return false; @@ -3569,7 +3549,7 @@ // FIXME: Should we also allow this in C++11? if (!Info.getLangOpts().CPlusPlus14) return false; - return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true); + return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/ true); } explicit operator bool() const { return !Type.isNull(); } @@ -3591,10 +3571,10 @@ } /// Find the designated sub-object of an rvalue. -template +template typename SubobjectHandler::result_type -findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, - const SubobjectDesignator &Sub, SubobjectHandler &handler) { +findSubobject(EvalInfo &Info, Expr const *E, CompleteObject const &Obj, + SubobjectDesignator const &Sub, SubobjectHandler &handler) { if (Sub.Invalid) // A diagnostic will have already been produced. return handler.failed(); @@ -3611,12 +3591,13 @@ APValue *O = Obj.Value; QualType ObjType = Obj.Type; - const FieldDecl *LastField = nullptr; - const FieldDecl *VolatileField = nullptr; + FieldDecl const *LastField = nullptr; + FieldDecl const *VolatileField = nullptr; // Walk the designator's path to find the subobject. for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) { - // Reading an indeterminate value is undefined, but assigning over one is OK. + // Reading an indeterminate value is undefined, but assigning over one is + // OK. if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) || (O->isIndeterminate() && !isValidIndeterminateAccess(handler.AccessKind))) { @@ -3632,9 +3613,9 @@ if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) && ObjType->isRecordType() && Info.isEvaluatingCtorDtor( - Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(), - Sub.Entries.begin() + I)) != - ConstructionPhase::None) { + Obj.Base, + llvm::makeArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) != + ConstructionPhase::None) { ObjType = Info.Ctx.getCanonicalType(ObjType); ObjType.removeLocalConst(); ObjType.removeLocalVolatile(); @@ -3647,18 +3628,18 @@ if (Info.getLangOpts().CPlusPlus) { int DiagKind; SourceLocation Loc; - const NamedDecl *Decl = nullptr; + NamedDecl const *Decl = nullptr; if (VolatileField) { DiagKind = 2; Loc = VolatileField->getLocation(); Decl = VolatileField; - } else if (auto *VD = Obj.Base.dyn_cast()) { + } else if (auto *VD = Obj.Base.dyn_cast()) { DiagKind = 1; Loc = VD->getLocation(); Decl = VD; } else { DiagKind = 0; - if (auto *E = Obj.Base.dyn_cast()) + if (auto *E = Obj.Base.dyn_cast()) Loc = E->getExprLoc(); } Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1) @@ -3685,8 +3666,8 @@ return false; // If we modified a bit-field, truncate it to the right width. - if (isModification(handler.AccessKind) && - LastField && LastField->isBitField() && + if (isModification(handler.AccessKind) && LastField && + LastField->isBitField() && !truncateBitfieldValue(Info, E, *O, LastField)) return false; @@ -3696,7 +3677,7 @@ LastField = nullptr; if (ObjType->isArrayType()) { // Next subobject is an array element. - const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType); + ConstantArrayType const *CAT = Info.Ctx.getAsConstantArrayType(ObjType); assert(CAT && "vla in literal type?"); uint64_t Index = Sub.Entries[I].getAsArrayIndex(); if (CAT->getSize().ule(Index)) { @@ -3704,7 +3685,7 @@ // designator which points more than one past the end of the array. if (Info.getLangOpts().CPlusPlus11) Info.FFDiag(E, diag::note_constexpr_access_past_end) - << handler.AccessKind; + << handler.AccessKind; else Info.FFDiag(E); return handler.failed(); @@ -3725,7 +3706,7 @@ if (Index > 1) { if (Info.getLangOpts().CPlusPlus11) Info.FFDiag(E, diag::note_constexpr_access_past_end) - << handler.AccessKind; + << handler.AccessKind; else Info.FFDiag(E); return handler.failed(); @@ -3736,18 +3717,19 @@ assert(I == N - 1 && "extracting subobject of scalar?"); if (O->isComplexInt()) { - return handler.found(Index ? O->getComplexIntImag() - : O->getComplexIntReal(), ObjType); + return handler.found( + Index ? O->getComplexIntImag() : O->getComplexIntReal(), ObjType); } else { assert(O->isComplexFloat()); return handler.found(Index ? O->getComplexFloatImag() - : O->getComplexFloatReal(), ObjType); + : O->getComplexFloatReal(), + ObjType); } - } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) { + } else if (FieldDecl const *Field = getAsField(Sub.Entries[I])) { if (Field->isMutable() && !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) { Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) - << handler.AccessKind << Field; + << handler.AccessKind << Field; Info.Note(Field->getLocation(), diag::note_declared_at); return handler.failed(); } @@ -3755,7 +3737,7 @@ // Next subobject is a class, struct or union field. RecordDecl *RD = ObjType->castAs()->getDecl(); if (RD->isUnion()) { - const FieldDecl *UnionField = O->getUnionField(); + FieldDecl const *UnionField = O->getUnionField(); if (!UnionField || UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) { if (I == N - 1 && handler.AccessKind == AK_Construct) { @@ -3781,8 +3763,8 @@ VolatileField = Field; } else { // Next subobject is a base class. - const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl(); - const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]); + CXXRecordDecl const *Derived = ObjType->getAsCXXRecordDecl(); + CXXRecordDecl const *Base = getAsBaseClass(Sub.Entries[I]); O = &O->getStructBase(getBaseIndex(Derived, Base)); ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base)); @@ -3793,7 +3775,7 @@ namespace { struct ExtractSubobjectHandler { EvalInfo &Info; - const Expr *E; + Expr const *E; APValue &Result; const AccessKinds AccessKind; @@ -3817,9 +3799,9 @@ } // end anonymous namespace /// Extract the designated sub-object of an rvalue. -static bool extractSubobject(EvalInfo &Info, const Expr *E, - const CompleteObject &Obj, - const SubobjectDesignator &Sub, APValue &Result, +static bool extractSubobject(EvalInfo &Info, Expr const *E, + CompleteObject const &Obj, + SubobjectDesignator const &Sub, APValue &Result, AccessKinds AK = AK_Read) { assert(AK == AK_Read || AK == AK_ReadObjectRepresentation); ExtractSubobjectHandler Handler = {Info, E, Result, AK}; @@ -3830,7 +3812,7 @@ struct ModifySubobjectHandler { EvalInfo &Info; APValue &NewVal; - const Expr *E; + Expr const *E; typedef bool result_type; static const AccessKinds AccessKind = AK_Assign; @@ -3875,19 +3857,18 @@ const AccessKinds ModifySubobjectHandler::AccessKind; /// Update the designated sub-object of an rvalue to the given value. -static bool modifySubobject(EvalInfo &Info, const Expr *E, - const CompleteObject &Obj, - const SubobjectDesignator &Sub, - APValue &NewVal) { - ModifySubobjectHandler Handler = { Info, NewVal, E }; +static bool modifySubobject(EvalInfo &Info, Expr const *E, + CompleteObject const &Obj, + SubobjectDesignator const &Sub, APValue &NewVal) { + ModifySubobjectHandler Handler = {Info, NewVal, E}; return findSubobject(Info, E, Obj, Sub, Handler); } /// Find the position where two subobject designators diverge, or equivalently /// the length of the common initial subsequence. static unsigned FindDesignatorMismatch(QualType ObjType, - const SubobjectDesignator &A, - const SubobjectDesignator &B, + SubobjectDesignator const &A, + SubobjectDesignator const &B, bool &WasArrayIndex) { unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size()); for (/**/; I != N; ++I) { @@ -3908,7 +3889,7 @@ WasArrayIndex = false; return I; } - if (const FieldDecl *FD = getAsField(A.Entries[I])) + if (FieldDecl const *FD = getAsField(A.Entries[I])) // Next subobject is a field. ObjType = FD->getType(); else @@ -3923,8 +3904,8 @@ /// Determine whether the given subobject designators refer to elements of the /// same array object. static bool AreElementsOfSameArray(QualType ObjType, - const SubobjectDesignator &A, - const SubobjectDesignator &B) { + SubobjectDesignator const &A, + SubobjectDesignator const &B) { if (A.Entries.size() != B.Entries.size()) return false; @@ -3942,8 +3923,8 @@ } /// Find the complete object to which an LValue refers. -static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, - AccessKinds AK, const LValue &LVal, +static CompleteObject findCompleteObject(EvalInfo &Info, Expr const *E, + AccessKinds AK, LValue const &LVal, QualType LValType) { if (LVal.InvalidBase) { Info.FFDiag(E); @@ -3962,7 +3943,7 @@ Info.getCallFrameAndDepth(LVal.getLValueCallIndex()); if (!Frame) { Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1) - << AK << LVal.Base.is(); + << AK << LVal.Base.is(); NoteLValueLocation(Info, LVal.Base); return CompleteObject(); } @@ -3977,7 +3958,7 @@ if (isFormalAccess(AK) && LValType.isVolatileQualified()) { if (Info.getLangOpts().CPlusPlus) Info.FFDiag(E, diag::note_constexpr_access_volatile_type) - << AK << LValType; + << AK << LValType; else Info.FFDiag(E); return CompleteObject(); @@ -3992,7 +3973,7 @@ // This is the object whose initializer we're evaluating, so its lifetime // started in the current evaluation. BaseVal = Info.EvaluatingDeclValue; - } else if (const ValueDecl *D = LVal.Base.dyn_cast()) { + } else if (ValueDecl const *D = LVal.Base.dyn_cast()) { // Allow reading from a GUID declaration. if (auto *GD = dyn_cast(D)) { if (isModification(AK)) { @@ -4026,9 +4007,9 @@ // In C++1y, objects local to a constant expression (those with a Frame) are // both readable and writable inside constant expressions. // In C, such things can also be folded, although they are not ICEs. - const VarDecl *VD = dyn_cast(D); + VarDecl const *VD = dyn_cast(D); if (VD) { - if (const VarDecl *VDef = VD->getDefinition(Info.Ctx)) + if (VarDecl const *VDef = VD->getDefinition(Info.Ctx)) VD = VDef; } if (!VD || VD->isInvalidDecl()) { @@ -4078,9 +4059,11 @@ // folding of const floating-point types, in order to make static const // data members of such types (supported as an extension) more useful. if (Info.getLangOpts().CPlusPlus) { - Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11 - ? diag::note_constexpr_ltor_non_constexpr - : diag::note_constexpr_ltor_non_integral, 1) + Info.CCEDiag(E, + Info.getLangOpts().CPlusPlus11 + ? diag::note_constexpr_ltor_non_constexpr + : diag::note_constexpr_ltor_non_integral, + 1) << VD << BaseType; Info.Note(VD->getLocation(), diag::note_declared_at); } else { @@ -4089,9 +4072,11 @@ } else { // Never allow reading a non-const value. if (Info.getLangOpts().CPlusPlus) { - Info.FFDiag(E, Info.getLangOpts().CPlusPlus11 - ? diag::note_constexpr_ltor_non_constexpr - : diag::note_constexpr_ltor_non_integral, 1) + Info.FFDiag(E, + Info.getLangOpts().CPlusPlus11 + ? diag::note_constexpr_ltor_non_constexpr + : diag::note_constexpr_ltor_non_integral, + 1) << VD << BaseType; Info.Note(VD->getLocation(), diag::note_declared_at); } else { @@ -4101,10 +4086,11 @@ } } - if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal)) + if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), + BaseVal)) return CompleteObject(); } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast()) { - Optional Alloc = Info.lookupDynamicAlloc(DA); + Optional Alloc = Info.lookupDynamicAlloc(DA); if (!Alloc) { Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK; return CompleteObject(); @@ -4112,10 +4098,10 @@ return CompleteObject(LVal.Base, &(*Alloc)->Value, LVal.Base.getDynamicAllocType()); } else { - const Expr *Base = LVal.Base.dyn_cast(); + Expr const *Base = LVal.Base.dyn_cast(); if (!Frame) { - if (const MaterializeTemporaryExpr *MTE = + if (MaterializeTemporaryExpr const *MTE = dyn_cast_or_null(Base)) { assert(MTE->getStorageDuration() == SD_Static && "should have a frame for a non-global materialized temporary"); @@ -4183,7 +4169,7 @@ // to be read here (but take care with 'mutable' fields). unsigned VisibleDepth = Depth; if (llvm::isa_and_nonnull( - LVal.Base.dyn_cast())) + LVal.Base.dyn_cast())) ++VisibleDepth; if ((Frame && Info.getLangOpts().CPlusPlus14 && Info.EvalStatus.HasSideEffects) || @@ -4208,20 +4194,20 @@ /// representation rather than the value, and in particular, /// there is no requirement that the result be fully initialized. static bool -handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, - const LValue &LVal, APValue &RVal, +handleLValueToRValueConversion(EvalInfo &Info, Expr const *Conv, QualType Type, + LValue const &LVal, APValue &RVal, bool WantObjectRepresentation = false) { if (LVal.Designator.Invalid) return false; // Check for special cases where there is no existing APValue to look at. - const Expr *Base = LVal.Base.dyn_cast(); + Expr const *Base = LVal.Base.dyn_cast(); AccessKinds AK = WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read; if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) { - if (const CompoundLiteralExpr *CLE = dyn_cast(Base)) { + if (CompoundLiteralExpr const *CLE = dyn_cast(Base)) { // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the // initializer until now for such expressions. Such an expression can't be // an ICE in C, so this only matters for fold. @@ -4264,7 +4250,7 @@ } /// Perform an assignment of Val to LVal. Takes ownership of Val. -static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, +static bool handleAssignment(EvalInfo &Info, Expr const *E, LValue const &LVal, QualType LValType, APValue &Val) { if (LVal.Designator.Invalid) return false; @@ -4281,10 +4267,10 @@ namespace { struct CompoundAssignSubobjectHandler { EvalInfo &Info; - const CompoundAssignOperator *E; + CompoundAssignOperator const *E; QualType PromotedLHSType; BinaryOperatorKind Opcode; - const APValue &RHS; + APValue const &RHS; static const AccessKinds AccessKind = AK_Assign; @@ -4352,8 +4338,7 @@ Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS); return true; } else if (RHS.isFloat()) { - const FPOptions FPO = E->getFPFeaturesInEffect( - Info.Ctx.getLangOpts()); + const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); APFloat FValue(0.0); return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value, PromotedLHSType, FValue) && @@ -4377,7 +4362,7 @@ return false; QualType PointeeType; - if (const PointerType *PT = SubobjType->getAs()) + if (PointerType const *PT = SubobjType->getAs()) PointeeType = PT->getPointeeType(); if (PointeeType.isNull() || !RHS.isInt() || @@ -4404,11 +4389,11 @@ /// Perform a compound assignment of LVal = RVal. static bool handleCompoundAssignment(EvalInfo &Info, - const CompoundAssignOperator *E, - const LValue &LVal, QualType LValType, + CompoundAssignOperator const *E, + LValue const &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, - const APValue &RVal) { + APValue const &RVal) { if (LVal.Designator.Invalid) return false; @@ -4418,15 +4403,15 @@ } CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType); - CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode, - RVal }; + CompoundAssignSubobjectHandler Handler = {Info, E, PromotedLValType, Opcode, + RVal}; return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler); } namespace { struct IncDecSubobjectHandler { EvalInfo &Info; - const UnaryOperator *E; + UnaryOperator const *E; AccessKinds AccessKind; APValue *Old; @@ -4456,13 +4441,15 @@ case APValue::Float: return found(Subobj.getFloat(), SubobjType); case APValue::ComplexInt: - return found(Subobj.getComplexIntReal(), - SubobjType->castAs()->getElementType() - .withCVRQualifiers(SubobjType.getCVRQualifiers())); + return found( + Subobj.getComplexIntReal(), + SubobjType->castAs()->getElementType().withCVRQualifiers( + SubobjType.getCVRQualifiers())); case APValue::ComplexFloat: - return found(Subobj.getComplexFloatReal(), - SubobjType->castAs()->getElementType() - .withCVRQualifiers(SubobjType.getCVRQualifiers())); + return found( + Subobj.getComplexFloatReal(), + SubobjType->castAs()->getElementType().withCVRQualifiers( + SubobjType.getCVRQualifiers())); case APValue::LValue: return foundPointer(Subobj, SubobjType); default: @@ -4482,7 +4469,8 @@ return false; } - if (Old) *Old = APValue(Value); + if (Old) + *Old = APValue(Value); // bool arithmetic promotes to int, and the conversion back to bool // doesn't reduce mod 2^n, so special-case it. @@ -4499,7 +4487,7 @@ ++Value; if (!WasNegative && Value.isNegative() && E->canOverflow()) { - APSInt ActualValue(Value, /*IsUnsigned*/true); + APSInt ActualValue(Value, /*IsUnsigned*/ true); return HandleOverflow(Info, E, ActualValue, SubobjType); } } else { @@ -4507,7 +4495,7 @@ if (WasNegative && !Value.isNegative() && E->canOverflow()) { unsigned BitWidth = Value.getBitWidth(); - APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false); + APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/ false); ActualValue.setBit(BitWidth); return HandleOverflow(Info, E, ActualValue, SubobjType); } @@ -4518,7 +4506,8 @@ if (!checkConst(SubobjType)) return false; - if (Old) *Old = APValue(Value); + if (Old) + *Old = APValue(Value); APFloat One(Value.getSemantics(), 1); if (AccessKind == AK_Increment) @@ -4532,7 +4521,7 @@ return false; QualType PointeeType; - if (const PointerType *PT = SubobjType->getAs()) + if (PointerType const *PT = SubobjType->getAs()) PointeeType = PT->getPointeeType(); else { Info.FFDiag(E); @@ -4551,7 +4540,7 @@ } // end anonymous namespace /// Perform an increment or decrement on LVal. -static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, +static bool handleIncDec(EvalInfo &Info, Expr const *E, LValue const &LVal, QualType LValType, bool IsIncrement, APValue *Old) { if (LVal.Designator.Invalid) return false; @@ -4568,7 +4557,7 @@ } /// Build an lvalue for the object argument of a member function call. -static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, +static bool EvaluateObjectArgument(EvalInfo &Info, Expr const *Object, LValue &This) { if (Object->getType()->isPointerType() && Object->isPRValue()) return EvaluatePointer(Object, This, Info); @@ -4594,10 +4583,9 @@ /// creating a bound member function. /// \return The field or method declaration to which the member pointer refers, /// or 0 if evaluation fails. -static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, - QualType LVType, - LValue &LV, - const Expr *RHS, +static ValueDecl const *HandleMemberPointerAccess(EvalInfo &Info, + QualType LVType, LValue &LV, + Expr const *RHS, bool IncludeMember = true) { MemberPtr MemPtr; if (!EvaluateMemberPointer(RHS, MemPtr, Info)) @@ -4623,9 +4611,9 @@ unsigned PathLengthToMember = LV.Designator.Entries.size() - MemPtr.Path.size(); for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) { - const CXXRecordDecl *LVDecl = getAsBaseClass( - LV.Designator.Entries[PathLengthToMember + I]); - const CXXRecordDecl *MPDecl = MemPtr.Path[I]; + CXXRecordDecl const *LVDecl = + getAsBaseClass(LV.Designator.Entries[PathLengthToMember + I]); + CXXRecordDecl const *MPDecl = MemPtr.Path[I]; if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) { Info.FFDiag(RHS); return nullptr; @@ -4642,13 +4630,13 @@ MemPtr.Path.size() + IncludeMember); // Walk down to the appropriate base class. - if (const PointerType *PT = LVType->getAs()) + if (PointerType const *PT = LVType->getAs()) LVType = PT->getPointeeType(); - const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl(); + CXXRecordDecl const *RD = LVType->getAsCXXRecordDecl(); assert(RD && "member pointer access on non-class-type expression"); // The first class in the path is that of the lvalue. for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) { - const CXXRecordDecl *Base = MemPtr.Path[N - I - 1]; + CXXRecordDecl const *Base = MemPtr.Path[N - I - 1]; if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base)) return nullptr; RD = Base; @@ -4661,11 +4649,11 @@ // Add the member. Note that we cannot build bound member functions here. if (IncludeMember) { - if (const FieldDecl *FD = dyn_cast(MemPtr.getDecl())) { + if (FieldDecl const *FD = dyn_cast(MemPtr.getDecl())) { if (!HandleLValueMember(Info, RHS, LV, FD)) return nullptr; - } else if (const IndirectFieldDecl *IFD = - dyn_cast(MemPtr.getDecl())) { + } else if (IndirectFieldDecl const *IFD = + dyn_cast(MemPtr.getDecl())) { if (!HandleLValueIndirectMember(Info, RHS, LV, IFD)) return nullptr; } else { @@ -4676,8 +4664,8 @@ return MemPtr.getDecl(); } -static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info, - const BinaryOperator *BO, +static ValueDecl const *HandleMemberPointerAccess(EvalInfo &Info, + BinaryOperator const *BO, LValue &LV, bool IncludeMember = true) { assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI); @@ -4696,35 +4684,35 @@ /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on /// the provided lvalue, which currently refers to the base object. -static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, +static bool HandleBaseToDerivedCast(EvalInfo &Info, CastExpr const *E, LValue &Result) { SubobjectDesignator &D = Result.Designator; if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived)) return false; QualType TargetQT = E->getType(); - if (const PointerType *PT = TargetQT->getAs()) + if (PointerType const *PT = TargetQT->getAs()) TargetQT = PT->getPointeeType(); // Check this cast lands within the final derived-to-base subobject path. if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) { Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) - << D.MostDerivedType << TargetQT; + << D.MostDerivedType << TargetQT; return false; } // Check the type of the final cast. We don't need to check the path, // since a cast can only be formed if the path is unique. unsigned NewEntriesSize = D.Entries.size() - E->path_size(); - const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl(); - const CXXRecordDecl *FinalType; + CXXRecordDecl const *TargetType = TargetQT->getAsCXXRecordDecl(); + CXXRecordDecl const *FinalType; if (NewEntriesSize == D.MostDerivedPathLength) FinalType = D.MostDerivedType->getAsCXXRecordDecl(); else FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]); if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) { Info.CCEDiag(E, diag::note_constexpr_invalid_downcast) - << D.MostDerivedType << TargetQT; + << D.MostDerivedType << TargetQT; return false; } @@ -4742,7 +4730,7 @@ return false; } if (RD->isUnion()) { - Result = APValue((const FieldDecl *)nullptr); + Result = APValue((FieldDecl const *)nullptr); return true; } Result = APValue(APValue::UninitStruct(), RD->getNumBases(), @@ -4754,7 +4742,7 @@ I != End; ++I, ++Index) Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index)); - for (const auto *I : RD->fields()) { + for (auto const *I : RD->fields()) { if (I->isUnnamedBitfield()) continue; Success &= getDefaultInitValue(I->getType(), @@ -4794,7 +4782,7 @@ }; } -static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) { +static bool EvaluateVarDecl(EvalInfo &Info, VarDecl const *VD) { // We don't need to evaluate the initializer for a static local. if (!VD->hasLocalStorage()) return true; @@ -4803,7 +4791,7 @@ APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(), ScopeKind::Block, Result); - const Expr *InitE = VD->getInit(); + Expr const *InitE = VD->getInit(); if (!InitE) { if (VD->getType()->isDependentType()) return Info.noteSideEffect(); @@ -4822,13 +4810,13 @@ return true; } -static bool EvaluateDecl(EvalInfo &Info, const Decl *D) { +static bool EvaluateDecl(EvalInfo &Info, Decl const *D) { bool OK = true; - if (const VarDecl *VD = dyn_cast(D)) + if (VarDecl const *VD = dyn_cast(D)) OK &= EvaluateVarDecl(Info, VD); - if (const DecompositionDecl *DD = dyn_cast(D)) + if (DecompositionDecl const *DD = dyn_cast(D)) for (auto *BD : DD->bindings()) if (auto *VD = BD->getHoldingVar()) OK &= EvaluateDecl(Info, VD); @@ -4836,7 +4824,7 @@ return OK; } -static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) { +static bool EvaluateDependentExpr(Expr const *E, EvalInfo &Info) { assert(E->isValueDependent()); if (Info.noteSideEffect()) return true; @@ -4846,8 +4834,8 @@ } /// Evaluate a condition (either a variable declaration or an expression). -static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, - const Expr *Cond, bool &Result) { +static bool EvaluateCond(EvalInfo &Info, VarDecl const *CondDecl, + Expr const *Cond, bool &Result) { if (Cond->isValueDependent()) return false; FullExpressionRAII Scope(Info); @@ -4865,7 +4853,7 @@ /// The APValue that should be filled in with the returned value. APValue &Value; /// The location containing the result, if any (used to support RVO). - const LValue *Slot; + LValue const *Slot; }; struct TempVersionRAII { @@ -4875,21 +4863,19 @@ Frame.pushTempVersion(); } - ~TempVersionRAII() { - Frame.popTempVersion(); - } + ~TempVersionRAII() { Frame.popTempVersion(); } }; -} +} // namespace static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, - const Stmt *S, - const SwitchCase *SC = nullptr); + Stmt const *S, + SwitchCase const *SC = nullptr); /// Evaluate the body of a loop, and translate the result as appropriate. static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, - const Stmt *Body, - const SwitchCase *Case = nullptr) { + Stmt const *Body, + SwitchCase const *Case = nullptr) { BlockScopeRAII Scope(Info); EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case); @@ -4912,13 +4898,13 @@ /// Evaluate a switch statement. static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, - const SwitchStmt *SS) { + SwitchStmt const *SS) { BlockScopeRAII Scope(Info); // Evaluate the switch condition. APSInt Value; { - if (const Stmt *Init = SS->getInit()) { + if (Stmt const *Init = SS->getInit()) { EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); if (ESR != ESR_Succeeded) { if (ESR != ESR_Failed && !Scope.destroy()) @@ -4939,18 +4925,18 @@ // Find the switch case corresponding to the value of the condition. // FIXME: Cache this lookup. - const SwitchCase *Found = nullptr; - for (const SwitchCase *SC = SS->getSwitchCaseList(); SC; + SwitchCase const *Found = nullptr; + for (SwitchCase const *SC = SS->getSwitchCaseList(); SC; SC = SC->getNextSwitchCase()) { if (isa(SC)) { Found = SC; continue; } - const CaseStmt *CS = cast(SC); + CaseStmt const *CS = cast(SC); APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx); - APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) - : LHS; + APSInt RHS = + CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx) : LHS; if (LHS <= Value && Value <= RHS) { Found = SC; break; @@ -4985,7 +4971,7 @@ // Evaluate a statement. static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, - const Stmt *S, const SwitchCase *Case) { + Stmt const *S, SwitchCase const *Case) { if (!Info.nextStep(S)) return ESR_Failed; @@ -5011,7 +4997,7 @@ case Stmt::IfStmtClass: { // FIXME: Precompute which side of an 'if' we would jump to, and go // straight there rather than scanning both sides. - const IfStmt *IS = cast(S); + IfStmt const *IS = cast(S); // Wrap the evaluation in a block scope, in case it's a DeclStmt // preceded by our switch label. @@ -5019,7 +5005,7 @@ // Step into the init statement in case it brings an (uninitialized) // variable into scope. - if (const Stmt *Init = IS->getInit()) { + if (Stmt const *Init = IS->getInit()) { EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); if (ESR != ESR_CaseNotFound) { assert(ESR != ESR_Succeeded); @@ -5057,12 +5043,12 @@ } case Stmt::ForStmtClass: { - const ForStmt *FS = cast(S); + ForStmt const *FS = cast(S); BlockScopeRAII Scope(Info); // Step into the init statement in case it brings an (uninitialized) // variable into scope. - if (const Stmt *Init = FS->getInit()) { + if (Stmt const *Init = FS->getInit()) { EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case); if (ESR != ESR_CaseNotFound) { assert(ESR != ESR_Succeeded); @@ -5070,11 +5056,10 @@ } } - EvalStmtResult ESR = - EvaluateLoopBody(Result, Info, FS->getBody(), Case); + EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody(), Case); if (ESR != ESR_Continue) return ESR; - if (const auto *Inc = FS->getInc()) { + if (auto const *Inc = FS->getInc()) { if (Inc->isValueDependent()) { if (!EvaluateDependentExpr(Inc, Info)) return ESR_Failed; @@ -5090,9 +5075,9 @@ case Stmt::DeclStmtClass: { // Start the lifetime of any uninitialized variables we encounter. They // might be used by the selected branch of the switch. - const DeclStmt *DS = cast(S); - for (const auto *D : DS->decls()) { - if (const auto *VD = dyn_cast(D)) { + DeclStmt const *DS = cast(S); + for (auto const *D : DS->decls()) { + if (auto const *VD = dyn_cast(D)) { if (VD->hasLocalStorage() && !VD->getInit()) if (!EvaluateVarDecl(Info, VD)) return ESR_Failed; @@ -5111,7 +5096,7 @@ switch (S->getStmtClass()) { default: - if (const Expr *E = dyn_cast(S)) { + if (Expr const *E = dyn_cast(S)) { if (E->isValueDependent()) { if (!EvaluateDependentExpr(E, Info)) return ESR_Failed; @@ -5134,8 +5119,8 @@ return ESR_Succeeded; case Stmt::DeclStmtClass: { - const DeclStmt *DS = cast(S); - for (const auto *D : DS->decls()) { + DeclStmt const *DS = cast(S); + for (auto const *D : DS->decls()) { // Each declaration initialization is its own full-expression. FullExpressionRAII Scope(Info); if (!EvaluateDecl(Info, D) && !Info.noteFailure()) @@ -5147,17 +5132,16 @@ } case Stmt::ReturnStmtClass: { - const Expr *RetExpr = cast(S)->getRetValue(); + Expr const *RetExpr = cast(S)->getRetValue(); FullExpressionRAII Scope(Info); if (RetExpr && RetExpr->isValueDependent()) { EvaluateDependentExpr(RetExpr, Info); // We know we returned, but we don't know what the value is. return ESR_Failed; } - if (RetExpr && - !(Result.Slot - ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr) - : Evaluate(Result.Value, Info, RetExpr))) + if (RetExpr && !(Result.Slot ? EvaluateInPlace(Result.Value, Info, + *Result.Slot, RetExpr) + : Evaluate(Result.Value, Info, RetExpr))) return ESR_Failed; return Scope.destroy() ? ESR_Returned : ESR_Failed; } @@ -5165,8 +5149,8 @@ case Stmt::CompoundStmtClass: { BlockScopeRAII Scope(Info); - const CompoundStmt *CS = cast(S); - for (const auto *BI : CS->body()) { + CompoundStmt const *CS = cast(S); + for (auto const *BI : CS->body()) { EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case); if (ESR == ESR_Succeeded) Case = nullptr; @@ -5182,11 +5166,11 @@ } case Stmt::IfStmtClass: { - const IfStmt *IS = cast(S); + IfStmt const *IS = cast(S); // Evaluate the condition, as either a var decl or as an expression. BlockScopeRAII Scope(Info); - if (const Stmt *Init = IS->getInit()) { + if (Stmt const *Init = IS->getInit()) { EvalStmtResult ESR = EvaluateStmt(Result, Info, Init); if (ESR != ESR_Succeeded) { if (ESR != ESR_Failed && !Scope.destroy()) @@ -5198,7 +5182,7 @@ if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond)) return ESR_Failed; - if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) { + if (Stmt const *SubStmt = Cond ? IS->getThen() : IS->getElse()) { EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt); if (ESR != ESR_Succeeded) { if (ESR != ESR_Failed && !Scope.destroy()) @@ -5210,7 +5194,7 @@ } case Stmt::WhileStmtClass: { - const WhileStmt *WS = cast(S); + WhileStmt const *WS = cast(S); while (true) { BlockScopeRAII Scope(Info); bool Continue; @@ -5233,7 +5217,7 @@ } case Stmt::DoStmtClass: { - const DoStmt *DS = cast(S); + DoStmt const *DS = cast(S); bool Continue; do { EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case); @@ -5255,7 +5239,7 @@ } case Stmt::ForStmtClass: { - const ForStmt *FS = cast(S); + ForStmt const *FS = cast(S); BlockScopeRAII ForScope(Info); if (FS->getInit()) { EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit()); @@ -5281,7 +5265,7 @@ return ESR; } - if (const auto *Inc = FS->getInc()) { + if (auto const *Inc = FS->getInc()) { if (Inc->isValueDependent()) { if (!EvaluateDependentExpr(Inc, Info)) return ESR_Failed; @@ -5299,7 +5283,7 @@ } case Stmt::CXXForRangeStmtClass: { - const CXXForRangeStmt *FS = cast(S); + CXXForRangeStmt const *FS = cast(S); BlockScopeRAII Scope(Info); // Evaluate the init-statement if present. @@ -5414,7 +5398,7 @@ /// constexpr. If it is marked as constexpr, we will never implicitly define it, /// so we need special handling. static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, - const CXXConstructorDecl *CD, + CXXConstructorDecl const *CD, bool IsValueInitialization) { if (!CD->isTrivial() || !CD->isDefaultConstructor()) return false; @@ -5427,7 +5411,7 @@ // FIXME: If DiagDecl is an implicitly-declared special member function, // we should be much more explicit about why it's not constexpr. Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1) - << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD; + << /*IsConstexpr*/ 0 << /*IsConstructor*/ 1 << CD; Info.Note(CD->getLocation(), diag::note_declared_at); } else { Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr); @@ -5439,9 +5423,9 @@ /// CheckConstexprFunction - Check that a function can be called in a constant /// expression. static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, - const FunctionDecl *Declaration, - const FunctionDecl *Definition, - const Stmt *Body) { + FunctionDecl const *Declaration, + FunctionDecl const *Definition, + Stmt const *Body) { // Potential constant expressions can contain calls to declared, but not yet // defined, constexpr functions. if (Info.checkingPotentialConstantExpression() && !Definition && @@ -5473,7 +5457,7 @@ return true; if (Info.getLangOpts().CPlusPlus11) { - const FunctionDecl *DiagDecl = Definition ? Definition : Declaration; + FunctionDecl const *DiagDecl = Definition ? Definition : Declaration; // If this function is not constexpr because it is an inherited // non-constexpr constructor, diagnose that directly. @@ -5489,10 +5473,10 @@ // it's not constexpr. if (CD && CD->isInheritingConstructor()) Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1) - << CD->getInheritedConstructor().getConstructor()->getParent(); + << CD->getInheritedConstructor().getConstructor()->getParent(); else Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1) - << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; + << DiagDecl->isConstexpr() << (bool)CD << DiagDecl; Info.Note(DiagDecl->getLocation(), diag::note_declared_at); } else { Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr); @@ -5513,7 +5497,7 @@ /// Check that we can access the notional vptr of an object / determine its /// dynamic type. -static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, +static bool checkDynamicType(EvalInfo &Info, Expr const *E, LValue const &This, AccessKinds AK, bool Polymorphic) { if (This.Designator.Invalid) return false; @@ -5555,9 +5539,9 @@ /// Check that the pointee of the 'this' pointer in a member function call is /// either within its lifetime or in its period of construction or destruction. static bool -checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, - const LValue &This, - const CXXMethodDecl *NamedMember) { +checkNonVirtualMemberCallThisPointer(EvalInfo &Info, Expr const *E, + LValue const &This, + CXXMethodDecl const *NamedMember) { return checkDynamicType( Info, E, This, isa(NamedMember) ? AK_Destroy : AK_MemberCall, false); @@ -5565,22 +5549,22 @@ struct DynamicType { /// The dynamic class type of the object. - const CXXRecordDecl *Type; + CXXRecordDecl const *Type; /// The corresponding path length in the lvalue. unsigned PathLength; }; -static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator, +static CXXRecordDecl const *getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength) { - assert(PathLength >= Designator.MostDerivedPathLength && PathLength <= - Designator.Entries.size() && "invalid path length"); + assert(PathLength >= Designator.MostDerivedPathLength && + PathLength <= Designator.Entries.size() && "invalid path length"); return (PathLength == Designator.MostDerivedPathLength) ? Designator.MostDerivedType->getAsCXXRecordDecl() : getAsBaseClass(Designator.Entries[PathLength - 1]); } /// Determine the dynamic type of an object. -static Optional ComputeDynamicType(EvalInfo &Info, const Expr *E, +static Optional ComputeDynamicType(EvalInfo &Info, Expr const *E, LValue &This, AccessKinds AK) { // If we don't have an lvalue denoting an object of class type, there is no // meaningful dynamic type. (We consider objects of non-class type to have no @@ -5594,7 +5578,7 @@ // // Note that consumers of DynamicType assume that the type has no virtual // bases, and will need modifications if this restriction is relaxed. - const CXXRecordDecl *Class = + CXXRecordDecl const *Class = This.Designator.MostDerivedType->getAsCXXRecordDecl(); if (!Class || Class->getNumVBases()) { Info.FFDiag(E); @@ -5635,8 +5619,8 @@ } /// Perform virtual dispatch. -static const CXXMethodDecl *HandleVirtualDispatch( - EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, +static CXXMethodDecl const *HandleVirtualDispatch( + EvalInfo &Info, Expr const *E, LValue &This, CXXMethodDecl const *Found, llvm::SmallVectorImpl &CovariantAdjustmentPath) { Optional DynType = ComputeDynamicType( Info, E, This, @@ -5648,11 +5632,11 @@ // path from the dynamic type to the static type. // FIXME: If we ever allow literal types to have virtual base classes, that // won't be true. - const CXXMethodDecl *Callee = Found; + CXXMethodDecl const *Callee = Found; unsigned PathLength = DynType->PathLength; for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) { - const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength); - const CXXMethodDecl *Overrider = + CXXRecordDecl const *Class = getBaseClassType(This.Designator, PathLength); + CXXMethodDecl const *Overrider = Found->getCorrespondingMethodDeclaredInClass(Class, false); if (Overrider) { Callee = Overrider; @@ -5677,9 +5661,9 @@ for (unsigned CovariantPathLength = PathLength + 1; CovariantPathLength != This.Designator.Entries.size(); ++CovariantPathLength) { - const CXXRecordDecl *NextClass = + CXXRecordDecl const *NextClass = getBaseClassType(This.Designator, CovariantPathLength); - const CXXMethodDecl *Next = + CXXMethodDecl const *Next = Found->getCorrespondingMethodDeclaredInClass(NextClass, false); if (Next && !Info.Ctx.hasSameUnqualifiedType( Next->getReturnType(), CovariantAdjustmentPath.back())) @@ -5700,7 +5684,7 @@ /// Perform the adjustment from a value returned by a virtual function to /// a value of the statically expected type, which may be a pointer or /// reference to a base class of the returned type. -static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, +static bool HandleCovariantReturnAdjustment(EvalInfo &Info, Expr const *E, APValue &Result, ArrayRef Path) { assert(Result.isLValue() && @@ -5711,9 +5695,9 @@ LValue LVal; LVal.setFrom(Info.Ctx, Result); - const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl(); + CXXRecordDecl const *OldClass = Path[0]->getPointeeCXXRecordDecl(); for (unsigned I = 1; I != Path.size(); ++I) { - const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl(); + CXXRecordDecl const *NewClass = Path[I]->getPointeeCXXRecordDecl(); assert(OldClass && NewClass && "unexpected kind of covariant return"); if (OldClass != NewClass && !CastToBaseClass(Info, E, LVal, OldClass, NewClass)) @@ -5727,9 +5711,9 @@ /// Determine whether \p Base, which is known to be a direct base class of /// \p Derived, is a public base class. -static bool isBaseClassPublic(const CXXRecordDecl *Derived, - const CXXRecordDecl *Base) { - for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) { +static bool isBaseClassPublic(CXXRecordDecl const *Derived, + CXXRecordDecl const *Base) { + for (CXXBaseSpecifier const &BaseSpec : Derived->bases()) { auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl(); if (BaseClass && declaresSameEntity(BaseClass, Base)) return BaseSpec.getAccessSpecifier() == AS_public; @@ -5741,7 +5725,7 @@ /// /// This implements the hard case of dynamic_cast, requiring a "runtime check" /// to find a suitable target subobject. -static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, +static bool HandleDynamicCast(EvalInfo &Info, ExplicitCastExpr const *E, LValue &Ptr) { // We can't do anything with a non-symbolic pointer value. SubobjectDesignator &D = Ptr.Designator; @@ -5767,11 +5751,11 @@ if (E->getType()->isVoidPointerType()) return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength); - const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); + CXXRecordDecl const *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl(); assert(C && "dynamic_cast target is not void pointer nor class"); CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C)); - auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) { + auto RuntimeCheckFailed = [&](CXXBasePaths *Paths) { // C++ [expr.dynamic.cast]p9: if (!E->isGLValue()) { // The value of a failed cast to pointer type is the null pointer value @@ -5805,7 +5789,7 @@ // target type. for (int PathLength = Ptr.Designator.Entries.size(); PathLength >= (int)DynType->PathLength; --PathLength) { - const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength); + CXXRecordDecl const *Class = getBaseClassType(Ptr.Designator, PathLength); if (declaresSameEntity(Class, C)) return CastToDerivedClass(Info, E, Ptr, Class, PathLength); // We can only walk across public inheritance edges. @@ -5838,8 +5822,8 @@ namespace { struct StartLifetimeOfUnionMemberHandler { EvalInfo &Info; - const Expr *LHSExpr; - const FieldDecl *Field; + Expr const *LHSExpr; + FieldDecl const *Field; bool DuringInit; bool Failed = false; static const AccessKinds AccessKind = AK_Assign; @@ -5889,16 +5873,16 @@ /// operator whose left-hand side might involve a union member access. If it /// does, implicitly start the lifetime of any accessed union elements per /// C++20 [class.union]5. -static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, - const LValue &LHS) { +static bool HandleUnionActiveMemberChange(EvalInfo &Info, Expr const *LHSExpr, + LValue const &LHS) { if (LHS.InvalidBase || LHS.Designator.Invalid) return false; - llvm::SmallVector, 4> UnionPathLengths; + llvm::SmallVector, 4> UnionPathLengths; // C++ [class.union]p5: // define the set S(E) of subexpressions of E as follows: unsigned PathLength = LHS.Designator.Entries.size(); - for (const Expr *E = LHSExpr; E != nullptr;) { + for (Expr const *E = LHSExpr; E != nullptr;) { // -- If E is of the form A.B, S(E) contains the elements of S(A)... if (auto *ME = dyn_cast(E)) { auto *FD = dyn_cast(ME->getMemberDecl()); @@ -5920,9 +5904,9 @@ E = ME->getBase(); --PathLength; - assert(declaresSameEntity(FD, - LHS.Designator.Entries[PathLength] - .getAsBaseOrMember().getPointer())); + assert(declaresSameEntity( + FD, + LHS.Designator.Entries[PathLength].getAsBaseOrMember().getPointer())); // -- If E is of the form A[B] and is interpreted as a built-in array // subscripting operator, S(E) is [S(the array operand, if any)]. @@ -5944,15 +5928,16 @@ ICE->getCastKind() != CK_UncheckedDerivedToBase) break; // Walk path backwards as we walk up from the base to the derived class. - for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) { + for (CXXBaseSpecifier const *Elt : llvm::reverse(ICE->path())) { --PathLength; (void)Elt; assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(), LHS.Designator.Entries[PathLength] - .getAsBaseOrMember().getPointer())); + .getAsBaseOrMember() + .getPointer())); } - // -- Otherwise, S(E) is empty. + // -- Otherwise, S(E) is empty. } else { break; } @@ -5968,8 +5953,8 @@ findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType()); if (!Obj) return false; - for (std::pair LengthAndField : - llvm::reverse(UnionPathLengths)) { + for (std::pair LengthAndField : + llvm::reverse(UnionPathLengths)) { // Form a designator for the union object. SubobjectDesignator D = LHS.Designator; D.truncate(Info.Ctx, LHS.Base, LengthAndField.first); @@ -5985,7 +5970,7 @@ return true; } -static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, +static bool EvaluateCallArg(ParmVarDecl const *PVD, Expr const *Arg, CallRef Call, EvalInfo &Info, bool NonNull = false) { LValue LV; @@ -6011,14 +5996,14 @@ } /// Evaluate the arguments to a function call. -static bool EvaluateArgs(ArrayRef Args, CallRef Call, - EvalInfo &Info, const FunctionDecl *Callee, +static bool EvaluateArgs(ArrayRef Args, CallRef Call, + EvalInfo &Info, FunctionDecl const *Callee, bool RightToLeft = false) { bool Success = true; llvm::SmallBitVector ForbiddenNullArgs; if (Callee->hasAttr()) { ForbiddenNullArgs.resize(Args.size()); - for (const auto *Attr : Callee->specific_attrs()) { + for (auto const *Attr : Callee->specific_attrs()) { if (!Attr->args_size()) { ForbiddenNullArgs.set(); break; @@ -6033,7 +6018,7 @@ } for (unsigned I = 0; I < Args.size(); I++) { unsigned Idx = RightToLeft ? Args.size() - I - 1 : I; - const ParmVarDecl *PVD = + ParmVarDecl const *PVD = Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr; bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx]; if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) { @@ -6049,8 +6034,8 @@ /// Perform a trivial copy from Param, which is the parameter of a copy or move /// constructor or assignment operator. -static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, - const Expr *E, APValue &Result, +static bool handleTrivialCopy(EvalInfo &Info, ParmVarDecl const *Param, + Expr const *E, APValue &Result, bool CopyObjectRepresentation) { // Find the reference argument. CallStackFrame *Frame = Info.CurrentCall; @@ -6070,10 +6055,10 @@ /// Evaluate a function call. static bool HandleFunctionCall(SourceLocation CallLoc, - const FunctionDecl *Callee, const LValue *This, - ArrayRef Args, CallRef Call, - const Stmt *Body, EvalInfo &Info, - APValue &Result, const LValue *ResultSlot) { + FunctionDecl const *Callee, LValue const *This, + ArrayRef Args, CallRef Call, + Stmt const *Body, EvalInfo &Info, + APValue &Result, LValue const *ResultSlot) { if (!Info.CheckCallLimit(CallLoc)) return false; @@ -6085,7 +6070,7 @@ // // Skip this for non-union classes with no fields; in that case, the defaulted // copy/move does not actually read the object. - const CXXMethodDecl *MD = dyn_cast(Callee); + CXXMethodDecl const *MD = dyn_cast(Callee); if (MD && MD->isDefaulted() && (MD->getParent()->isUnion() || (MD->isTrivial() && @@ -6099,8 +6084,7 @@ if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() && !HandleUnionActiveMemberChange(Info, Args[0], *This)) return false; - if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), - RHSValue)) + if (!handleAssignment(Info, Args[0], *This, MD->getThisType(), RHSValue)) return false; This->moveInto(Result); return true; @@ -6127,15 +6111,15 @@ } /// Evaluate a constructor call. -static bool HandleConstructorCall(const Expr *E, const LValue &This, +static bool HandleConstructorCall(Expr const *E, LValue const &This, CallRef Call, - const CXXConstructorDecl *Definition, + CXXConstructorDecl const *Definition, EvalInfo &Info, APValue &Result) { SourceLocation CallLoc = E->getExprLoc(); if (!Info.CheckCallLimit(CallLoc)) return false; - const CXXRecordDecl *RD = Definition->getParent(); + CXXRecordDecl const *RD = Definition->getParent(); if (RD->getNumVBases()) { Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD; return false; @@ -6190,11 +6174,12 @@ std::distance(RD->field_begin(), RD->field_end())); else // A union starts with no active member. - Result = APValue((const FieldDecl*)nullptr); + Result = APValue((FieldDecl const *)nullptr); } - if (RD->isInvalidDecl()) return false; - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); + if (RD->isInvalidDecl()) + return false; + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(RD); // A scope for temporaries lifetime-extended by reference members. BlockScopeRAII LifetimeExtendedScope(Info); @@ -6224,7 +6209,7 @@ } ++FieldIt; }; - for (const auto *I : Definition->inits()) { + for (auto const *I : Definition->inits()) { LValue Subobject = This; LValue SubobjectParent = This; APValue *Value = &Result; @@ -6298,7 +6283,7 @@ // Need to override This for implicit field initializers as in this case // This refers to innermost anonymous struct/union containing initializer, // not to currently constructed class. - const Expr *Init = I->getInit(); + Expr const *Init = I->getInit(); if (Init->isValueDependent()) { if (!EvaluateDependentExpr(Init, Info)) return false; @@ -6340,9 +6325,9 @@ LifetimeExtendedScope.destroy(); } -static bool HandleConstructorCall(const Expr *E, const LValue &This, - ArrayRef Args, - const CXXConstructorDecl *Definition, +static bool HandleConstructorCall(Expr const *E, LValue const &This, + ArrayRef Args, + CXXConstructorDecl const *Definition, EvalInfo &Info, APValue &Result) { CallScopeRAII CallScope(Info); CallRef Call = Info.CurrentCall->createCall(Definition); @@ -6354,7 +6339,7 @@ } static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc, - const LValue &This, APValue &Value, + LValue const &This, APValue &Value, QualType T) { // Objects can only be destroyed while they're within their lifetimes. // FIXME: We have no representation for whether an object of type nullptr_t @@ -6364,7 +6349,7 @@ APValue Printable; This.moveInto(Printable); Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime) - << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); + << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T)); return false; } @@ -6373,7 +6358,7 @@ OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue); // For arrays, destroy elements right-to-left. - if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) { + if (ConstantArrayType const *CAT = Info.Ctx.getAsConstantArrayType(T)) { uint64_t Size = CAT->getSize().getZExtValue(); QualType ElemT = CAT->getElementType(); @@ -6400,7 +6385,7 @@ return true; } - const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); + CXXRecordDecl const *RD = T->getAsCXXRecordDecl(); if (!RD) { if (T.isDestructedType()) { Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T; @@ -6416,7 +6401,7 @@ return false; } - const CXXDestructorDecl *DD = RD->getDestructor(); + CXXDestructorDecl const *DD = RD->getDestructor(); if (!DD && !RD->hasTrivialDestructor()) { Info.FFDiag(CallLoc); return false; @@ -6440,8 +6425,8 @@ if (!Info.CheckCallLimit(CallLoc)) return false; - const FunctionDecl *Definition = nullptr; - const Stmt *Body = DD->getBody(Definition); + FunctionDecl const *Definition = nullptr; + Stmt const *Body = DD->getBody(Definition); if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body)) return false; @@ -6475,12 +6460,12 @@ if (RD->isUnion()) return true; - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(RD); // We don't have a good way to iterate fields in reverse, so collect all the // fields first and then walk them backwards. - SmallVector Fields(RD->field_begin(), RD->field_end()); - for (const FieldDecl *FD : llvm::reverse(Fields)) { + SmallVector Fields(RD->field_begin(), RD->field_end()); + for (FieldDecl const *FD : llvm::reverse(Fields)) { if (FD->isUnnamedBitfield()) continue; @@ -6498,7 +6483,7 @@ EvalObj.startedDestroyingBases(); // Destroy base classes in reverse order. - for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) { + for (CXXBaseSpecifier const &Base : llvm::reverse(RD->bases())) { --BasesLeft; QualType BaseType = Base.getType(); @@ -6522,8 +6507,8 @@ namespace { struct DestroyObjectHandler { EvalInfo &Info; - const Expr *E; - const LValue &This; + Expr const *E; + LValue const &This; const AccessKinds AccessKind; typedef bool result_type; @@ -6541,12 +6526,12 @@ return false; } }; -} +} // namespace /// Perform a destructor or pseudo-destructor call on the given object, which /// might in general not be a complete object. -static bool HandleDestruction(EvalInfo &Info, const Expr *E, - const LValue &This, QualType ThisType) { +static bool HandleDestruction(EvalInfo &Info, Expr const *E, LValue const &This, + QualType ThisType) { CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType); DestroyObjectHandler Handler = {Info, E, This, AK_Destroy}; return Obj && findSubobject(Info, E, Obj, This.Designator, Handler); @@ -6567,7 +6552,7 @@ } /// Perform a call to 'perator new' or to `__builtin_operator_new'. -static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, +static bool HandleOperatorNewCall(EvalInfo &Info, CallExpr const *E, LValue &Result) { if (Info.checkingPotentialConstantExpression() || Info.SpeculativeEvaluationDepth) @@ -6637,7 +6622,7 @@ return false; } -static const FunctionDecl *getVirtualOperatorDelete(QualType T) { +static FunctionDecl const *getVirtualOperatorDelete(QualType T) { if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) if (CXXDestructorDecl *DD = RD->getDestructor()) return DD->isVirtual() ? DD->getOperatorDelete() : nullptr; @@ -6649,8 +6634,8 @@ /// /// On success, returns the heap allocation to deallocate. On failure, produces /// a diagnostic and returns None. -static Optional CheckDeleteKind(EvalInfo &Info, const Expr *E, - const LValue &Pointer, +static Optional CheckDeleteKind(EvalInfo &Info, Expr const *E, + LValue const &Pointer, DynAlloc::Kind DeallocKind) { auto PointerAsString = [&] { return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy); @@ -6697,7 +6682,7 @@ } // Perform a call to 'operator delete' or '__builtin_operator_delete'. -bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) { +bool HandleOperatorDeleteCall(EvalInfo &Info, CallExpr const *E) { if (Info.checkingPotentialConstantExpression() || Info.SpeculativeEvaluationDepth) return false; @@ -6751,8 +6736,8 @@ public: BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian) - : Bytes(Width.getQuantity()), - TargetIsLittleEndian(TargetIsLittleEndian) {} + : Bytes(Width.getQuantity()), TargetIsLittleEndian(TargetIsLittleEndian) { + } LLVM_NODISCARD bool readObject(CharUnits Offset, CharUnits Width, @@ -6789,20 +6774,20 @@ class APValueToBufferConverter { EvalInfo &Info; BitCastBuffer Buffer; - const CastExpr *BCE; + CastExpr const *BCE; APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth, - const CastExpr *BCE) + CastExpr const *BCE) : Info(Info), Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()), BCE(BCE) {} - bool visit(const APValue &Val, QualType Ty) { + bool visit(APValue const &Val, QualType Ty) { return visit(Val, Ty, CharUnits::fromQuantity(0)); } // Write out Val with type Ty into Buffer starting at Offset. - bool visit(const APValue &Val, QualType Ty, CharUnits Offset) { + bool visit(APValue const &Val, QualType Ty, CharUnits Offset) { assert((size_t)Offset.getQuantity() <= Buffer.size()); // As a special case, nullptr_t has an indeterminate value. @@ -6845,14 +6830,14 @@ llvm_unreachable("Unhandled APValue::ValueKind"); } - bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) { - const RecordDecl *RD = Ty->getAsRecordDecl(); - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); + bool visitRecord(APValue const &Val, QualType Ty, CharUnits Offset) { + RecordDecl const *RD = Ty->getAsRecordDecl(); + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(RD); // Visit the base classes. if (auto *CXXRD = dyn_cast(RD)) { for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { - const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; + CXXBaseSpecifier const &BS = CXXRD->bases_begin()[I]; CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); if (!visitRecord(Val.getStructBase(I), BS.getType(), @@ -6885,8 +6870,8 @@ return true; } - bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) { - const auto *CAT = + bool visitArray(APValue const &Val, QualType Ty, CharUnits Offset) { + auto const *CAT = dyn_cast_or_null(Ty->getAsArrayTypeUnsafe()); if (!CAT) return false; @@ -6896,14 +6881,14 @@ unsigned ArraySize = Val.getArraySize(); // First, initialize the initialized elements. for (unsigned I = 0; I != NumInitializedElts; ++I) { - const APValue &SubObj = Val.getArrayInitializedElt(I); + APValue const &SubObj = Val.getArrayInitializedElt(I); if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth)) return false; } // Next, initialize the rest of the array using the filler. if (Val.hasArrayFiller()) { - const APValue &Filler = Val.getArrayFiller(); + APValue const &Filler = Val.getArrayFiller(); for (unsigned I = NumInitializedElts; I != ArraySize; ++I) { if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth)) return false; @@ -6913,7 +6898,7 @@ return true; } - bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) { + bool visitInt(APSInt const &Val, QualType Ty, CharUnits Offset) { APSInt AdjustedVal = Val; unsigned Width = AdjustedVal.getBitWidth(); if (Ty->isBooleanType()) { @@ -6927,14 +6912,14 @@ return true; } - bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) { + bool visitFloat(APFloat const &Val, QualType Ty, CharUnits Offset) { APSInt AsInt(Val.bitcastToAPInt()); return visitInt(AsInt, Ty, Offset); } public: - static Optional convert(EvalInfo &Info, const APValue &Src, - const CastExpr *BCE) { + static Optional convert(EvalInfo &Info, APValue const &Src, + CastExpr const *BCE) { CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType()); APValueToBufferConverter Converter(Info, DstSize, BCE); if (!Converter.visit(Src, BCE->getSubExpr()->getType())) @@ -6946,11 +6931,11 @@ /// Write an BitCastBuffer into an APValue. class BufferToAPValueConverter { EvalInfo &Info; - const BitCastBuffer &Buffer; - const CastExpr *BCE; + BitCastBuffer const &Buffer; + CastExpr const *BCE; - BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer, - const CastExpr *BCE) + BufferToAPValueConverter(EvalInfo &Info, BitCastBuffer const &Buffer, + CastExpr const *BCE) : Info(Info), Buffer(Buffer), BCE(BCE) {} // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast @@ -6963,15 +6948,15 @@ return None; } - llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) { + llvm::NoneType unrepresentableValue(QualType Ty, APSInt const &Val) { Info.FFDiag(BCE->getBeginLoc(), diag::note_constexpr_bit_cast_unrepresentable_value) << Ty << toString(Val, /*Radix=*/10); return None; } - Optional visit(const BuiltinType *T, CharUnits Offset, - const EnumType *EnumSugar = nullptr) { + Optional visit(BuiltinType const *T, CharUnits Offset, + EnumType const *EnumSugar = nullptr) { if (T->isNullPtrType()) { uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0)); return APValue((Expr *)nullptr, @@ -6985,7 +6970,7 @@ // is really just `long double` on x86, which is the only fundamental type // with padding bytes. if (T->isRealFloatingType()) { - const llvm::fltSemantics &Semantics = + llvm::fltSemantics const &Semantics = Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics); assert(NumBits % 8 == 0); @@ -7003,9 +6988,8 @@ !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) || T->isSpecificBuiltinType(BuiltinType::Char_U)); if (!IsStdByte && !IsUChar) { - QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0); - Info.FFDiag(BCE->getExprLoc(), - diag::note_constexpr_bit_cast_indet_dest) + QualType DisplayType(EnumSugar ? (Type const *)EnumSugar : T, 0); + Info.FFDiag(BCE->getExprLoc(), diag::note_constexpr_bit_cast_indet_dest) << DisplayType << Info.Ctx.getLangOpts().CharIsSigned; return None; } @@ -7031,7 +7015,7 @@ } if (T->isRealFloatingType()) { - const llvm::fltSemantics &Semantics = + llvm::fltSemantics const &Semantics = Info.Ctx.getFloatTypeSemantics(QualType(T, 0)); return APValue(APFloat(Semantics, Val)); } @@ -7039,9 +7023,9 @@ return unsupportedType(QualType(T, 0)); } - Optional visit(const RecordType *RTy, CharUnits Offset) { - const RecordDecl *RD = RTy->getAsRecordDecl(); - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); + Optional visit(RecordType const *RTy, CharUnits Offset) { + RecordDecl const *RD = RTy->getAsRecordDecl(); + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(RD); unsigned NumBases = 0; if (auto *CXXRD = dyn_cast(RD)) @@ -7053,7 +7037,7 @@ // Visit the base classes. if (auto *CXXRD = dyn_cast(RD)) { for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) { - const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I]; + CXXBaseSpecifier const &BS = CXXRD->bases_begin()[I]; CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); if (BaseDecl->isEmpty() || Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero()) @@ -7095,18 +7079,18 @@ return ResultVal; } - Optional visit(const EnumType *Ty, CharUnits Offset) { + Optional visit(EnumType const *Ty, CharUnits Offset) { QualType RepresentationType = Ty->getDecl()->getIntegerType(); assert(!RepresentationType.isNull() && "enum forward decl should be caught by Sema"); - const auto *AsBuiltin = + auto const *AsBuiltin = RepresentationType.getCanonicalType()->castAs(); // Recurse into the underlying type. Treat std::byte transparently as // unsigned char. return visit(AsBuiltin, Offset, /*EnumTy=*/Ty); } - Optional visit(const ConstantArrayType *Ty, CharUnits Offset) { + Optional visit(ConstantArrayType const *Ty, CharUnits Offset) { size_t Size = Ty->getSize().getLimitedValue(); CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType()); @@ -7122,7 +7106,7 @@ return ArrayValue; } - Optional visit(const Type *Ty, CharUnits Offset) { + Optional visit(Type const *Ty, CharUnits Offset) { return unsupportedType(QualType(Ty, 0)); } @@ -7152,7 +7136,7 @@ public: // Pull out a full value of type DstType. static Optional convert(EvalInfo &Info, BitCastBuffer &Buffer, - const CastExpr *BCE) { + CastExpr const *BCE) { BufferToAPValueConverter Converter(Info, Buffer, BCE); return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0)); } @@ -7160,7 +7144,7 @@ static bool checkBitCastConstexprEligibilityType(SourceLocation Loc, QualType Ty, EvalInfo *Info, - const ASTContext &Ctx, + ASTContext const &Ctx, bool CheckingDest) { Ty = Ty.getCanonicalType(); @@ -7211,8 +7195,8 @@ } static bool checkBitCastConstexprEligibility(EvalInfo *Info, - const ASTContext &Ctx, - const CastExpr *BCE) { + ASTContext const &Ctx, + CastExpr const *BCE) { bool DestOK = checkBitCastConstexprEligibilityType( BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true); bool SourceOK = DestOK && checkBitCastConstexprEligibilityType( @@ -7223,7 +7207,7 @@ static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue, APValue &SourceValue, - const CastExpr *BCE) { + CastExpr const *BCE) { assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 && "no host or target supports non 8-bit chars"); assert(SourceValue.isLValue() && @@ -7257,22 +7241,21 @@ } template -class ExprEvaluatorBase - : public ConstStmtVisitor { +class ExprEvaluatorBase : public ConstStmtVisitor { private: - Derived &getDerived() { return static_cast(*this); } - bool DerivedSuccess(const APValue &V, const Expr *E) { + Derived &getDerived() { return static_cast(*this); } + bool DerivedSuccess(APValue const &V, Expr const *E) { return getDerived().Success(V, E); } - bool DerivedZeroInitialization(const Expr *E) { + bool DerivedZeroInitialization(Expr const *E) { return getDerived().ZeroInitialization(E); } // Check whether a conditional operator with a non-constant condition is a // potential constant expression. If neither arm is a potential constant // expression, then the conditional operator is not either. - template - void CheckPotentialConstantConditional(const ConditionalOperator *E) { + template + void CheckPotentialConstantConditional(ConditionalOperator const *E) { assert(Info.checkingPotentialConstantExpression()); // Speculatively evaluate both arms. @@ -7295,9 +7278,8 @@ Error(E, diag::note_constexpr_conditional_never_const); } - - template - bool HandleConditionalOperator(const ConditionalOperator *E) { + template + bool HandleConditionalOperator(ConditionalOperator const *E) { bool BoolResult; if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) { if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) { @@ -7320,11 +7302,11 @@ typedef ConstStmtVisitor StmtVisitorTy; typedef ExprEvaluatorBase ExprEvaluatorBaseTy; - OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { + OptionalDiagnostic CCEDiag(Expr const *E, diag::kind D) { return Info.CCEDiag(E, D); } - bool ZeroInitialization(const Expr *E) { return Error(E); } + bool ZeroInitialization(Expr const *E) { return Error(E); } public: ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {} @@ -7333,46 +7315,51 @@ /// Report an evaluation error. This should only be called when an error is /// first discovered. When propagating an error, just return false. - bool Error(const Expr *E, diag::kind D) { + bool Error(Expr const *E, diag::kind D) { Info.FFDiag(E, D); return false; } - bool Error(const Expr *E) { + bool Error(Expr const *E) { return Error(E, diag::note_invalid_subexpr_in_const_expr); } - bool VisitStmt(const Stmt *) { + bool VisitStmt(Stmt const *) { llvm_unreachable("Expression evaluator should not be called on stmts"); } - bool VisitExpr(const Expr *E) { - return Error(E); - } + bool VisitExpr(Expr const *E) { return Error(E); } - bool VisitConstantExpr(const ConstantExpr *E) { + bool VisitConstantExpr(ConstantExpr const *E) { if (E->hasAPValueResult()) return DerivedSuccess(E->getAPValueResult(), E); return StmtVisitorTy::Visit(E->getSubExpr()); } - bool VisitParenExpr(const ParenExpr *E) - { return StmtVisitorTy::Visit(E->getSubExpr()); } - bool VisitUnaryExtension(const UnaryOperator *E) - { return StmtVisitorTy::Visit(E->getSubExpr()); } - bool VisitUnaryPlus(const UnaryOperator *E) - { return StmtVisitorTy::Visit(E->getSubExpr()); } - bool VisitChooseExpr(const ChooseExpr *E) - { return StmtVisitorTy::Visit(E->getChosenSubExpr()); } - bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) - { return StmtVisitorTy::Visit(E->getResultExpr()); } - bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E) - { return StmtVisitorTy::Visit(E->getReplacement()); } - bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { + bool VisitParenExpr(ParenExpr const *E) { + return StmtVisitorTy::Visit(E->getSubExpr()); + } + bool VisitUnaryExtension(UnaryOperator const *E) { + return StmtVisitorTy::Visit(E->getSubExpr()); + } + bool VisitUnaryPlus(UnaryOperator const *E) { + return StmtVisitorTy::Visit(E->getSubExpr()); + } + bool VisitChooseExpr(ChooseExpr const *E) { + return StmtVisitorTy::Visit(E->getChosenSubExpr()); + } + bool VisitGenericSelectionExpr(GenericSelectionExpr const *E) { + return StmtVisitorTy::Visit(E->getResultExpr()); + } + bool + VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr const *E) { + return StmtVisitorTy::Visit(E->getReplacement()); + } + bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr const *E) { TempVersionRAII RAII(*Info.CurrentCall); SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope); return StmtVisitorTy::Visit(E->getExpr()); } - bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { + bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr const *E) { TempVersionRAII RAII(*Info.CurrentCall); // The initializer may not have been parsed yet, or might be erroneous. if (!E->getExpr()) @@ -7381,31 +7368,31 @@ return StmtVisitorTy::Visit(E->getExpr()); } - bool VisitExprWithCleanups(const ExprWithCleanups *E) { + bool VisitExprWithCleanups(ExprWithCleanups const *E) { FullExpressionRAII Scope(Info); return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy(); } // Temporaries are registered when created, so we don't care about // CXXBindTemporaryExpr. - bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) { + bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr const *E) { return StmtVisitorTy::Visit(E->getSubExpr()); } - bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) { + bool VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr const *E) { CCEDiag(E, diag::note_constexpr_invalid_cast) << 0; - return static_cast(this)->VisitCastExpr(E); + return static_cast(this)->VisitCastExpr(E); } - bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) { + bool VisitCXXDynamicCastExpr(CXXDynamicCastExpr const *E) { if (!Info.Ctx.getLangOpts().CPlusPlus20) CCEDiag(E, diag::note_constexpr_invalid_cast) << 1; - return static_cast(this)->VisitCastExpr(E); + return static_cast(this)->VisitCastExpr(E); } - bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) { - return static_cast(this)->VisitCastExpr(E); + bool VisitBuiltinBitCastExpr(BuiltinBitCastExpr const *E) { + return static_cast(this)->VisitCastExpr(E); } - bool VisitBinaryOperator(const BinaryOperator *E) { + bool VisitBinaryOperator(BinaryOperator const *E) { switch (E->getOpcode()) { default: return Error(E); @@ -7427,11 +7414,11 @@ } } - bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) { + bool VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator const *E) { return StmtVisitorTy::Visit(E->getSemanticForm()); } - bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) { + bool VisitBinaryConditionalOperator(BinaryConditionalOperator const *E) { // Evaluate and cache the common expression. We treat it as a temporary, // even though it's not quite the same thing. LValue CommonLV; @@ -7445,14 +7432,14 @@ return HandleConditionalOperator(E); } - bool VisitConditionalOperator(const ConditionalOperator *E) { + bool VisitConditionalOperator(ConditionalOperator const *E) { bool IsBcpCall = false; // If the condition (ignoring parens) is a __builtin_constant_p call, // the result is a constant expression if it can be folded without // side-effects. This is an important GNU extension. See GCC PR38377 // for discussion. - if (const CallExpr *CallCE = - dyn_cast(E->getCond()->IgnoreParenCasts())) + if (CallExpr const *CallCE = + dyn_cast(E->getCond()->IgnoreParenCasts())) if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) IsBcpCall = true; @@ -7472,11 +7459,11 @@ return true; } - bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) { + bool VisitOpaqueValueExpr(OpaqueValueExpr const *E) { if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E)) return DerivedSuccess(*Value, E); - const Expr *Source = E->getSourceExpr(); + Expr const *Source = E->getSourceExpr(); if (!Source) return Error(E); if (Source == E) { // sanity checking. @@ -7486,8 +7473,8 @@ return StmtVisitorTy::Visit(Source); } - bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) { - for (const Expr *SemE : E->semantics()) { + bool VisitPseudoObjectExpr(PseudoObjectExpr const *E) { + for (Expr const *SemE : E->semantics()) { if (auto *OVE = dyn_cast(SemE)) { // FIXME: We can't handle the case where an OpaqueValueExpr is also the // result expression: there could be two different LValues that would @@ -7517,21 +7504,21 @@ return true; } - bool VisitCallExpr(const CallExpr *E) { + bool VisitCallExpr(CallExpr const *E) { APValue Result; if (!handleCallExpr(E, Result, nullptr)) return false; return DerivedSuccess(Result, E); } - bool handleCallExpr(const CallExpr *E, APValue &Result, - const LValue *ResultSlot) { + bool handleCallExpr(CallExpr const *E, APValue &Result, + LValue const *ResultSlot) { CallScopeRAII CallScope(Info); - const Expr *Callee = E->getCallee()->IgnoreParens(); + Expr const *Callee = E->getCallee()->IgnoreParens(); QualType CalleeType = Callee->getType(); - const FunctionDecl *FD = nullptr; + FunctionDecl const *FD = nullptr; LValue *This = nullptr, ThisVal; auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); bool HasQualifier = false; @@ -7540,8 +7527,8 @@ // Extract function decl and 'this' pointer from the callee. if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) { - const CXXMethodDecl *Member = nullptr; - if (const MemberExpr *ME = dyn_cast(Callee)) { + CXXMethodDecl const *Member = nullptr; + if (MemberExpr const *ME = dyn_cast(Callee)) { // Explicit bound member calls, such as x.f() or p->g(); if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal)) return false; @@ -7550,9 +7537,9 @@ return Error(Callee); This = &ThisVal; HasQualifier = ME->hasQualifier(); - } else if (const BinaryOperator *BE = dyn_cast(Callee)) { + } else if (BinaryOperator const *BE = dyn_cast(Callee)) { // Indirect bound member calls ('.*' or '->*'). - const ValueDecl *D = + ValueDecl const *D = HandleMemberPointerAccess(Info, BE, ThisVal, false); if (!D) return false; @@ -7560,7 +7547,7 @@ if (!Member) return Error(Callee); This = &ThisVal; - } else if (const auto *PDE = dyn_cast(Callee)) { + } else if (auto const *PDE = dyn_cast(Callee)) { if (!Info.getLangOpts().CPlusPlus20) Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor); return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) && @@ -7576,13 +7563,13 @@ if (!CalleeLV.getLValueOffset().isZero()) return Error(Callee); FD = dyn_cast_or_null( - CalleeLV.getLValueBase().dyn_cast()); + CalleeLV.getLValueBase().dyn_cast()); if (!FD) return Error(Callee); // Don't call function pointers which have been cast to some other type. // Per DR (no number yet), the caller and callee can differ in noexcept. if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec( - CalleeType->getPointeeType(), FD->getType())) { + CalleeType->getPointeeType(), FD->getType())) { return Error(E); } @@ -7599,7 +7586,7 @@ // Overloaded operator calls to member functions are represented as normal // calls with '*this' as the first argument. - const CXXMethodDecl *MD = dyn_cast(FD); + CXXMethodDecl const *MD = dyn_cast(FD); if (MD && !MD->isStatic()) { // FIXME: When selecting an implicit conversion for an overloaded // operator delete, we sometimes try to evaluate calls to conversion @@ -7616,12 +7603,12 @@ // Conveniently, we don't have to slice out the 'this' argument (as is // being done for the non-static case), since a static member function // doesn't have an implicit argument passed in. - const CXXRecordDecl *ClosureClass = MD->getParent(); + CXXRecordDecl const *ClosureClass = MD->getParent(); assert( ClosureClass->captures_begin() == ClosureClass->captures_end() && "Number of captures must be zero for conversion to function-ptr"); - const CXXMethodDecl *LambdaCallOp = + CXXMethodDecl const *LambdaCallOp = ClosureClass->getLambdaCallOperator(); // Set 'FD', the function that will be called below, to the call @@ -7632,7 +7619,7 @@ assert(MD->isFunctionTemplateSpecialization() && "A generic lambda's static-invoker function must be a " "template specialization"); - const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); + TemplateArgumentList const *TAL = MD->getTemplateSpecializationArgs(); FunctionTemplateDecl *CallOpTemplate = LambdaCallOp->getDescribedFunctionTemplate(); void *InsertPos = nullptr; @@ -7692,12 +7679,12 @@ CallScope.destroy(); } - const FunctionDecl *Definition = nullptr; + FunctionDecl const *Definition = nullptr; Stmt *Body = FD->getBody(Definition); if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) || - !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, - Body, Info, Result, ResultSlot)) + !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call, Body, + Info, Result, ResultSlot)) return false; if (!CovariantAdjustmentPath.empty() && @@ -7708,28 +7695,28 @@ return CallScope.destroy(); } - bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { + bool VisitCompoundLiteralExpr(CompoundLiteralExpr const *E) { return StmtVisitorTy::Visit(E->getInitializer()); } - bool VisitInitListExpr(const InitListExpr *E) { + bool VisitInitListExpr(InitListExpr const *E) { if (E->getNumInits() == 0) return DerivedZeroInitialization(E); if (E->getNumInits() == 1) return StmtVisitorTy::Visit(E->getInit(0)); return Error(E); } - bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) { + bool VisitImplicitValueInitExpr(ImplicitValueInitExpr const *E) { return DerivedZeroInitialization(E); } - bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) { + bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr const *E) { return DerivedZeroInitialization(E); } - bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) { + bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr const *E) { return DerivedZeroInitialization(E); } /// A member expression where the object is a prvalue is itself a prvalue. - bool VisitMemberExpr(const MemberExpr *E) { + bool VisitMemberExpr(MemberExpr const *E) { assert(!Info.Ctx.getLangOpts().CPlusPlus11 && "missing temporary materialization conversion"); assert(!E->isArrow() && "missing call to bound member function?"); @@ -7740,11 +7727,13 @@ QualType BaseTy = E->getBase()->getType(); - const FieldDecl *FD = dyn_cast(E->getMemberDecl()); - if (!FD) return Error(E); + FieldDecl const *FD = dyn_cast(E->getMemberDecl()); + if (!FD) + return Error(E); assert(!FD->getType()->isReferenceType() && "prvalue reference?"); assert(BaseTy->castAs()->getDecl()->getCanonicalDecl() == - FD->getParent()->getCanonicalDecl() && "record / field mismatch"); + FD->getParent()->getCanonicalDecl() && + "record / field mismatch"); // Note: there is no lvalue base here. But this case should only ever // happen in C or in C++98, where we cannot be evaluating a constexpr @@ -7758,7 +7747,7 @@ DerivedSuccess(Result, E); } - bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) { + bool VisitExtVectorElementExpr(ExtVectorElementExpr const *E) { APValue Val; if (!Evaluate(Val, Info, E->getBase())) return false; @@ -7783,7 +7772,7 @@ return false; } - bool VisitCastExpr(const CastExpr *E) { + bool VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { default: break; @@ -7833,13 +7822,13 @@ return Error(E); } - bool VisitUnaryPostInc(const UnaryOperator *UO) { + bool VisitUnaryPostInc(UnaryOperator const *UO) { return VisitUnaryPostIncDec(UO); } - bool VisitUnaryPostDec(const UnaryOperator *UO) { + bool VisitUnaryPostDec(UnaryOperator const *UO) { return VisitUnaryPostIncDec(UO); } - bool VisitUnaryPostIncDec(const UnaryOperator *UO) { + bool VisitUnaryPostIncDec(UnaryOperator const *UO) { if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) return Error(UO); @@ -7853,13 +7842,13 @@ return DerivedSuccess(RVal, UO); } - bool VisitStmtExpr(const StmtExpr *E) { + bool VisitStmtExpr(StmtExpr const *E) { // We will have checked the full-expressions inside the statement expression // when they were completed, and don't need to check them again now. llvm::SaveAndRestore NotCheckingForUB( Info.CheckingForUndefinedBehavior, false); - const CompoundStmt *CS = E->getSubStmt(); + CompoundStmt const *CS = E->getSubStmt(); if (CS->body_empty()) return true; @@ -7868,7 +7857,7 @@ BE = CS->body_end(); /**/; ++BI) { if (BI + 1 == BE) { - const Expr *FinalExpr = dyn_cast(*BI); + Expr const *FinalExpr = dyn_cast(*BI); if (!FinalExpr) { Info.FFDiag((*BI)->getBeginLoc(), diag::note_constexpr_stmt_expr_unsupported); @@ -7878,7 +7867,7 @@ } APValue ReturnValue; - StmtResult Result = { ReturnValue, nullptr }; + StmtResult Result = {ReturnValue, nullptr}; EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI); if (ESR != ESR_Succeeded) { // FIXME: If the statement-expression terminated due to 'return', @@ -7895,12 +7884,10 @@ } /// Visit a value which is evaluated, but whose value is ignored. - void VisitIgnoredValue(const Expr *E) { - EvaluateIgnoredValue(Info, E); - } + void VisitIgnoredValue(Expr const *E) { EvaluateIgnoredValue(Info, E); } /// Potentially visit a MemberExpr's base expression. - void VisitIgnoredBaseExpression(const Expr *E) { + void VisitIgnoredBaseExpression(Expr const *E) { // While MSVC doesn't evaluate the base expression, it does diagnose the // presence of side-effecting behavior. if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx)) @@ -7915,9 +7902,8 @@ // Common base class for lvalue and temporary evaluation. //===----------------------------------------------------------------------===// namespace { -template -class LValueExprEvaluatorBase - : public ExprEvaluatorBase { +template +class LValueExprEvaluatorBase : public ExprEvaluatorBase { protected: LValue &Result; bool InvalidBaseOK; @@ -7929,7 +7915,7 @@ return true; } - bool evaluatePointer(const Expr *E, LValue &Result) { + bool evaluatePointer(Expr const *E, LValue &Result) { return EvaluatePointer(E, Result, this->Info, InvalidBaseOK); } @@ -7938,12 +7924,12 @@ : ExprEvaluatorBaseTy(Info), Result(Result), InvalidBaseOK(InvalidBaseOK) {} - bool Success(const APValue &V, const Expr *E) { + bool Success(APValue const &V, Expr const *E) { Result.setFrom(this->Info.Ctx, V); return true; } - bool VisitMemberExpr(const MemberExpr *E) { + bool VisitMemberExpr(MemberExpr const *E) { // Handle non-static data members. QualType BaseTy; bool EvalOK; @@ -7965,14 +7951,15 @@ return true; } - const ValueDecl *MD = E->getMemberDecl(); - if (const FieldDecl *FD = dyn_cast(E->getMemberDecl())) { + ValueDecl const *MD = E->getMemberDecl(); + if (FieldDecl const *FD = dyn_cast(E->getMemberDecl())) { assert(BaseTy->castAs()->getDecl()->getCanonicalDecl() == - FD->getParent()->getCanonicalDecl() && "record / field mismatch"); + FD->getParent()->getCanonicalDecl() && + "record / field mismatch"); (void)BaseTy; if (!HandleLValueMember(this->Info, E, Result, FD)) return false; - } else if (const IndirectFieldDecl *IFD = dyn_cast(MD)) { + } else if (IndirectFieldDecl const *IFD = dyn_cast(MD)) { if (!HandleLValueIndirectMember(this->Info, E, Result, IFD)) return false; } else @@ -7988,7 +7975,7 @@ return true; } - bool VisitBinaryOperator(const BinaryOperator *E) { + bool VisitBinaryOperator(BinaryOperator const *E) { switch (E->getOpcode()) { default: return ExprEvaluatorBaseTy::VisitBinaryOperator(E); @@ -7999,7 +7986,7 @@ } } - bool VisitCastExpr(const CastExpr *E) { + bool VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { default: return ExprEvaluatorBaseTy::VisitCastExpr(E); @@ -8016,7 +8003,7 @@ } } }; -} +} // namespace //===----------------------------------------------------------------------===// // LValue Evaluation @@ -8053,37 +8040,37 @@ //===----------------------------------------------------------------------===// namespace { class LValueExprEvaluator - : public LValueExprEvaluatorBase { + : public LValueExprEvaluatorBase { public: - LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) : - LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} - - bool VisitVarDecl(const Expr *E, const VarDecl *VD); - bool VisitUnaryPreIncDec(const UnaryOperator *UO); - - bool VisitDeclRefExpr(const DeclRefExpr *E); - bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); } - bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E); - bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); - bool VisitMemberExpr(const MemberExpr *E); - bool VisitStringLiteral(const StringLiteral *E) { return Success(E); } - bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); } - bool VisitCXXTypeidExpr(const CXXTypeidExpr *E); - bool VisitCXXUuidofExpr(const CXXUuidofExpr *E); - bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E); - bool VisitUnaryDeref(const UnaryOperator *E); - bool VisitUnaryReal(const UnaryOperator *E); - bool VisitUnaryImag(const UnaryOperator *E); - bool VisitUnaryPreInc(const UnaryOperator *UO) { + LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) + : LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {} + + bool VisitVarDecl(Expr const *E, VarDecl const *VD); + bool VisitUnaryPreIncDec(UnaryOperator const *UO); + + bool VisitDeclRefExpr(DeclRefExpr const *E); + bool VisitPredefinedExpr(PredefinedExpr const *E) { return Success(E); } + bool VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr const *E); + bool VisitCompoundLiteralExpr(CompoundLiteralExpr const *E); + bool VisitMemberExpr(MemberExpr const *E); + bool VisitStringLiteral(StringLiteral const *E) { return Success(E); } + bool VisitObjCEncodeExpr(ObjCEncodeExpr const *E) { return Success(E); } + bool VisitCXXTypeidExpr(CXXTypeidExpr const *E); + bool VisitCXXUuidofExpr(CXXUuidofExpr const *E); + bool VisitArraySubscriptExpr(ArraySubscriptExpr const *E); + bool VisitUnaryDeref(UnaryOperator const *E); + bool VisitUnaryReal(UnaryOperator const *E); + bool VisitUnaryImag(UnaryOperator const *E); + bool VisitUnaryPreInc(UnaryOperator const *UO) { return VisitUnaryPreIncDec(UO); } - bool VisitUnaryPreDec(const UnaryOperator *UO) { + bool VisitUnaryPreDec(UnaryOperator const *UO) { return VisitUnaryPreIncDec(UO); } - bool VisitBinAssign(const BinaryOperator *BO); - bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO); + bool VisitBinAssign(BinaryOperator const *BO); + bool VisitCompoundAssignOperator(CompoundAssignOperator const *CAO); - bool VisitCastExpr(const CastExpr *E) { + bool VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { default: return LValueExprEvaluatorBaseTy::VisitCastExpr(E); @@ -8114,7 +8101,7 @@ /// * function designators in C, and /// * "extern void" objects /// * @selector() expressions in Objective-C -static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, +static bool EvaluateLValue(Expr const *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK) { assert(!E->isValueDependent()); assert(E->isGLValue() || E->getType()->isFunctionType() || @@ -8122,19 +8109,18 @@ return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); } -bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) { - const NamedDecl *D = E->getDecl(); +bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr const *E) { + NamedDecl const *D = E->getDecl(); if (isa(D)) return Success(cast(D)); - if (const VarDecl *VD = dyn_cast(D)) + if (VarDecl const *VD = dyn_cast(D)) return VisitVarDecl(E, VD); - if (const BindingDecl *BD = dyn_cast(D)) + if (BindingDecl const *BD = dyn_cast(D)) return Visit(BD->getBinding()); return Error(E); } - -bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) { +bool LValueExprEvaluator::VisitVarDecl(Expr const *E, VarDecl const *VD) { // If we are within a lambda's call operator, check whether the 'VD' referred // to within 'E' actually represents a lambda-capture that maps to a @@ -8226,11 +8212,11 @@ } bool LValueExprEvaluator::VisitMaterializeTemporaryExpr( - const MaterializeTemporaryExpr *E) { + MaterializeTemporaryExpr const *E) { // Walk through the expression to find the materialized temporary itself. - SmallVector CommaLHSs; + SmallVector CommaLHSs; SmallVector Adjustments; - const Expr *Inner = + Expr const *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); // If we passed any comma operators, evaluate their LHSs. @@ -8292,8 +8278,8 @@ return true; } -bool -LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { +bool LValueExprEvaluator::VisitCompoundLiteralExpr( + CompoundLiteralExpr const *E) { assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) && "lvalue compound literal in c++?"); // Defer visiting the literal until the lvalue-to-rvalue conversion. We can @@ -8301,7 +8287,7 @@ return Success(E); } -bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { +bool LValueExprEvaluator::VisitCXXTypeidExpr(CXXTypeidExpr const *E) { TypeInfoLValue TypeInfo; if (!E->isPotentiallyEvaluated()) { @@ -8312,8 +8298,8 @@ } else { if (!Info.Ctx.getLangOpts().CPlusPlus20) { Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic) - << E->getExprOperand()->getType() - << E->getExprOperand()->getSourceRange(); + << E->getExprOperand()->getType() + << E->getExprOperand()->getSourceRange(); } if (!Visit(E->getExprOperand())) @@ -8331,19 +8317,19 @@ return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType())); } -bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { +bool LValueExprEvaluator::VisitCXXUuidofExpr(CXXUuidofExpr const *E) { return Success(E->getGuidDecl()); } -bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) { +bool LValueExprEvaluator::VisitMemberExpr(MemberExpr const *E) { // Handle static data members. - if (const VarDecl *VD = dyn_cast(E->getMemberDecl())) { + if (VarDecl const *VD = dyn_cast(E->getMemberDecl())) { VisitIgnoredBaseExpression(E->getBase()); return VisitVarDecl(E, VD); } // Handle static member functions. - if (const CXXMethodDecl *MD = dyn_cast(E->getMemberDecl())) { + if (CXXMethodDecl const *MD = dyn_cast(E->getMemberDecl())) { if (MD->isStatic()) { VisitIgnoredBaseExpression(E->getBase()); return Success(MD); @@ -8354,7 +8340,7 @@ return LValueExprEvaluatorBaseTy::VisitMemberExpr(E); } -bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { +bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr const *E) { // FIXME: Deal with vectors as array subscript bases. if (E->getBase()->getType()->isVectorType()) return Error(E); @@ -8364,7 +8350,7 @@ // C++17's rules require us to evaluate the LHS first, regardless of which // side is the base. - for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) { + for (Expr const *SubExpr : {E->getLHS(), E->getRHS()}) { if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result) : !EvaluateInteger(SubExpr, Index, Info)) { if (!Info.noteFailure()) @@ -8377,11 +8363,11 @@ HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index); } -bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) { +bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator const *E) { return evaluatePointer(E->getSubExpr(), Result); } -bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { +bool LValueExprEvaluator::VisitUnaryReal(UnaryOperator const *E) { if (!Visit(E->getSubExpr())) return false; // __real is a no-op on scalar lvalues. @@ -8390,7 +8376,7 @@ return true; } -bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { +bool LValueExprEvaluator::VisitUnaryImag(UnaryOperator const *E) { assert(E->getSubExpr()->getType()->isAnyComplexType() && "lvalue __imag__ on scalar?"); if (!Visit(E->getSubExpr())) @@ -8399,20 +8385,19 @@ return true; } -bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) { +bool LValueExprEvaluator::VisitUnaryPreIncDec(UnaryOperator const *UO) { if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) return Error(UO); if (!this->Visit(UO->getSubExpr())) return false; - return handleIncDec( - this->Info, UO, Result, UO->getSubExpr()->getType(), - UO->isIncrementOp(), nullptr); + return handleIncDec(this->Info, UO, Result, UO->getSubExpr()->getType(), + UO->isIncrementOp(), nullptr); } bool LValueExprEvaluator::VisitCompoundAssignOperator( - const CompoundAssignOperator *CAO) { + CompoundAssignOperator const *CAO) { if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) return Error(CAO); @@ -8431,12 +8416,12 @@ return false; return handleCompoundAssignment( - this->Info, CAO, - Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(), + this->Info, CAO, Result, CAO->getLHS()->getType(), + CAO->getComputationLHSType(), CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS); } -bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) { +bool LValueExprEvaluator::VisitBinAssign(BinaryOperator const *E) { if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure()) return Error(E); @@ -8471,10 +8456,10 @@ /// /// This expects the given CallExpr to be a call to a function with an /// alloc_size attribute. -static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, - const CallExpr *Call, +static bool getBytesReturnedByAllocSizeCall(ASTContext const &Ctx, + CallExpr const *Call, llvm::APInt &Result) { - const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call); + AllocSizeAttr const *AllocSize = getAllocSizeAttr(Call); assert(AllocSize && AllocSize->getElemSizeParam().isValid()); unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex(); @@ -8482,7 +8467,7 @@ if (Call->getNumArgs() <= SizeArgNo) return false; - auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) { + auto EvaluateAsSizeT = [&](Expr const *E, APSInt &Into) { Expr::EvalResult ExprResult; if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects)) return false; @@ -8518,13 +8503,13 @@ /// Convenience function. LVal's base must be a call to an alloc_size /// function. -static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, - const LValue &LVal, +static bool getBytesReturnedByAllocSizeCall(ASTContext const &Ctx, + LValue const &LVal, llvm::APInt &Result) { assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) && "Can't get the size of a non alloc_size function"); - const auto *Base = LVal.getLValueBase().get(); - const CallExpr *CE = tryUnwrapAllocSizeCall(Base); + auto const *Base = LVal.getLValueBase().get(); + CallExpr const *CE = tryUnwrapAllocSizeCall(Base); return getBytesReturnedByAllocSizeCall(Ctx, CE, Result); } @@ -8542,16 +8527,16 @@ // Additionally, we can't support parameters, nor can we support static // variables (in the latter case, use-before-assign isn't UB; in the former, // we have no clue what they'll be assigned to). - const auto *VD = - dyn_cast_or_null(Base.dyn_cast()); + auto const *VD = + dyn_cast_or_null(Base.dyn_cast()); if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified()) return false; - const Expr *Init = VD->getAnyInitializer(); + Expr const *Init = VD->getAnyInitializer(); if (!Init) return false; - const Expr *E = Init->IgnoreParens(); + Expr const *E = Init->IgnoreParens(); if (!tryUnwrapAllocSizeCall(E)) return false; @@ -8565,62 +8550,59 @@ } namespace { -class PointerExprEvaluator - : public ExprEvaluatorBase { +class PointerExprEvaluator : public ExprEvaluatorBase { LValue &Result; bool InvalidBaseOK; - bool Success(const Expr *E) { + bool Success(Expr const *E) { Result.set(E); return true; } - bool evaluateLValue(const Expr *E, LValue &Result) { + bool evaluateLValue(Expr const *E, LValue &Result) { return EvaluateLValue(E, Result, Info, InvalidBaseOK); } - bool evaluatePointer(const Expr *E, LValue &Result) { + bool evaluatePointer(Expr const *E, LValue &Result) { return EvaluatePointer(E, Result, Info, InvalidBaseOK); } - bool visitNonBuiltinCallExpr(const CallExpr *E); -public: + bool visitNonBuiltinCallExpr(CallExpr const *E); +public: PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK) : ExprEvaluatorBaseTy(info), Result(Result), InvalidBaseOK(InvalidBaseOK) {} - bool Success(const APValue &V, const Expr *E) { + bool Success(APValue const &V, Expr const *E) { Result.setFrom(Info.Ctx, V); return true; } - bool ZeroInitialization(const Expr *E) { + bool ZeroInitialization(Expr const *E) { Result.setNull(Info.Ctx, E->getType()); return true; } - bool VisitBinaryOperator(const BinaryOperator *E); - bool VisitCastExpr(const CastExpr* E); - bool VisitUnaryAddrOf(const UnaryOperator *E); - bool VisitObjCStringLiteral(const ObjCStringLiteral *E) - { return Success(E); } - bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { + bool VisitBinaryOperator(BinaryOperator const *E); + bool VisitCastExpr(CastExpr const *E); + bool VisitUnaryAddrOf(UnaryOperator const *E); + bool VisitObjCStringLiteral(ObjCStringLiteral const *E) { return Success(E); } + bool VisitObjCBoxedExpr(ObjCBoxedExpr const *E) { if (E->isExpressibleAsConstantInitializer()) return Success(E); if (Info.noteFailure()) EvaluateIgnoredValue(Info, E->getSubExpr()); return Error(E); } - bool VisitAddrLabelExpr(const AddrLabelExpr *E) - { return Success(E); } - bool VisitCallExpr(const CallExpr *E); - bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); - bool VisitBlockExpr(const BlockExpr *E) { + bool VisitAddrLabelExpr(AddrLabelExpr const *E) { return Success(E); } + bool VisitCallExpr(CallExpr const *E); + bool VisitBuiltinCallExpr(CallExpr const *E, unsigned BuiltinOp); + bool VisitBlockExpr(BlockExpr const *E) { if (!E->getBlockDecl()->hasCaptures()) return Success(E); return Error(E); } - bool VisitCXXThisExpr(const CXXThisExpr *E) { + bool VisitCXXThisExpr(CXXThisExpr const *E) { // Can't look at 'this' when checking a potential constant expression. if (Info.checkingPotentialConstantExpression()) return false; @@ -8645,9 +8627,10 @@ // Update 'Result' to refer to the data member/field of the closure object // that represents the '*this' capture. if (!HandleLValueMember(Info, E, Result, - Info.CurrentCall->LambdaThisCaptureField)) + Info.CurrentCall->LambdaThisCaptureField)) return false; - // If we captured '*this' by reference, replace the field with its referent. + // If we captured '*this' by reference, replace the field with its + // referent. if (Info.CurrentCall->LambdaThisCaptureField->getType() ->isPointerType()) { APValue RVal; @@ -8661,9 +8644,9 @@ return true; } - bool VisitCXXNewExpr(const CXXNewExpr *E); + bool VisitCXXNewExpr(CXXNewExpr const *E); - bool VisitSourceLocExpr(const SourceLocExpr *E) { + bool VisitSourceLocExpr(SourceLocExpr const *E) { assert(E->isStringType() && "SourceLocExpr isn't a pointer type?"); APValue LValResult = E->EvaluateInContext( Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); @@ -8671,7 +8654,7 @@ return true; } - bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) { + bool VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr const *E) { std::string ResultStr = E->ComputeName(Info.Ctx); Info.Ctx.SYCLUniqueStableNameEvaluatedValues[E] = ResultStr; @@ -8695,20 +8678,19 @@ }; } // end anonymous namespace -static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info, +static bool EvaluatePointer(Expr const *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E); } -bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { - if (E->getOpcode() != BO_Add && - E->getOpcode() != BO_Sub) +bool PointerExprEvaluator::VisitBinaryOperator(BinaryOperator const *E) { + if (E->getOpcode() != BO_Add && E->getOpcode() != BO_Sub) return ExprEvaluatorBaseTy::VisitBinaryOperator(E); - const Expr *PExp = E->getLHS(); - const Expr *IExp = E->getRHS(); + Expr const *PExp = E->getLHS(); + Expr const *IExp = E->getRHS(); if (IExp->getType()->isPointerType()) std::swap(PExp, IExp); @@ -8727,12 +8709,12 @@ return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset); } -bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { +bool PointerExprEvaluator::VisitUnaryAddrOf(UnaryOperator const *E) { return evaluateLValue(E->getSubExpr(), Result); } -bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) { - const Expr *SubExpr = E->getSubExpr(); +bool PointerExprEvaluator::VisitCastExpr(CastExpr const *E) { + Expr const *SubExpr = E->getSubExpr(); switch (E->getCastKind()) { default: @@ -8760,7 +8742,7 @@ Result.Designator.setInvalid(); if (SubExpr->getType()->isVoidPointerType()) CCEDiag(E, diag::note_constexpr_invalid_cast) - << 3 << SubExpr->getType(); + << 3 << SubExpr->getType(); else CCEDiag(E, diag::note_constexpr_invalid_cast) << 2; } @@ -8778,9 +8760,10 @@ // Now figure out the necessary offset to add to the base LV to get from // the derived class to the base class. - return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()-> - castAs()->getPointeeType(), - Result); + return HandleLValueBasePath( + Info, E, + E->getSubExpr()->getType()->castAs()->getPointeeType(), + Result); case CK_BaseToDerived: if (!Visit(E->getSubExpr())) @@ -8808,7 +8791,7 @@ if (Value.isInt()) { unsigned Size = Info.Ctx.getTypeSize(E->getType()); uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue(); - Result.Base = (Expr*)nullptr; + Result.Base = (Expr *)nullptr; Result.InvalidBase = false; Result.Offset = CharUnits::fromQuantity(N); Result.Designator.setInvalid(); @@ -8866,13 +8849,13 @@ // C++ [expr.alignof]p3: // When alignof is applied to a reference type, the result is the // alignment of the referenced type. - if (const ReferenceType *Ref = T->getAs()) + if (ReferenceType const *Ref = T->getAs()) T = Ref->getPointeeType(); if (T.getQualifiers().hasUnaligned()) return CharUnits::One(); - const bool AlignOfReturnsPreferred = + bool const AlignOfReturnsPreferred = Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; // __alignof is defined to return the preferred alignment. @@ -8880,7 +8863,7 @@ // as well. if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) return Info.Ctx.toCharUnitsFromBits( - Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); + Info.Ctx.getPreferredTypeAlign(T.getTypePtr())); // alignof and _Alignof are defined to return the ABI alignment. else if (ExprKind == UETT_AlignOf) return Info.Ctx.getTypeAlignInChars(T.getTypePtr()); @@ -8888,7 +8871,7 @@ llvm_unreachable("GetAlignOfType on a non-alignment ExprKind"); } -static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E, +static CharUnits GetAlignOfExpr(EvalInfo &Info, Expr const *E, UnaryExprOrTypeTrait ExprKind) { E = E->IgnoreParens(); @@ -8898,28 +8881,28 @@ // alignof decl is always accepted, even if it doesn't make sense: we default // to 1 in those cases. - if (const DeclRefExpr *DRE = dyn_cast(E)) + if (DeclRefExpr const *DRE = dyn_cast(E)) return Info.Ctx.getDeclAlign(DRE->getDecl(), - /*RefAsPointee*/true); + /*RefAsPointee*/ true); - if (const MemberExpr *ME = dyn_cast(E)) + if (MemberExpr const *ME = dyn_cast(E)) return Info.Ctx.getDeclAlign(ME->getMemberDecl(), - /*RefAsPointee*/true); + /*RefAsPointee*/ true); return GetAlignOfType(Info, E->getType(), ExprKind); } -static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) { - if (const auto *VD = Value.Base.dyn_cast()) +static CharUnits getBaseAlignment(EvalInfo &Info, LValue const &Value) { + if (auto const *VD = Value.Base.dyn_cast()) return Info.Ctx.getDeclAlign(VD); - if (const auto *E = Value.Base.dyn_cast()) + if (auto const *E = Value.Base.dyn_cast()) return GetAlignOfExpr(Info, E, UETT_AlignOf); return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf); } /// Evaluate the value of the alignment argument to __builtin_align_{up,down}, /// __builtin_is_aligned and __builtin_assume_aligned. -static bool getAlignmentArgument(const Expr *E, QualType ForType, +static bool getAlignmentArgument(Expr const *E, QualType ForType, EvalInfo &Info, APSInt &Alignment) { if (!EvaluateInteger(E, Alignment, Info)) return false; @@ -8946,7 +8929,7 @@ } // To be clear: this happily visits unsupported builtins. Better name welcomed. -bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) { +bool PointerExprEvaluator::visitNonBuiltinCallExpr(CallExpr const *E) { if (ExprEvaluatorBaseTy::VisitCallExpr(E)) return true; @@ -8959,7 +8942,7 @@ return true; } -bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) { +bool PointerExprEvaluator::VisitCallExpr(CallExpr const *E) { if (IsStringLiteralCall(E)) return Success(E); @@ -8975,7 +8958,7 @@ return T->isCharType() || T->isChar8Type(); } -bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, +bool PointerExprEvaluator::VisitBuiltinCallExpr(CallExpr const *E, unsigned BuiltinOp) { switch (BuiltinOp) { case Builtin::BI__builtin_addressof: @@ -9010,10 +8993,9 @@ if (BaseAlignment < Align) { Result.Designator.setInvalid(); // FIXME: Add support to Diagnostic for long / long long. - CCEDiag(E->getArg(0), - diag::note_constexpr_baa_insufficient_alignment) << 0 - << (unsigned)BaseAlignment.getQuantity() - << (unsigned)Align.getQuantity(); + CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment) + << 0 << (unsigned)BaseAlignment.getQuantity() + << (unsigned)Align.getQuantity(); return false; } } @@ -9024,11 +9006,12 @@ (OffsetResult.Base ? CCEDiag(E->getArg(0), - diag::note_constexpr_baa_insufficient_alignment) << 1 + diag::note_constexpr_baa_insufficient_alignment) + << 1 : CCEDiag(E->getArg(0), diag::note_constexpr_baa_value_insufficient_alignment)) - << (int)OffsetResult.Offset.getQuantity() - << (unsigned)Align.getQuantity(); + << (int)OffsetResult.Offset.getQuantity() + << (unsigned)Align.getQuantity(); return false; } @@ -9081,8 +9064,8 @@ case Builtin::BIwmemchr: if (Info.getLangOpts().CPlusPlus11) Info.CCEDiag(E, diag::note_constexpr_invalid_function) - << /*isConstexpr*/0 << /*isConstructor*/0 - << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); + << /*isConstexpr*/ 0 << /*isConstructor*/ 0 + << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); else Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); LLVM_FALLTHROUGH; @@ -9097,8 +9080,7 @@ if (!EvaluateInteger(E->getArg(1), Desired, Info)) return false; uint64_t MaxLength = uint64_t(-1); - if (BuiltinOp != Builtin::BIstrchr && - BuiltinOp != Builtin::BIwcschr && + if (BuiltinOp != Builtin::BIstrchr && BuiltinOp != Builtin::BIwcschr && BuiltinOp != Builtin::BI__builtin_strchr && BuiltinOp != Builtin::BI__builtin_wcschr) { APSInt N; @@ -9115,9 +9097,8 @@ QualType CharTy = Result.Designator.getType(Info.Ctx); bool IsRawByte = BuiltinOp == Builtin::BImemchr || BuiltinOp == Builtin::BI__builtin_memchr; - assert(IsRawByte || - Info.Ctx.hasSameUnqualifiedType( - CharTy, E->getArg(0)->getType()->getPointeeType())); + assert(IsRawByte || Info.Ctx.hasSameUnqualifiedType( + CharTy, E->getArg(0)->getType()->getPointeeType())); // Pointers to const void may point to objects of incomplete type. if (IsRawByte && CharTy->isIncompleteType()) { Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy; @@ -9189,8 +9170,8 @@ case Builtin::BIwmemmove: if (Info.getLangOpts().CPlusPlus11) Info.CCEDiag(E, diag::note_constexpr_invalid_function) - << /*isConstexpr*/0 << /*isConstructor*/0 - << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); + << /*isConstexpr*/ 0 << /*isConstructor*/ 0 + << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); else Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); LLVM_FALLTHROUGH; @@ -9267,7 +9248,7 @@ llvm::APInt::udivrem(OrigN, TSize, N, Remainder); if (Remainder) { Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) - << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false) + << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/ false) << (unsigned)TSize; return false; } @@ -9281,7 +9262,7 @@ if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) { Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported) << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T - << toString(N, 10, /*Signed*/false); + << toString(N, 10, /*Signed*/ false); return false; } uint64_t NElems = N.getZExtValue(); @@ -9336,14 +9317,14 @@ } static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, - APValue &Result, const InitListExpr *ILE, + APValue &Result, InitListExpr const *ILE, QualType AllocType); static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, - const CXXConstructExpr *CCE, + CXXConstructExpr const *CCE, QualType AllocType); -bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) { +bool PointerExprEvaluator::VisitCXXNewExpr(CXXNewExpr const *E) { if (!Info.getLangOpts().CPlusPlus20) Info.CCEDiag(E, diag::note_constexpr_new); @@ -9389,14 +9370,14 @@ IsNothrow = true; } - const Expr *Init = E->getInitializer(); - const InitListExpr *ResizedArrayILE = nullptr; - const CXXConstructExpr *ResizedArrayCCE = nullptr; + Expr const *Init = E->getInitializer(); + InitListExpr const *ResizedArrayILE = nullptr; + CXXConstructExpr const *ResizedArrayCCE = nullptr; bool ValueInit = false; QualType AllocType = E->getAllocatedType(); - if (Optional ArraySize = E->getArraySize()) { - const Expr *Stripped = *ArraySize; + if (Optional ArraySize = E->getArraySize()) { + Expr const *Stripped = *ArraySize; for (; auto *ICE = dyn_cast(Stripped); Stripped = ICE->getSubExpr()) if (ICE->getCastKind() != CK_NoOp && @@ -9429,7 +9410,7 @@ return ZeroInitialization(E); Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large) - << ArrayBound << (*ArraySize)->getSourceRange(); + << ArrayBound << (*ArraySize)->getSourceRange(); return false; } @@ -9471,8 +9452,7 @@ AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr, ArrayType::Normal, 0); } else { - assert(!AllocType->isArrayType() && - "array allocation with non-array new"); + assert(!AllocType->isArrayType() && "array allocation with non-array new"); } APValue *Val; @@ -9480,7 +9460,7 @@ AccessKinds AK = AK_Construct; struct FindObjectHandler { EvalInfo &Info; - const Expr *E; + Expr const *E; QualType AllocType; const AccessKinds AccessKind; APValue *Value; @@ -9491,8 +9471,8 @@ // FIXME: Reject the cases where [basic.life]p8 would not permit the // old name of the object to be used to name the new object. if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) { - Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) << - SubobjType << AllocType; + Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) + << SubobjType << AllocType; return false; } Value = &Subobj; @@ -9558,39 +9538,39 @@ namespace { class MemberPointerExprEvaluator - : public ExprEvaluatorBase { + : public ExprEvaluatorBase { MemberPtr &Result; - bool Success(const ValueDecl *D) { + bool Success(ValueDecl const *D) { Result = MemberPtr(D); return true; } -public: +public: MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result) - : ExprEvaluatorBaseTy(Info), Result(Result) {} + : ExprEvaluatorBaseTy(Info), Result(Result) {} - bool Success(const APValue &V, const Expr *E) { + bool Success(APValue const &V, Expr const *E) { Result.setFrom(V); return true; } - bool ZeroInitialization(const Expr *E) { - return Success((const ValueDecl*)nullptr); + bool ZeroInitialization(Expr const *E) { + return Success((ValueDecl const *)nullptr); } - bool VisitCastExpr(const CastExpr *E); - bool VisitUnaryAddrOf(const UnaryOperator *E); + bool VisitCastExpr(CastExpr const *E); + bool VisitUnaryAddrOf(UnaryOperator const *E); }; } // end anonymous namespace -static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, +static bool EvaluateMemberPointer(Expr const *E, MemberPtr &Result, EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isMemberPointerType()); return MemberPointerExprEvaluator(Info, Result).Visit(E); } -bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) { +bool MemberPointerExprEvaluator::VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { default: return ExprEvaluatorBaseTy::VisitCastExpr(E); @@ -9611,11 +9591,11 @@ for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin()); PathI != PathE; ++PathI) { assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); - const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); + CXXRecordDecl const *Derived = (*PathI)->getType()->getAsCXXRecordDecl(); if (!Result.castToDerived(Derived)) return Error(E); } - const Type *FinalTy = E->getType()->castAs()->getClass(); + Type const *FinalTy = E->getType()->castAs()->getClass(); if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl())) return Error(E); return true; @@ -9625,9 +9605,10 @@ if (!Visit(E->getSubExpr())) return false; for (CastExpr::path_const_iterator PathI = E->path_begin(), - PathE = E->path_end(); PathI != PathE; ++PathI) { + PathE = E->path_end(); + PathI != PathE; ++PathI) { assert(!(*PathI)->isVirtual() && "memptr cast through vbase"); - const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); + CXXRecordDecl const *Base = (*PathI)->getType()->getAsCXXRecordDecl(); if (!Result.castToBase(Base)) return Error(E); } @@ -9635,7 +9616,7 @@ } } -bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) { +bool MemberPointerExprEvaluator::VisitUnaryAddrOf(UnaryOperator const *E) { // C++11 [expr.unary.op]p3 has very strict rules on how the address of a // member can be formed. return Success(cast(E->getSubExpr())->getDecl()); @@ -9646,39 +9627,38 @@ //===----------------------------------------------------------------------===// namespace { - class RecordExprEvaluator - : public ExprEvaluatorBase { - const LValue &This; - APValue &Result; - public: +class RecordExprEvaluator : public ExprEvaluatorBase { + LValue const &This; + APValue &Result; - RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result) +public: + RecordExprEvaluator(EvalInfo &info, LValue const &This, APValue &Result) : ExprEvaluatorBaseTy(info), This(This), Result(Result) {} - bool Success(const APValue &V, const Expr *E) { - Result = V; - return true; - } - bool ZeroInitialization(const Expr *E) { - return ZeroInitialization(E, E->getType()); - } - bool ZeroInitialization(const Expr *E, QualType T); + bool Success(APValue const &V, Expr const *E) { + Result = V; + return true; + } + bool ZeroInitialization(Expr const *E) { + return ZeroInitialization(E, E->getType()); + } + bool ZeroInitialization(Expr const *E, QualType T); - bool VisitCallExpr(const CallExpr *E) { - return handleCallExpr(E, Result, &This); - } - bool VisitCastExpr(const CastExpr *E); - bool VisitInitListExpr(const InitListExpr *E); - bool VisitCXXConstructExpr(const CXXConstructExpr *E) { - return VisitCXXConstructExpr(E, E->getType()); - } - bool VisitLambdaExpr(const LambdaExpr *E); - bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E); - bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T); - bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E); - bool VisitBinCmp(const BinaryOperator *E); - }; -} + bool VisitCallExpr(CallExpr const *E) { + return handleCallExpr(E, Result, &This); + } + bool VisitCastExpr(CastExpr const *E); + bool VisitInitListExpr(InitListExpr const *E); + bool VisitCXXConstructExpr(CXXConstructExpr const *E) { + return VisitCXXConstructExpr(E, E->getType()); + } + bool VisitLambdaExpr(LambdaExpr const *E); + bool VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr const *E); + bool VisitCXXConstructExpr(CXXConstructExpr const *E, QualType T); + bool VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr const *E); + bool VisitBinCmp(BinaryOperator const *E); +}; +} // namespace /// Perform zero-initialization on an object of non-union class type. /// C++11 [dcl.init]p5: @@ -9687,22 +9667,24 @@ /// -- if T is a (possibly cv-qualified) non-union class type, /// each non-static data member and each base-class subobject is /// zero-initialized -static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, - const RecordDecl *RD, - const LValue &This, APValue &Result) { +static bool HandleClassZeroInitialization(EvalInfo &Info, Expr const *E, + RecordDecl const *RD, + LValue const &This, APValue &Result) { assert(!RD->isUnion() && "Expected non-union class type"); - const CXXRecordDecl *CD = dyn_cast(RD); + CXXRecordDecl const *CD = dyn_cast(RD); Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0, std::distance(RD->field_begin(), RD->field_end())); - if (RD->isInvalidDecl()) return false; - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); + if (RD->isInvalidDecl()) + return false; + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(RD); if (CD) { unsigned Index = 0; for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(), - End = CD->bases_end(); I != End; ++I, ++Index) { - const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl(); + End = CD->bases_end(); + I != End; ++I, ++Index) { + CXXRecordDecl const *Base = I->getType()->getAsCXXRecordDecl(); LValue Subobject = This; if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout)) return false; @@ -9712,7 +9694,7 @@ } } - for (const auto *I : RD->fields()) { + for (auto const *I : RD->fields()) { // -- if T is a reference type, no initialization is performed. if (I->isUnnamedBitfield() || I->getType()->isReferenceType()) continue; @@ -9722,17 +9704,18 @@ return false; ImplicitValueInitExpr VIE(I->getType()); - if (!EvaluateInPlace( - Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE)) + if (!EvaluateInPlace(Result.getStructField(I->getFieldIndex()), Info, + Subobject, &VIE)) return false; } return true; } -bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) { - const RecordDecl *RD = T->castAs()->getDecl(); - if (RD->isInvalidDecl()) return false; +bool RecordExprEvaluator::ZeroInitialization(Expr const *E, QualType T) { + RecordDecl const *RD = T->castAs()->getDecl(); + if (RD->isInvalidDecl()) + return false; if (RD->isUnion()) { // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the // object's first non-static named data member is zero-initialized @@ -9740,7 +9723,7 @@ while (I != RD->field_end() && (*I)->isUnnamedBitfield()) ++I; if (I == RD->field_end()) { - Result = APValue((const FieldDecl*)nullptr); + Result = APValue((FieldDecl const *)nullptr); return true; } @@ -9760,7 +9743,7 @@ return HandleClassZeroInitialization(Info, E, RD, This, Result); } -bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) { +bool RecordExprEvaluator::VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { default: return ExprEvaluatorBaseTy::VisitCastExpr(E); @@ -9778,11 +9761,12 @@ // Derived-to-base rvalue conversion: just slice off the derived part. APValue *Value = &DerivedObject; - const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); + CXXRecordDecl const *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl(); for (CastExpr::path_const_iterator PathI = E->path_begin(), - PathE = E->path_end(); PathI != PathE; ++PathI) { + PathE = E->path_end(); + PathI != PathE; ++PathI) { assert(!(*PathI)->isVirtual() && "record rvalue with virtual base"); - const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl(); + CXXRecordDecl const *Base = (*PathI)->getType()->getAsCXXRecordDecl(); Value = &Value->getStructBase(getBaseIndex(RD, Base)); RD = Base; } @@ -9792,13 +9776,14 @@ } } -bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) { +bool RecordExprEvaluator::VisitInitListExpr(InitListExpr const *E) { if (E->isTransparent()) return Visit(E->getInit(0)); - const RecordDecl *RD = E->getType()->castAs()->getDecl(); - if (RD->isInvalidDecl()) return false; - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD); + RecordDecl const *RD = E->getType()->castAs()->getDecl(); + if (RD->isInvalidDecl()) + return false; + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(RD); auto *CXXRD = dyn_cast(RD); EvalInfo::EvaluatingConstructorRAII EvalObj( @@ -9807,7 +9792,7 @@ CXXRD && CXXRD->getNumBases()); if (RD->isUnion()) { - const FieldDecl *Field = E->getInitializedFieldInUnion(); + FieldDecl const *Field = E->getInitializedFieldInUnion(); Result = APValue(Field); if (!Field) return true; @@ -9818,7 +9803,7 @@ // Is this difference ever observable for initializer lists which // we don't build? ImplicitValueInitExpr VIE(Field->getType()); - const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; + Expr const *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE; LValue Subobject = This; if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout)) @@ -9846,9 +9831,9 @@ // Initialize base classes. if (CXXRD && CXXRD->getNumBases()) { - for (const auto &Base : CXXRD->bases()) { + for (auto const &Base : CXXRD->bases()) { assert(ElementNo < E->getNumInits() && "missing init for base class"); - const Expr *Init = E->getInit(ElementNo); + Expr const *Init = E->getInit(ElementNo); LValue Subobject = This; if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base)) @@ -9867,7 +9852,7 @@ } // Initialize members. - for (const auto *Field : RD->fields()) { + for (auto const *Field : RD->fields()) { // Anonymous bit-fields are not considered members of the class for // purposes of aggregate initialization. if (Field->isUnnamedBitfield()) @@ -9886,7 +9871,7 @@ // Perform an implicit value-initialization for members beyond the end of // the initializer list. ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType()); - const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; + Expr const *Init = HaveInit ? E->getInit(ElementNo++) : &VIE; // Temporarily override This, in case there's a CXXDefaultInitExpr in here. ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This, @@ -9894,8 +9879,8 @@ APValue &FieldVal = Result.getStructField(Field->getFieldIndex()); if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) || - (Field->isBitField() && !truncateBitfieldValue(Info, Init, - FieldVal, Field))) { + (Field->isBitField() && + !truncateBitfieldValue(Info, Init, FieldVal, Field))) { if (!Info.noteFailure()) return false; Success = false; @@ -9907,12 +9892,13 @@ return Success; } -bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, +bool RecordExprEvaluator::VisitCXXConstructExpr(CXXConstructExpr const *E, QualType T) { // Note that E's type is not necessarily the type of our class here; we might // be initializing an array element instead. - const CXXConstructorDecl *FD = E->getConstructor(); - if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; + CXXConstructorDecl const *FD = E->getConstructor(); + if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) + return false; bool ZeroInit = E->requiresZeroInitialization(); if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) { @@ -9926,7 +9912,7 @@ return getDefaultInitValue(T, Result); } - const FunctionDecl *Definition = nullptr; + FunctionDecl const *Definition = nullptr; auto Body = FD->getBody(Definition); if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) @@ -9934,31 +9920,30 @@ // Avoid materializing a temporary for an elidable copy/move constructor. if (E->isElidable() && !ZeroInit) - if (const MaterializeTemporaryExpr *ME - = dyn_cast(E->getArg(0))) + if (MaterializeTemporaryExpr const *ME = + dyn_cast(E->getArg(0))) return Visit(ME->getSubExpr()); if (ZeroInit && !ZeroInitialization(E, T)) return false; auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs()); - return HandleConstructorCall(E, This, Args, - cast(Definition), Info, - Result); + return HandleConstructorCall( + E, This, Args, cast(Definition), Info, Result); } bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr( - const CXXInheritedCtorInitExpr *E) { + CXXInheritedCtorInitExpr const *E) { if (!Info.CurrentCall) { assert(Info.checkingPotentialConstantExpression()); return false; } - const CXXConstructorDecl *FD = E->getConstructor(); + CXXConstructorDecl const *FD = E->getConstructor(); if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false; - const FunctionDecl *Definition = nullptr; + FunctionDecl const *Definition = nullptr; auto Body = FD->getBody(Definition); if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body)) @@ -9970,8 +9955,8 @@ } bool RecordExprEvaluator::VisitCXXStdInitializerListExpr( - const CXXStdInitializerListExpr *E) { - const ConstantArrayType *ArrayType = + CXXStdInitializerListExpr const *E) { + ConstantArrayType const *ArrayType = Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType()); LValue Array; @@ -9982,8 +9967,7 @@ Array.addArray(Info, E, ArrayType); auto InvalidType = [&] { - Info.FFDiag(E, diag::note_constexpr_unsupported_layout) - << E->getType(); + Info.FFDiag(E, diag::note_constexpr_unsupported_layout) << E->getType(); return false; }; @@ -10027,8 +10011,8 @@ return true; } -bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) { - const CXXRecordDecl *ClosureClass = E->getLambdaClass(); +bool RecordExprEvaluator::VisitLambdaExpr(LambdaExpr const *E) { + CXXRecordDecl const *ClosureClass = E->getLambdaClass(); if (ClosureClass->isInvalidDecl()) return false; @@ -10040,14 +10024,14 @@ "The number of lambda capture initializers should equal the number of " "fields within the closure type"); - Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields); + Result = APValue(APValue::UninitStruct(), /*NumBases*/ 0, NumFields); // Iterate through all the lambda's closure object's fields and initialize // them. auto *CaptureInitIt = E->capture_init_begin(); - const LambdaCapture *CaptureIt = ClosureClass->captures_begin(); + LambdaCapture const *CaptureIt = ClosureClass->captures_begin(); bool Success = true; - const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); - for (const auto *Field : ClosureClass->fields()) { + ASTRecordLayout const &Layout = Info.Ctx.getASTRecordLayout(ClosureClass); + for (auto const *Field : ClosureClass->fields()) { assert(CaptureInitIt != E->capture_init_end()); // Get the initializer for this field Expr *const CurFieldInit = *CaptureInitIt++; @@ -10073,8 +10057,8 @@ return Success; } -static bool EvaluateRecord(const Expr *E, const LValue &This, - APValue &Result, EvalInfo &Info) { +static bool EvaluateRecord(Expr const *E, LValue const &This, APValue &Result, + EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isRecordType() && "can't evaluate expression as a record rvalue"); @@ -10090,19 +10074,19 @@ //===----------------------------------------------------------------------===// namespace { class TemporaryExprEvaluator - : public LValueExprEvaluatorBase { + : public LValueExprEvaluatorBase { public: - TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) : - LValueExprEvaluatorBaseTy(Info, Result, false) {} + TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) + : LValueExprEvaluatorBaseTy(Info, Result, false) {} /// Visit an expression which constructs the value of this temporary. - bool VisitConstructExpr(const Expr *E) { + bool VisitConstructExpr(Expr const *E) { APValue &Value = Info.CurrentCall->createTemporary( E, E->getType(), ScopeKind::FullExpression, Result); return EvaluateInPlace(Value, Info, Result, E); } - bool VisitCastExpr(const CastExpr *E) { + bool VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { default: return LValueExprEvaluatorBaseTy::VisitCastExpr(E); @@ -10111,26 +10095,22 @@ return VisitConstructExpr(E->getSubExpr()); } } - bool VisitInitListExpr(const InitListExpr *E) { + bool VisitInitListExpr(InitListExpr const *E) { return VisitConstructExpr(E); } - bool VisitCXXConstructExpr(const CXXConstructExpr *E) { + bool VisitCXXConstructExpr(CXXConstructExpr const *E) { return VisitConstructExpr(E); } - bool VisitCallExpr(const CallExpr *E) { - return VisitConstructExpr(E); - } - bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) { - return VisitConstructExpr(E); - } - bool VisitLambdaExpr(const LambdaExpr *E) { + bool VisitCallExpr(CallExpr const *E) { return VisitConstructExpr(E); } + bool VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr const *E) { return VisitConstructExpr(E); } + bool VisitLambdaExpr(LambdaExpr const *E) { return VisitConstructExpr(E); } }; } // end anonymous namespace /// Evaluate an expression of record type as a temporary. -static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) { +static bool EvaluateTemporary(Expr const *E, LValue &Result, EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isRecordType()); return TemporaryExprEvaluator(Info, Result).Visit(E); @@ -10141,49 +10121,47 @@ //===----------------------------------------------------------------------===// namespace { - class VectorExprEvaluator - : public ExprEvaluatorBase { - APValue &Result; - public: +class VectorExprEvaluator : public ExprEvaluatorBase { + APValue &Result; - VectorExprEvaluator(EvalInfo &info, APValue &Result) +public: + VectorExprEvaluator(EvalInfo &info, APValue &Result) : ExprEvaluatorBaseTy(info), Result(Result) {} - bool Success(ArrayRef V, const Expr *E) { - assert(V.size() == E->getType()->castAs()->getNumElements()); - // FIXME: remove this APValue copy. - Result = APValue(V.data(), V.size()); - return true; - } - bool Success(const APValue &V, const Expr *E) { - assert(V.isVector()); - Result = V; - return true; - } - bool ZeroInitialization(const Expr *E); + bool Success(ArrayRef V, Expr const *E) { + assert(V.size() == E->getType()->castAs()->getNumElements()); + // FIXME: remove this APValue copy. + Result = APValue(V.data(), V.size()); + return true; + } + bool Success(APValue const &V, Expr const *E) { + assert(V.isVector()); + Result = V; + return true; + } + bool ZeroInitialization(Expr const *E); - bool VisitUnaryReal(const UnaryOperator *E) - { return Visit(E->getSubExpr()); } - bool VisitCastExpr(const CastExpr* E); - bool VisitInitListExpr(const InitListExpr *E); - bool VisitUnaryImag(const UnaryOperator *E); - bool VisitBinaryOperator(const BinaryOperator *E); - // FIXME: Missing: unary -, unary ~, conditional operator (for GNU - // conditional select), shufflevector, ExtVectorElementExpr - }; + bool VisitUnaryReal(UnaryOperator const *E) { return Visit(E->getSubExpr()); } + bool VisitCastExpr(CastExpr const *E); + bool VisitInitListExpr(InitListExpr const *E); + bool VisitUnaryImag(UnaryOperator const *E); + bool VisitBinaryOperator(BinaryOperator const *E); + // FIXME: Missing: unary -, unary ~, conditional operator (for GNU + // conditional select), shufflevector, ExtVectorElementExpr +}; } // end anonymous namespace -static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) { +static bool EvaluateVector(Expr const *E, APValue &Result, EvalInfo &Info) { assert(E->isPRValue() && E->getType()->isVectorType() && "not a vector prvalue"); return VectorExprEvaluator(Info, Result).Visit(E); } -bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) { - const VectorType *VTy = E->getType()->castAs(); +bool VectorExprEvaluator::VisitCastExpr(CastExpr const *E) { + VectorType const *VTy = E->getType()->castAs(); unsigned NElts = VTy->getNumElements(); - const Expr *SE = E->getSubExpr(); + Expr const *SE = E->getSubExpr(); QualType SETy = SE->getType(); switch (E->getCastKind()) { @@ -10218,25 +10196,25 @@ bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian(); SmallVector Elts; if (EltTy->isRealFloatingType()) { - const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); + llvm::fltSemantics const &Sem = Info.Ctx.getFloatTypeSemantics(EltTy); unsigned FloatEltSize = EltSize; if (&Sem == &APFloat::x87DoubleExtended()) FloatEltSize = 80; for (unsigned i = 0; i < NElts; i++) { llvm::APInt Elt; if (BigEndian) - Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize); + Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize); else - Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize); + Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize); Elts.push_back(APValue(APFloat(Sem, Elt))); } } else if (EltTy->isIntegerType()) { for (unsigned i = 0; i < NElts; i++) { llvm::APInt Elt; if (BigEndian) - Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize); + Elt = SValInt.rotl(i * EltSize + EltSize).zextOrTrunc(EltSize); else - Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize); + Elt = SValInt.rotr(i * EltSize).zextOrTrunc(EltSize); Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType()))); } } else { @@ -10249,9 +10227,8 @@ } } -bool -VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) { - const VectorType *VT = E->getType()->castAs(); +bool VectorExprEvaluator::VisitInitListExpr(InitListExpr const *E) { + VectorType const *VT = E->getType()->castAs(); unsigned NumInits = E->getNumInits(); unsigned NumElements = VT->getNumElements(); @@ -10265,8 +10242,8 @@ unsigned CountInits = 0, CountElts = 0; while (CountElts < NumElements) { // Handle nested vector initialization. - if (CountInits < NumInits - && E->getInit(CountInits)->getType()->isVectorType()) { + if (CountInits < NumInits && + E->getInit(CountInits)->getType()->isVectorType()) { APValue v; if (!EvaluateVector(E->getInit(CountInits), v, Info)) return Error(E); @@ -10298,9 +10275,8 @@ return Success(Elements, E); } -bool -VectorExprEvaluator::ZeroInitialization(const Expr *E) { - const auto *VT = E->getType()->castAs(); +bool VectorExprEvaluator::ZeroInitialization(Expr const *E) { + auto const *VT = E->getType()->castAs(); QualType EltTy = VT->getElementType(); APValue ZeroElement; if (EltTy->isIntegerType()) @@ -10313,12 +10289,12 @@ return Success(Elements, E); } -bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { +bool VectorExprEvaluator::VisitUnaryImag(UnaryOperator const *E) { VisitIgnoredValue(E->getSubExpr()); return ZeroInitialization(E); } -bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { +bool VectorExprEvaluator::VisitBinaryOperator(BinaryOperator const *E) { BinaryOperatorKind Op = E->getOpcode(); assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp && "Operation not supported on vector types"); @@ -10358,68 +10334,65 @@ //===----------------------------------------------------------------------===// namespace { - class ArrayExprEvaluator - : public ExprEvaluatorBase { - const LValue &This; - APValue &Result; - public: +class ArrayExprEvaluator : public ExprEvaluatorBase { + LValue const &This; + APValue &Result; - ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result) +public: + ArrayExprEvaluator(EvalInfo &Info, LValue const &This, APValue &Result) : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} - bool Success(const APValue &V, const Expr *E) { - assert(V.isArray() && "expected array"); - Result = V; - return true; - } - - bool ZeroInitialization(const Expr *E) { - const ConstantArrayType *CAT = - Info.Ctx.getAsConstantArrayType(E->getType()); - if (!CAT) { - if (E->getType()->isIncompleteArrayType()) { - // We can be asked to zero-initialize a flexible array member; this - // is represented as an ImplicitValueInitExpr of incomplete array - // type. In this case, the array has zero elements. - Result = APValue(APValue::UninitArray(), 0, 0); - return true; - } - // FIXME: We could handle VLAs here. - return Error(E); - } + bool Success(APValue const &V, Expr const *E) { + assert(V.isArray() && "expected array"); + Result = V; + return true; + } - Result = APValue(APValue::UninitArray(), 0, - CAT->getSize().getZExtValue()); - if (!Result.hasArrayFiller()) + bool ZeroInitialization(Expr const *E) { + ConstantArrayType const *CAT = + Info.Ctx.getAsConstantArrayType(E->getType()); + if (!CAT) { + if (E->getType()->isIncompleteArrayType()) { + // We can be asked to zero-initialize a flexible array member; this + // is represented as an ImplicitValueInitExpr of incomplete array + // type. In this case, the array has zero elements. + Result = APValue(APValue::UninitArray(), 0, 0); return true; + } + // FIXME: We could handle VLAs here. + return Error(E); + } - // Zero-initialize all elements. - LValue Subobject = This; - Subobject.addArray(Info, E, CAT); - ImplicitValueInitExpr VIE(CAT->getElementType()); - return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); - } - - bool VisitCallExpr(const CallExpr *E) { - return handleCallExpr(E, Result, &This); - } - bool VisitInitListExpr(const InitListExpr *E, - QualType AllocType = QualType()); - bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E); - bool VisitCXXConstructExpr(const CXXConstructExpr *E); - bool VisitCXXConstructExpr(const CXXConstructExpr *E, - const LValue &Subobject, - APValue *Value, QualType Type); - bool VisitStringLiteral(const StringLiteral *E, - QualType AllocType = QualType()) { - expandStringLiteral(Info, E, Result, AllocType); + Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue()); + if (!Result.hasArrayFiller()) return true; - } - }; + + // Zero-initialize all elements. + LValue Subobject = This; + Subobject.addArray(Info, E, CAT); + ImplicitValueInitExpr VIE(CAT->getElementType()); + return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE); + } + + bool VisitCallExpr(CallExpr const *E) { + return handleCallExpr(E, Result, &This); + } + bool VisitInitListExpr(InitListExpr const *E, + QualType AllocType = QualType()); + bool VisitArrayInitLoopExpr(ArrayInitLoopExpr const *E); + bool VisitCXXConstructExpr(CXXConstructExpr const *E); + bool VisitCXXConstructExpr(CXXConstructExpr const *E, LValue const &Subobject, + APValue *Value, QualType Type); + bool VisitStringLiteral(StringLiteral const *E, + QualType AllocType = QualType()) { + expandStringLiteral(Info, E, Result, AllocType); + return true; + } +}; } // end anonymous namespace -static bool EvaluateArray(const Expr *E, const LValue &This, - APValue &Result, EvalInfo &Info) { +static bool EvaluateArray(Expr const *E, LValue const &This, APValue &Result, + EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isArrayType() && "not an array prvalue"); @@ -10427,7 +10400,7 @@ } static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, - APValue &Result, const InitListExpr *ILE, + APValue &Result, InitListExpr const *ILE, QualType AllocType) { assert(!ILE->isValueDependent()); assert(ILE->isPRValue() && ILE->getType()->isArrayType() && @@ -10438,7 +10411,7 @@ static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, - const CXXConstructExpr *CCE, + CXXConstructExpr const *CCE, QualType AllocType) { assert(!CCE->isValueDependent()); assert(CCE->isPRValue() && CCE->getType()->isArrayType() && @@ -10448,12 +10421,12 @@ } // Return true iff the given array filler may depend on the element index. -static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) { +static bool MaybeElementDependentArrayFiller(Expr const *FillerExpr) { // For now, just allow non-class value-initialization and initialization // lists comprised of them. if (isa(FillerExpr)) return false; - if (const InitListExpr *ILE = dyn_cast(FillerExpr)) { + if (InitListExpr const *ILE = dyn_cast(FillerExpr)) { for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) { if (MaybeElementDependentArrayFiller(ILE->getInit(I))) return true; @@ -10463,9 +10436,9 @@ return true; } -bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E, +bool ArrayExprEvaluator::VisitInitListExpr(InitListExpr const *E, QualType AllocType) { - const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType( + ConstantArrayType const *CAT = Info.Ctx.getAsConstantArrayType( AllocType.isNull() ? E->getType() : AllocType); if (!CAT) return Error(E); @@ -10495,7 +10468,7 @@ unsigned NumEltsToInit = E->getNumInits(); unsigned NumElts = CAT->getSize().getZExtValue(); - const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; + Expr const *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr; // If the initializer might depend on the array index, run it for each // array element. @@ -10519,10 +10492,10 @@ LValue Subobject = This; Subobject.addArray(Info, E, CAT); for (unsigned Index = 0; Index != NumEltsToInit; ++Index) { - const Expr *Init = + Expr const *Init = Index < E->getNumInits() ? E->getInit(Index) : FillerExpr; - if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), - Info, Subobject, Init) || + if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), Info, Subobject, + Init) || !HandleLValueArrayAdjustment(Info, Init, Subobject, CAT->getElementType(), 1)) { if (!Info.noteFailure()) @@ -10538,10 +10511,11 @@ // once and splat over the rest of the array elements. assert(FillerExpr && "no array filler for incomplete init list"); return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, - FillerExpr) && Success; + FillerExpr) && + Success; } -bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { +bool ArrayExprEvaluator::VisitArrayInitLoopExpr(ArrayInitLoopExpr const *E) { LValue CommonLV; if (E->getCommonExpr() && !Evaluate(Info.CurrentCall->createTemporary( @@ -10561,10 +10535,10 @@ bool Success = true; for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) { - if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), - Info, Subobject, E->getSubExpr()) || - !HandleLValueArrayAdjustment(Info, E, Subobject, - CAT->getElementType(), 1)) { + if (!EvaluateInPlace(Result.getArrayInitializedElt(Index), Info, Subobject, + E->getSubExpr()) || + !HandleLValueArrayAdjustment(Info, E, Subobject, CAT->getElementType(), + 1)) { if (!Info.noteFailure()) return false; Success = false; @@ -10574,23 +10548,22 @@ return Success; } -bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) { +bool ArrayExprEvaluator::VisitCXXConstructExpr(CXXConstructExpr const *E) { return VisitCXXConstructExpr(E, This, &Result, E->getType()); } -bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E, - const LValue &Subobject, - APValue *Value, - QualType Type) { +bool ArrayExprEvaluator::VisitCXXConstructExpr(CXXConstructExpr const *E, + LValue const &Subobject, + APValue *Value, QualType Type) { bool HadZeroInit = Value->hasValue(); - if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) { + if (ConstantArrayType const *CAT = Info.Ctx.getAsConstantArrayType(Type)) { unsigned N = CAT->getSize().getZExtValue(); // Preserve the array filler if we had prior zero-initialization. - APValue Filler = - HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller() - : APValue(); + APValue Filler = HadZeroInit && Value->hasArrayFiller() + ? Value->getArrayFiller() + : APValue(); *Value = APValue(APValue::UninitArray(), N, N); @@ -10604,8 +10577,8 @@ for (unsigned I = 0; I != N; ++I) if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I), CAT->getElementType()) || - !HandleLValueArrayAdjustment(Info, E, ArrayElt, - CAT->getElementType(), 1)) + !HandleLValueArrayAdjustment(Info, E, ArrayElt, CAT->getElementType(), + 1)) return false; return true; @@ -10615,7 +10588,7 @@ return Error(E); return RecordExprEvaluator(Info, Subobject, *Value) - .VisitCXXConstructExpr(E, Type); + .VisitCXXConstructExpr(E, Type); } //===----------------------------------------------------------------------===// @@ -10627,14 +10600,14 @@ //===----------------------------------------------------------------------===// namespace { -class IntExprEvaluator - : public ExprEvaluatorBase { +class IntExprEvaluator : public ExprEvaluatorBase { APValue &Result; + public: IntExprEvaluator(EvalInfo &info, APValue &result) : ExprEvaluatorBaseTy(info), Result(result) {} - bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) { + bool Success(llvm::APSInt const &SI, Expr const *E, APValue &Result) { assert(E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result."); assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() && @@ -10644,39 +10617,39 @@ Result = APValue(SI); return true; } - bool Success(const llvm::APSInt &SI, const Expr *E) { + bool Success(llvm::APSInt const &SI, Expr const *E) { return Success(SI, E, Result); } - bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) { + bool Success(llvm::APInt const &I, Expr const *E, APValue &Result) { assert(E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result."); assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result."); Result = APValue(APSInt(I)); Result.getInt().setIsUnsigned( - E->getType()->isUnsignedIntegerOrEnumerationType()); + E->getType()->isUnsignedIntegerOrEnumerationType()); return true; } - bool Success(const llvm::APInt &I, const Expr *E) { + bool Success(llvm::APInt const &I, Expr const *E) { return Success(I, E, Result); } - bool Success(uint64_t Value, const Expr *E, APValue &Result) { + bool Success(uint64_t Value, Expr const *E, APValue &Result) { assert(E->getType()->isIntegralOrEnumerationType() && "Invalid evaluation result."); Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType())); return true; } - bool Success(uint64_t Value, const Expr *E) { + bool Success(uint64_t Value, Expr const *E) { return Success(Value, E, Result); } - bool Success(CharUnits Size, const Expr *E) { + bool Success(CharUnits Size, Expr const *E) { return Success(Size.getQuantity(), E); } - bool Success(const APValue &V, const Expr *E) { + bool Success(APValue const &V, Expr const *E) { if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) { Result = V; return true; @@ -10684,27 +10657,27 @@ return Success(V.getInt(), E); } - bool ZeroInitialization(const Expr *E) { return Success(0, E); } + bool ZeroInitialization(Expr const *E) { return Success(0, E); } //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// - bool VisitIntegerLiteral(const IntegerLiteral *E) { + bool VisitIntegerLiteral(IntegerLiteral const *E) { return Success(E->getValue(), E); } - bool VisitCharacterLiteral(const CharacterLiteral *E) { + bool VisitCharacterLiteral(CharacterLiteral const *E) { return Success(E->getValue(), E); } - bool CheckReferencedDecl(const Expr *E, const Decl *D); - bool VisitDeclRefExpr(const DeclRefExpr *E) { + bool CheckReferencedDecl(Expr const *E, Decl const *D); + bool VisitDeclRefExpr(DeclRefExpr const *E) { if (CheckReferencedDecl(E, E->getDecl())) return true; return ExprEvaluatorBaseTy::VisitDeclRefExpr(E); } - bool VisitMemberExpr(const MemberExpr *E) { + bool VisitMemberExpr(MemberExpr const *E) { if (CheckReferencedDecl(E, E->getMemberDecl())) { VisitIgnoredBaseExpression(E->getBase()); return true; @@ -10713,24 +10686,24 @@ return ExprEvaluatorBaseTy::VisitMemberExpr(E); } - bool VisitCallExpr(const CallExpr *E); - bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp); - bool VisitBinaryOperator(const BinaryOperator *E); - bool VisitOffsetOfExpr(const OffsetOfExpr *E); - bool VisitUnaryOperator(const UnaryOperator *E); + bool VisitCallExpr(CallExpr const *E); + bool VisitBuiltinCallExpr(CallExpr const *E, unsigned BuiltinOp); + bool VisitBinaryOperator(BinaryOperator const *E); + bool VisitOffsetOfExpr(OffsetOfExpr const *E); + bool VisitUnaryOperator(UnaryOperator const *E); - bool VisitCastExpr(const CastExpr* E); - bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E); + bool VisitCastExpr(CastExpr const *E); + bool VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr const *E); - bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { + bool VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr const *E) { return Success(E->getValue(), E); } - bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { + bool VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr const *E) { return Success(E->getValue(), E); } - bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { + bool VisitArrayInitIndexExpr(ArrayInitIndexExpr const *E) { if (Info.ArrayInitIndex == uint64_t(-1)) { // We were asked to evaluate this subexpression independent of the // enclosing ArrayInitLoopExpr. We can't do that. @@ -10741,30 +10714,28 @@ } // Note, GNU defines __null as an integer, not a pointer. - bool VisitGNUNullExpr(const GNUNullExpr *E) { - return ZeroInitialization(E); - } + bool VisitGNUNullExpr(GNUNullExpr const *E) { return ZeroInitialization(E); } - bool VisitTypeTraitExpr(const TypeTraitExpr *E) { + bool VisitTypeTraitExpr(TypeTraitExpr const *E) { return Success(E->getValue(), E); } - bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { + bool VisitArrayTypeTraitExpr(ArrayTypeTraitExpr const *E) { return Success(E->getValue(), E); } - bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { + bool VisitExpressionTraitExpr(ExpressionTraitExpr const *E) { return Success(E->getValue(), E); } - bool VisitUnaryReal(const UnaryOperator *E); - bool VisitUnaryImag(const UnaryOperator *E); + bool VisitUnaryReal(UnaryOperator const *E); + bool VisitUnaryImag(UnaryOperator const *E); - bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E); - bool VisitSizeOfPackExpr(const SizeOfPackExpr *E); - bool VisitSourceLocExpr(const SourceLocExpr *E); - bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E); - bool VisitRequiresExpr(const RequiresExpr *E); + bool VisitCXXNoexceptExpr(CXXNoexceptExpr const *E); + bool VisitSizeOfPackExpr(SizeOfPackExpr const *E); + bool VisitSourceLocExpr(SourceLocExpr const *E); + bool VisitConceptSpecializationExpr(ConceptSpecializationExpr const *E); + bool VisitRequiresExpr(RequiresExpr const *E); // FIXME: Missing: array subscript of vector, member of vector }; @@ -10772,25 +10743,25 @@ : public ExprEvaluatorBase { APValue &Result; - public: +public: FixedPointExprEvaluator(EvalInfo &info, APValue &result) : ExprEvaluatorBaseTy(info), Result(result) {} - bool Success(const llvm::APInt &I, const Expr *E) { + bool Success(llvm::APInt const &I, Expr const *E) { return Success( APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E); } - bool Success(uint64_t Value, const Expr *E) { + bool Success(uint64_t Value, Expr const *E) { return Success( APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E); } - bool Success(const APValue &V, const Expr *E) { + bool Success(APValue const &V, Expr const *E) { return Success(V.getFixedPoint(), E); } - bool Success(const APFixedPoint &V, const Expr *E) { + bool Success(APFixedPoint const &V, Expr const *E) { assert(E->getType()->isFixedPointType() && "Invalid evaluation result."); assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result."); @@ -10802,13 +10773,13 @@ // Visitor Methods //===--------------------------------------------------------------------===// - bool VisitFixedPointLiteral(const FixedPointLiteral *E) { + bool VisitFixedPointLiteral(FixedPointLiteral const *E) { return Success(E->getValue(), E); } - bool VisitCastExpr(const CastExpr *E); - bool VisitUnaryOperator(const UnaryOperator *E); - bool VisitBinaryOperator(const BinaryOperator *E); + bool VisitCastExpr(CastExpr const *E); + bool VisitUnaryOperator(UnaryOperator const *E); + bool VisitBinaryOperator(BinaryOperator const *E); }; } // end anonymous namespace @@ -10820,14 +10791,14 @@ /// an integer rvalue to produce a pointer (represented as an lvalue) instead. /// Some simple arithmetic on such values is supported (they are treated much /// like char*). -static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, +static bool EvaluateIntegerOrLValue(Expr const *E, APValue &Result, EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType()); return IntExprEvaluator(Info, Result).Visit(E); } -static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) { +static bool EvaluateInteger(Expr const *E, APSInt &Result, EvalInfo &Info) { assert(!E->isValueDependent()); APValue Val; if (!EvaluateIntegerOrLValue(E, Val, Info)) @@ -10842,13 +10813,13 @@ return true; } -bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) { +bool IntExprEvaluator::VisitSourceLocExpr(SourceLocExpr const *E) { APValue Evaluated = E->EvaluateInContext( Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr()); return Success(Evaluated, E); } -static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, +static bool EvaluateFixedPoint(Expr const *E, APFixedPoint &Result, EvalInfo &Info) { assert(!E->isValueDependent()); if (E->getType()->isFixedPointType()) { @@ -10864,7 +10835,7 @@ return false; } -static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, +static bool EvaluateFixedPointOrInteger(Expr const *E, APFixedPoint &Result, EvalInfo &Info) { assert(!E->isValueDependent()); if (E->getType()->isIntegerType()) { @@ -10883,14 +10854,14 @@ /// Check whether the given declaration can be directly converted to an integral /// rvalue. If not, no diagnostic is produced; there are other things we can /// try. -bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) { +bool IntExprEvaluator::CheckReferencedDecl(Expr const *E, Decl const *D) { // Enums are integer constant exprs. - if (const EnumConstantDecl *ECD = dyn_cast(D)) { + if (EnumConstantDecl const *ECD = dyn_cast(D)) { // Check for signedness/width mismatches between E type and ECD value. - bool SameSign = (ECD->getInitVal().isSigned() - == E->getType()->isSignedIntegerOrEnumerationType()); - bool SameWidth = (ECD->getInitVal().getBitWidth() - == Info.Ctx.getIntWidth(E->getType())); + bool SameSign = (ECD->getInitVal().isSigned() == + E->getType()->isSignedIntegerOrEnumerationType()); + bool SameWidth = + (ECD->getInitVal().getBitWidth() == Info.Ctx.getIntWidth(E->getType())); if (SameSign && SameWidth) return Success(ECD->getInitVal(), E); else { @@ -10939,12 +10910,12 @@ /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way /// as GCC. -static GCCTypeClass -EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) { +static GCCTypeClass EvaluateBuiltinClassifyType(QualType T, + LangOptions const &LangOpts) { assert(!T->isDependentType() && "unexpected dependent type"); QualType CanTy = T.getCanonicalType(); - const BuiltinType *BT = dyn_cast(CanTy); + BuiltinType const *BT = dyn_cast(CanTy); switch (CanTy->getTypeClass()) { #define TYPE(ID, BASE) @@ -10954,17 +10925,20 @@ #include "clang/AST/TypeNodes.inc" case Type::Auto: case Type::DeducedTemplateSpecialization: - llvm_unreachable("unexpected non-canonical or dependent type"); + llvm_unreachable("unexpected non-canonical or dependent type"); case Type::Builtin: switch (BT->getKind()) { #define BUILTIN_TYPE(ID, SINGLETON_ID) -#define SIGNED_TYPE(ID, SINGLETON_ID) \ - case BuiltinType::ID: return GCCTypeClass::Integer; -#define FLOATING_TYPE(ID, SINGLETON_ID) \ - case BuiltinType::ID: return GCCTypeClass::RealFloat; -#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ - case BuiltinType::ID: break; +#define SIGNED_TYPE(ID, SINGLETON_ID) \ + case BuiltinType::ID: \ + return GCCTypeClass::Integer; +#define FLOATING_TYPE(ID, SINGLETON_ID) \ + case BuiltinType::ID: \ + return GCCTypeClass::RealFloat; +#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \ + case BuiltinType::ID: \ + break; #include "clang/AST/BuiltinTypes.def" case BuiltinType::Void: return GCCTypeClass::Void; @@ -11004,22 +10978,19 @@ case BuiltinType::ObjCId: case BuiltinType::ObjCClass: case BuiltinType::ObjCSel: -#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ - case BuiltinType::Id: +#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ + case BuiltinType::Id: #include "clang/Basic/OpenCLImageTypes.def" -#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ - case BuiltinType::Id: +#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id: #include "clang/Basic/OpenCLExtensionTypes.def" case BuiltinType::OCLSampler: case BuiltinType::OCLEvent: case BuiltinType::OCLClkEvent: case BuiltinType::OCLQueue: case BuiltinType::OCLReserveID: -#define SVE_TYPE(Name, Id, SingletonId) \ - case BuiltinType::Id: +#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id: #include "clang/Basic/AArch64SVEACLETypes.def" -#define PPC_VECTOR_TYPE(Name, Id, Size) \ - case BuiltinType::Id: +#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id: #include "clang/Basic/PPCTypes.def" #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id: #include "clang/Basic/RISCVVTypes.def" @@ -11081,8 +11052,8 @@ /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way /// as GCC. -static GCCTypeClass -EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) { +static GCCTypeClass EvaluateBuiltinClassifyType(CallExpr const *E, + LangOptions const &LangOpts) { // If no argument was supplied, default to None. This isn't // ideal, however it is what gcc does. if (E->getNumArgs() == 0) @@ -11099,12 +11070,12 @@ /// /// A pointer is only "constant" if it is null (or a pointer cast to integer) /// or it points to the first character of a string literal. -static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) { +static bool EvaluateBuiltinConstantPForLValue(APValue const &LV) { APValue::LValueBase Base = LV.getLValueBase(); if (Base.isNull()) { // A null base is acceptable. return true; - } else if (const Expr *E = Base.dyn_cast()) { + } else if (Expr const *E = Base.dyn_cast()) { if (!isa(E)) return false; return LV.getLValueOffset().isZero(); @@ -11120,7 +11091,7 @@ /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to /// GCC as we can manage. -static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) { +static bool EvaluateBuiltinConstantP(EvalInfo &Info, Expr const *Arg) { // This evaluation is not permitted to have side-effects, so evaluate it in // a speculative evaluation context. SpeculativeEvaluationRAII SpeculativeEval(Info); @@ -11170,10 +11141,10 @@ /// Retrieves the "underlying object type" of the given expression, /// as used by __builtin_object_size. static QualType getObjectType(APValue::LValueBase B) { - if (const ValueDecl *D = B.dyn_cast()) { - if (const VarDecl *VD = dyn_cast(D)) + if (ValueDecl const *D = B.dyn_cast()) { + if (VarDecl const *VD = dyn_cast(D)) return VD->getType(); - } else if (const Expr *E = B.dyn_cast()) { + } else if (Expr const *E = B.dyn_cast()) { if (isa(E)) return E->getType(); } else if (B.is()) { @@ -11191,7 +11162,7 @@ /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo` /// /// Always returns an RValue with a pointer representation. -static const Expr *ignorePointerCastsAndParens(const Expr *E) { +static Expr const *ignorePointerCastsAndParens(Expr const *E) { assert(E->isPRValue() && E->getType()->hasPointerRepresentation()); auto *NoParens = E->IgnoreParens(); @@ -11227,10 +11198,10 @@ /// /// If this encounters an invalid RecordDecl or otherwise cannot determine the /// correct result, it will always return true. -static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) { +static bool isDesignatorAtObjectEnd(ASTContext const &Ctx, LValue const &LVal) { assert(!LVal.Designator.Invalid); - auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) { + auto IsLastOrInvalidFieldDecl = [&Ctx](FieldDecl const *FD, bool &Invalid) { const RecordDecl *Parent = FD->getParent(); Invalid = Parent->isInvalidDecl(); if (Invalid || Parent->isUnion()) @@ -11240,7 +11211,7 @@ }; auto &Base = LVal.getLValueBase(); - if (auto *ME = dyn_cast_or_null(Base.dyn_cast())) { + if (auto *ME = dyn_cast_or_null(Base.dyn_cast())) { if (auto *FD = dyn_cast(ME->getMemberDecl())) { bool Invalid; if (!IsLastOrInvalidFieldDecl(FD, Invalid)) @@ -11267,19 +11238,19 @@ } for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) { - const auto &Entry = LVal.Designator.Entries[I]; + auto const &Entry = LVal.Designator.Entries[I]; if (BaseType->isArrayType()) { // Because __builtin_object_size treats arrays as objects, we can ignore // the index iff this is the last array in the Designator. if (I + 1 == E) return true; - const auto *CAT = cast(Ctx.getAsArrayType(BaseType)); + auto const *CAT = cast(Ctx.getAsArrayType(BaseType)); uint64_t Index = Entry.getAsArrayIndex(); if (Index + 1 != CAT->getSize()) return false; BaseType = CAT->getElementType(); } else if (BaseType->isAnyComplexType()) { - const auto *CT = BaseType->castAs(); + auto const *CT = BaseType->castAs(); uint64_t Index = Entry.getAsArrayIndex(); if (Index != 1) return false; @@ -11301,7 +11272,7 @@ /// necessarily valid). Note that this always returns 'true' if the LValue has /// an unsized array as its first designator entry, because there's currently no /// way to tell if the user typed *foo or foo[0]. -static bool refersToCompleteObject(const LValue &LVal) { +static bool refersToCompleteObject(LValue const &LVal) { if (LVal.Designator.Invalid) return false; @@ -11313,14 +11284,14 @@ // If `E` is a MemberExpr, then the first part of the designator is hiding in // the LValueBase. - const auto *E = LVal.Base.dyn_cast(); + auto const *E = LVal.Base.dyn_cast(); return !E || !isa(E); } /// Attempts to detect a user writing into a piece of memory that's impossible /// to figure out the size of by just using types. -static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) { - const SubobjectDesignator &Designator = LVal.Designator; +static bool isUserWritingOffTheEnd(ASTContext const &Ctx, LValue const &LVal) { + SubobjectDesignator const &Designator = LVal.Designator; // Notes: // - Users can only write off of the end when we have an invalid base. Invalid // bases imply we don't know where the memory came from. @@ -11340,7 +11311,7 @@ /// Converts the given APInt to CharUnits, assuming the APInt is unsigned. /// Fails if the conversion would cause loss of precision. -static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, +static bool convertUnsignedAPIntToCharUnits(llvm::APInt const &Int, CharUnits &Result) { auto CharUnitsMax = std::numeric_limits::max(); if (Int.ugt(CharUnitsMax)) @@ -11356,7 +11327,7 @@ /// /// If this returns false, the value of Result is undefined. static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, - unsigned Type, const LValue &LVal, + unsigned Type, LValue const &LVal, CharUnits &EndOffset) { bool DetermineForCompleteObject = refersToCompleteObject(LVal); @@ -11387,7 +11358,7 @@ } // We want to evaluate the size of a subobject. - const SubobjectDesignator &Designator = LVal.Designator; + SubobjectDesignator const &Designator = LVal.Designator; // The following is a moderately common idiom in C: // @@ -11437,7 +11408,7 @@ /// /// If @p WasError is non-null, this will report whether the failure to evaluate /// is to be treated as an Error in IntExprEvaluator. -static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, +static bool tryEvaluateBuiltinObjectSize(Expr const *E, unsigned Type, EvalInfo &Info, uint64_t &Size) { // Determine the denoted object. LValue LVal; @@ -11480,14 +11451,14 @@ return true; } -bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) { +bool IntExprEvaluator::VisitCallExpr(CallExpr const *E) { if (unsigned BuiltinOp = E->getBuiltinCallee()) return VisitBuiltinCallExpr(E, BuiltinOp); return ExprEvaluatorBaseTy::VisitCallExpr(E); } -static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, +static bool getBuiltinAlignArguments(CallExpr const *E, EvalInfo &Info, APValue &Val, APSInt &Alignment) { QualType SrcTy = E->getArg(0)->getType(); if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment)) @@ -11514,7 +11485,7 @@ return true; } -bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E, +bool IntExprEvaluator::VisitBuiltinCallExpr(CallExpr const *E, unsigned BuiltinOp) { switch (BuiltinOp) { default: @@ -11664,7 +11635,7 @@ } case Builtin::BI__builtin_constant_p: { - const Expr *Arg = E->getArg(0); + Expr const *Arg = E->getArg(0); if (EvaluateBuiltinConstantP(Info, Arg)) return Success(true, E); if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) { @@ -11678,7 +11649,7 @@ } case Builtin::BI__builtin_is_constant_evaluated: { - const auto *Callee = Info.CurrentCall->getCallee(); + auto const *Callee = Info.CurrentCall->getCallee(); if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression && (Info.CallStackDepth == 1 || (Info.CallStackDepth == 2 && Callee->isInStdNamespace() && @@ -11736,10 +11707,18 @@ return false; unsigned Arg; switch (Val.getCategory()) { - case APFloat::fcNaN: Arg = 0; break; - case APFloat::fcInfinity: Arg = 1; break; - case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break; - case APFloat::fcZero: Arg = 4; break; + case APFloat::fcNaN: + Arg = 0; + break; + case APFloat::fcInfinity: + Arg = 1; + break; + case APFloat::fcNormal: + Arg = Val.isDenormal() ? 3 : 2; + break; + case APFloat::fcZero: + Arg = 4; + break; } return Visit(E->getArg(Arg)); } @@ -11833,8 +11812,8 @@ // A call to strlen is not a constant expression. if (Info.getLangOpts().CPlusPlus11) Info.CCEDiag(E, diag::note_constexpr_invalid_function) - << /*isConstexpr*/0 << /*isConstructor*/0 - << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); + << /*isConstexpr*/ 0 << /*isConstructor*/ 0 + << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); else Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); LLVM_FALLTHROUGH; @@ -11858,8 +11837,8 @@ // A call to strlen is not a constant expression. if (Info.getLangOpts().CPlusPlus11) Info.CCEDiag(E, diag::note_constexpr_invalid_function) - << /*isConstexpr*/0 << /*isConstructor*/0 - << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); + << /*isConstexpr*/ 0 << /*isConstructor*/ 0 + << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'"); else Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr); LLVM_FALLTHROUGH; @@ -11876,8 +11855,7 @@ return false; uint64_t MaxLength = uint64_t(-1); - if (BuiltinOp != Builtin::BIstrcmp && - BuiltinOp != Builtin::BIwcscmp && + if (BuiltinOp != Builtin::BIstrcmp && BuiltinOp != Builtin::BIwcscmp && BuiltinOp != Builtin::BI__builtin_strcmp && BuiltinOp != Builtin::BI__builtin_wcscmp) { APSInt N; @@ -11919,12 +11897,12 @@ return false; } - const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) { + auto const &ReadCurElems = [&](APValue &Char1, APValue &Char2) { return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) && handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) && Char1.isInt() && Char2.isInt(); }; - const auto &AdvanceElems = [&] { + auto const &AdvanceElems = [&] { return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) && HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1); }; @@ -11993,8 +11971,11 @@ // and _Atomic(T) is appropriately-aligned. return Success(1, E); - QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()-> - castAs()->getPointeeType(); + QualType PointeeType = E->getArg(1) + ->IgnoreImpCasts() + ->getType() + ->castAs() + ->getPointeeType(); if (!PointeeType->isIncompleteType() && Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) { // OK, we will inline operations on this object. @@ -12003,8 +11984,8 @@ } } - return BuiltinOp == Builtin::BI__atomic_always_lock_free ? - Success(0, E) : Error(E); + return BuiltinOp == Builtin::BI__atomic_always_lock_free ? Success(0, E) + : Error(E); } case Builtin::BI__builtin_add_overflow: case Builtin::BI__builtin_sub_overflow: @@ -12046,7 +12027,7 @@ bool IsSigned = LHS.isSigned() || RHS.isSigned() || ResultType->isSignedIntegerOrEnumerationType(); bool AllSigned = LHS.isSigned() && RHS.isSigned() && - ResultType->isSignedIntegerOrEnumerationType(); + ResultType->isSignedIntegerOrEnumerationType(); uint64_t LHSSize = LHS.getBitWidth(); uint64_t RHSSize = RHS.getBitWidth(); uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType); @@ -12128,8 +12109,8 @@ /// Determine whether this is a pointer past the end of the complete /// object referred to by the lvalue. -static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, - const LValue &LV) { +static bool isOnePastTheEndOfCompleteObject(ASTContext const &Ctx, + LValue const &LV) { // A null pointer can be viewed as being "past the end" but we don't // choose to look at it that way here. if (!LV.getLValueBase()) @@ -12165,7 +12146,7 @@ APValue Val; bool Failed; - EvalResult() : Failed(false) { } + EvalResult() : Failed(false) {} void swap(EvalResult &RHS) { Val.swap(RHS.Val); @@ -12175,7 +12156,7 @@ }; struct Job { - const Expr *E; + Expr const *E; EvalResult LHSResult; // meaningful only for binary operator expression. enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind; @@ -12198,57 +12179,54 @@ public: DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result) - : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { } + : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) {} /// True if \param E is a binary operator that we are going to handle /// data recursively. /// We handle binary operators that are comma, logical, or that have operands /// with integral or enumeration type. - static bool shouldEnqueue(const BinaryOperator *E) { + static bool shouldEnqueue(BinaryOperator const *E) { return E->getOpcode() == BO_Comma || E->isLogicalOp() || (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() && E->getLHS()->getType()->isIntegralOrEnumerationType() && E->getRHS()->getType()->isIntegralOrEnumerationType()); } - bool Traverse(const BinaryOperator *E) { + bool Traverse(BinaryOperator const *E) { enqueue(E); EvalResult PrevResult; while (!Queue.empty()) process(PrevResult); - if (PrevResult.Failed) return false; + if (PrevResult.Failed) + return false; FinalResult.swap(PrevResult.Val); return true; } private: - bool Success(uint64_t Value, const Expr *E, APValue &Result) { + bool Success(uint64_t Value, Expr const *E, APValue &Result) { return IntEval.Success(Value, E, Result); } - bool Success(const APSInt &Value, const Expr *E, APValue &Result) { + bool Success(APSInt const &Value, Expr const *E, APValue &Result) { return IntEval.Success(Value, E, Result); } - bool Error(const Expr *E) { - return IntEval.Error(E); - } - bool Error(const Expr *E, diag::kind D) { - return IntEval.Error(E, D); - } + bool Error(Expr const *E) { return IntEval.Error(E); } + bool Error(Expr const *E, diag::kind D) { return IntEval.Error(E, D); } - OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) { + OptionalDiagnostic CCEDiag(Expr const *E, diag::kind D) { return Info.CCEDiag(E, D); } // Returns true if visiting the RHS is necessary, false otherwise. - bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, + bool VisitBinOpLHSOnly(EvalResult &LHSResult, BinaryOperator const *E, bool &SuppressRHSDiags); - bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, - const BinaryOperator *E, APValue &Result); + bool VisitBinOp(EvalResult const &LHSResult, EvalResult const &RHSResult, + BinaryOperator const *E, APValue &Result); - void EvaluateExpr(const Expr *E, EvalResult &Result) { + void EvaluateExpr(Expr const *E, EvalResult &Result) { Result.Failed = !Evaluate(Result.Val, Info, E); if (Result.Failed) Result.Val = APValue(); @@ -12256,19 +12234,19 @@ void process(EvalResult &Result); - void enqueue(const Expr *E) { + void enqueue(Expr const *E) { E = E->IgnoreParens(); - Queue.resize(Queue.size()+1); + Queue.resize(Queue.size() + 1); Queue.back().E = E; Queue.back().Kind = Job::AnyExprKind; } }; -} +} // namespace -bool DataRecursiveIntBinOpEvaluator:: - VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E, - bool &SuppressRHSDiags) { +bool DataRecursiveIntBinOpEvaluator::VisitBinOpLHSOnly(EvalResult &LHSResult, + BinaryOperator const *E, + bool &SuppressRHSDiags) { if (E->getOpcode() == BO_Comma) { // Ignore LHS but note if we could not evaluate it. if (LHSResult.Failed) @@ -12311,7 +12289,7 @@ return true; } -static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, +static void addOrSubLValueAsInteger(APValue &LVal, APSInt const &Index, bool IsSub) { // Compute the new offset in the appropriate width, wrapping at 64 bits. // FIXME: When compiling for a 32-bit target, we should use 32-bit @@ -12320,13 +12298,14 @@ CharUnits &Offset = LVal.getLValueOffset(); uint64_t Offset64 = Offset.getQuantity(); uint64_t Index64 = Index.extOrTrunc(64).getZExtValue(); - Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64 - : Offset64 + Index64); + Offset = + CharUnits::fromQuantity(IsSub ? Offset64 - Index64 : Offset64 + Index64); } -bool DataRecursiveIntBinOpEvaluator:: - VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult, - const BinaryOperator *E, APValue &Result) { +bool DataRecursiveIntBinOpEvaluator::VisitBinOp(EvalResult const &LHSResult, + EvalResult const &RHSResult, + BinaryOperator const *E, + APValue &Result) { if (E->getOpcode() == BO_Comma) { if (RHSResult.Failed) return false; @@ -12364,8 +12343,8 @@ if (LHSResult.Failed || RHSResult.Failed) return false; - const APValue &LHSVal = LHSResult.Val; - const APValue &RHSVal = RHSResult.Val; + APValue const &LHSVal = LHSResult.Val; + APValue const &RHSVal = RHSResult.Val; // Handle cases like (unsigned long)&a + 4. if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) { @@ -12375,10 +12354,9 @@ } // Handle cases like 4 + (unsigned long)&a - if (E->getOpcode() == BO_Add && - RHSVal.isLValue() && LHSVal.isInt()) { + if (E->getOpcode() == BO_Add && RHSVal.isLValue() && LHSVal.isInt()) { Result = RHSVal; - addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false); + addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/ false); return true; } @@ -12387,12 +12365,12 @@ if (!LHSVal.getLValueOffset().isZero() || !RHSVal.getLValueOffset().isZero()) return false; - const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast(); - const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast(); + Expr const *LHSExpr = LHSVal.getLValueBase().dyn_cast(); + Expr const *RHSExpr = RHSVal.getLValueBase().dyn_cast(); if (!LHSExpr || !RHSExpr) return false; - const AddrLabelExpr *LHSAddrExpr = dyn_cast(LHSExpr); - const AddrLabelExpr *RHSAddrExpr = dyn_cast(RHSExpr); + AddrLabelExpr const *LHSAddrExpr = dyn_cast(LHSExpr); + AddrLabelExpr const *RHSAddrExpr = dyn_cast(RHSExpr); if (!LHSAddrExpr || !RHSAddrExpr) return false; // Make sure both labels come from the same function. @@ -12422,43 +12400,43 @@ Job &job = Queue.back(); switch (job.Kind) { - case Job::AnyExprKind: { - if (const BinaryOperator *Bop = dyn_cast(job.E)) { - if (shouldEnqueue(Bop)) { - job.Kind = Job::BinOpKind; - enqueue(Bop->getLHS()); - return; - } - } - - EvaluateExpr(job.E, Result); - Queue.pop_back(); - return; - } - - case Job::BinOpKind: { - const BinaryOperator *Bop = cast(job.E); - bool SuppressRHSDiags = false; - if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { - Queue.pop_back(); + case Job::AnyExprKind: { + if (BinaryOperator const *Bop = dyn_cast(job.E)) { + if (shouldEnqueue(Bop)) { + job.Kind = Job::BinOpKind; + enqueue(Bop->getLHS()); return; } - if (SuppressRHSDiags) - job.startSpeculativeEval(Info); - job.LHSResult.swap(Result); - job.Kind = Job::BinOpVisitedLHSKind; - enqueue(Bop->getRHS()); - return; } - case Job::BinOpVisitedLHSKind: { - const BinaryOperator *Bop = cast(job.E); - EvalResult RHS; - RHS.swap(Result); - Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); + EvaluateExpr(job.E, Result); + Queue.pop_back(); + return; + } + + case Job::BinOpKind: { + BinaryOperator const *Bop = cast(job.E); + bool SuppressRHSDiags = false; + if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) { Queue.pop_back(); return; } + if (SuppressRHSDiags) + job.startSpeculativeEval(Info); + job.LHSResult.swap(Result); + job.Kind = Job::BinOpVisitedLHSKind; + enqueue(Bop->getRHS()); + return; + } + + case Job::BinOpVisitedLHSKind: { + BinaryOperator const *Bop = cast(job.E); + EvalResult RHS; + RHS.swap(Result); + Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val); + Queue.pop_back(); + return; + } } llvm_unreachable("Invalid Job::Kind!"); @@ -12476,14 +12454,14 @@ template static bool -EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, +EvaluateComparisonBinaryOperator(EvalInfo &Info, BinaryOperator const *E, SuccessCB &&Success, AfterCB &&DoAfter) { assert(!E->isValueDependent()); assert(E->isComparisonOp() && "expected comparison operator"); assert((E->getOpcode() == BO_Cmp || E->getType()->isIntegralOrEnumerationType()) && "unsupported binary expression evaluation"); - auto Error = [&](const Expr *E) { + auto Error = [&](Expr const *E) { Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr); return false; }; @@ -12554,9 +12532,9 @@ if (LHS.isComplexFloat()) { APFloat::cmpResult CR_r = - LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); + LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal()); APFloat::cmpResult CR_i = - LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); + LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag()); bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual; return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E); } else { @@ -12567,8 +12545,7 @@ } } - if (LHSTy->isRealFloatingType() && - RHSTy->isRealFloatingType()) { + if (LHSTy->isRealFloatingType() && RHSTy->isRealFloatingType()) { APFloat RHS(0.0), LHS(0.0); bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info); @@ -12580,8 +12557,7 @@ assert(E->isComparisonOp() && "Invalid binary operator!"); llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS); - if (!Info.InConstantContext && - APFloatCmpResult == APFloat::cmpUnordered && + if (!Info.InConstantContext && APFloatCmpResult == APFloat::cmpUnordered && E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) { // Note: Compares may raise invalid in some cases involving NaN or sNaN. Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict); @@ -12654,8 +12630,8 @@ return Success(CmpResult::Unequal, E); } - const CharUnits &LHSOffset = LHSValue.getLValueOffset(); - const CharUnits &RHSOffset = RHSValue.getLValueOffset(); + CharUnits const &LHSOffset = LHSValue.getLValueOffset(); + CharUnits const &RHSOffset = RHSValue.getLValueOffset(); SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); @@ -12690,8 +12666,8 @@ // constant expression. if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() && Mismatch < RHSDesignator.Entries.size()) { - const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]); - const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]); + FieldDecl const *LF = getAsField(LHSDesignator.Entries[Mismatch]); + FieldDecl const *RF = getAsField(RHSDesignator.Entries[Mismatch]); if (!LF && !RF) Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes); else if (!LF) @@ -12764,10 +12740,10 @@ // Otherwise if either is a pointer to a virtual member function, the // result is unspecified. - if (const CXXMethodDecl *MD = dyn_cast(LHSValue.getDecl())) + if (CXXMethodDecl const *MD = dyn_cast(LHSValue.getDecl())) if (MD->isVirtual()) Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; - if (const CXXMethodDecl *MD = dyn_cast(RHSValue.getDecl())) + if (CXXMethodDecl const *MD = dyn_cast(RHSValue.getDecl())) if (MD->isVirtual()) Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD; @@ -12791,11 +12767,11 @@ return DoAfter(); } -bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) { +bool RecordExprEvaluator::VisitBinCmp(BinaryOperator const *E) { if (!CheckLiteralType(Info, E)) return false; - auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { + auto OnSuccess = [&](CmpResult CR, BinaryOperator const *E) { ComparisonCategoryResult CCR; switch (CR) { case CmpResult::Unequal: @@ -12831,7 +12807,7 @@ }); } -bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { +bool IntExprEvaluator::VisitBinaryOperator(BinaryOperator const *E) { // We don't support assignment in C. C++ assignments don't get here because // assignment is an lvalue in C++. if (E->isAssignmentOp()) { @@ -12850,11 +12826,10 @@ if (E->isComparisonOp()) { // Evaluate builtin binary comparisons by evaluating them as three-way // comparisons and then translating the result. - auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) { + auto OnSuccess = [&](CmpResult CR, BinaryOperator const *E) { assert((CR != CmpResult::Unequal || E->isEqualityOp()) && "should only produce Unequal for equality comparisons"); - bool IsEqual = CR == CmpResult::Equal, - IsLess = CR == CmpResult::Less, + bool IsEqual = CR == CmpResult::Equal, IsLess = CR == CmpResult::Less, IsGreater = CR == CmpResult::Greater; auto Op = E->getOpcode(); switch (Op) { @@ -12898,12 +12873,12 @@ // Handle &&A - &&B. if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero()) return Error(E); - const Expr *LHSExpr = LHSValue.Base.dyn_cast(); - const Expr *RHSExpr = RHSValue.Base.dyn_cast(); + Expr const *LHSExpr = LHSValue.Base.dyn_cast(); + Expr const *RHSExpr = RHSValue.Base.dyn_cast(); if (!LHSExpr || !RHSExpr) return Error(E); - const AddrLabelExpr *LHSAddrExpr = dyn_cast(LHSExpr); - const AddrLabelExpr *RHSAddrExpr = dyn_cast(RHSExpr); + AddrLabelExpr const *LHSAddrExpr = dyn_cast(LHSExpr); + AddrLabelExpr const *RHSAddrExpr = dyn_cast(RHSExpr); if (!LHSAddrExpr || !RHSAddrExpr) return Error(E); // Make sure both labels come from the same function. @@ -12912,8 +12887,8 @@ return Error(E); return Success(APValue(LHSAddrExpr, RHSAddrExpr), E); } - const CharUnits &LHSOffset = LHSValue.getLValueOffset(); - const CharUnits &RHSOffset = RHSValue.getLValueOffset(); + CharUnits const &LHSOffset = LHSValue.getLValueOffset(); + CharUnits const &RHSOffset = RHSValue.getLValueOffset(); SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator(); SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator(); @@ -12970,8 +12945,8 @@ /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with /// a result as the expression's type. bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr( - const UnaryExprOrTypeTraitExpr *E) { - switch(E->getKind()) { + UnaryExprOrTypeTraitExpr const *E) { + switch (E->getKind()) { case UETT_PreferredAlignOf: case UETT_AlignOf: { if (E->isArgumentType()) @@ -13002,7 +12977,7 @@ QualType SrcTy = E->getTypeOfArgument(); // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, // the result is the size of the referenced type." - if (const ReferenceType *Ref = SrcTy->getAs()) + if (ReferenceType const *Ref = SrcTy->getAs()) SrcTy = Ref->getPointeeType(); CharUnits Sizeof; @@ -13012,17 +12987,17 @@ } case UETT_OpenMPRequiredSimdAlign: assert(E->isArgumentType()); - return Success( - Info.Ctx.toCharUnitsFromBits( - Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType())) - .getQuantity(), - E); + return Success(Info.Ctx + .toCharUnitsFromBits(Info.Ctx.getOpenMPDefaultSimdAlign( + E->getArgumentType())) + .getQuantity(), + E); } llvm_unreachable("unknown expr/type trait"); } -bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) { +bool IntExprEvaluator::VisitOffsetOfExpr(OffsetOfExpr const *OOE) { CharUnits Result; unsigned n = OOE->getNumComponents(); if (n == 0) @@ -13032,11 +13007,11 @@ OffsetOfNode ON = OOE->getComponent(i); switch (ON.getKind()) { case OffsetOfNode::Array: { - const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); + Expr const *Idx = OOE->getIndexExpr(ON.getArrayExprIndex()); APSInt IdxResult; if (!EvaluateInteger(Idx, IdxResult, Info)) return false; - const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType); + ArrayType const *AT = Info.Ctx.getAsArrayType(CurrentType); if (!AT) return Error(OOE); CurrentType = AT->getElementType(); @@ -13047,12 +13022,13 @@ case OffsetOfNode::Field: { FieldDecl *MemberDecl = ON.getField(); - const RecordType *RT = CurrentType->getAs(); + RecordType const *RT = CurrentType->getAs(); if (!RT) return Error(OOE); RecordDecl *RD = RT->getDecl(); - if (RD->isInvalidDecl()) return false; - const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); + if (RD->isInvalidDecl()) + return false; + ASTRecordLayout const &RL = Info.Ctx.getASTRecordLayout(RD); unsigned i = MemberDecl->getFieldIndex(); assert(i < RL.getFieldCount() && "offsetof field in wrong type"); Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i)); @@ -13069,16 +13045,17 @@ return Error(OOE); // Find the layout of the class whose base we are looking into. - const RecordType *RT = CurrentType->getAs(); + RecordType const *RT = CurrentType->getAs(); if (!RT) return Error(OOE); RecordDecl *RD = RT->getDecl(); - if (RD->isInvalidDecl()) return false; - const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD); + if (RD->isInvalidDecl()) + return false; + ASTRecordLayout const &RL = Info.Ctx.getASTRecordLayout(RD); // Find the base class itself. CurrentType = BaseSpec->getType(); - const RecordType *BaseRT = CurrentType->getAs(); + RecordType const *BaseRT = CurrentType->getAs(); if (!BaseRT) return Error(OOE); @@ -13091,7 +13068,7 @@ return Success(Result, OOE); } -bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { +bool IntExprEvaluator::VisitUnaryOperator(UnaryOperator const *E) { switch (E->getOpcode()) { default: // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. @@ -13107,8 +13084,9 @@ case UO_Minus: { if (!Visit(E->getSubExpr())) return false; - if (!Result.isInt()) return Error(E); - const APSInt &Value = Result.getInt(); + if (!Result.isInt()) + return Error(E); + APSInt const &Value = Result.getInt(); if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() && !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1), E->getType())) @@ -13118,7 +13096,8 @@ case UO_Not: { if (!Visit(E->getSubExpr())) return false; - if (!Result.isInt()) return Error(E); + if (!Result.isInt()) + return Error(E); return Success(~Result.getInt(), E); } case UO_LNot: { @@ -13132,8 +13111,8 @@ /// HandleCast - This is used to evaluate implicit or explicit casts where the /// result type is integer. -bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) { - const Expr *SubExpr = E->getSubExpr(); +bool IntExprEvaluator::VisitCastExpr(CastExpr const *E) { + Expr const *SubExpr = E->getSubExpr(); QualType DestType = E->getType(); QualType SrcType = SubExpr->getType(); @@ -13249,8 +13228,8 @@ return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType); } - return Success(HandleIntToIntCast(Info, E, DestType, SrcType, - Result.getInt()), E); + return Success( + HandleIntToIntCast(Info, E, DestType, SrcType, Result.getInt()), E); } case CK_PointerToIntegral: { @@ -13304,7 +13283,7 @@ llvm_unreachable("unknown cast resulting in integral value"); } -bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { +bool IntExprEvaluator::VisitUnaryReal(UnaryOperator const *E) { if (E->getSubExpr()->getType()->isAnyComplexType()) { ComplexValue LV; if (!EvaluateComplex(E->getSubExpr(), LV, Info)) @@ -13317,7 +13296,7 @@ return Visit(E->getSubExpr()); } -bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { +bool IntExprEvaluator::VisitUnaryImag(UnaryOperator const *E) { if (E->getSubExpr()->getType()->isComplexIntegerType()) { ComplexValue LV; if (!EvaluateComplex(E->getSubExpr(), LV, Info)) @@ -13331,52 +13310,53 @@ return Success(0, E); } -bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { +bool IntExprEvaluator::VisitSizeOfPackExpr(SizeOfPackExpr const *E) { return Success(E->getPackLength(), E); } -bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { +bool IntExprEvaluator::VisitCXXNoexceptExpr(CXXNoexceptExpr const *E) { return Success(E->getValue(), E); } bool IntExprEvaluator::VisitConceptSpecializationExpr( - const ConceptSpecializationExpr *E) { + ConceptSpecializationExpr const *E) { return Success(E->isSatisfied(), E); } -bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) { +bool IntExprEvaluator::VisitRequiresExpr(RequiresExpr const *E) { return Success(E->isSatisfied(), E); } -bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { +bool FixedPointExprEvaluator::VisitUnaryOperator(UnaryOperator const *E) { switch (E->getOpcode()) { - default: - // Invalid unary operators + default: + // Invalid unary operators + return Error(E); + case UO_Plus: + // The result is just the value. + return Visit(E->getSubExpr()); + case UO_Minus: { + if (!Visit(E->getSubExpr())) + return false; + if (!Result.isFixedPoint()) return Error(E); - case UO_Plus: - // The result is just the value. - return Visit(E->getSubExpr()); - case UO_Minus: { - if (!Visit(E->getSubExpr())) return false; - if (!Result.isFixedPoint()) - return Error(E); - bool Overflowed; - APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); - if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) - return false; - return Success(Negated, E); - } - case UO_LNot: { - bool bres; - if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) - return false; - return Success(!bres, E); - } + bool Overflowed; + APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed); + if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType())) + return false; + return Success(Negated, E); + } + case UO_LNot: { + bool bres; + if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info)) + return false; + return Success(!bres, E); + } } } -bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) { - const Expr *SubExpr = E->getSubExpr(); +bool FixedPointExprEvaluator::VisitCastExpr(CastExpr const *E) { + Expr const *SubExpr = E->getSubExpr(); QualType DestType = E->getType(); assert(DestType->isFixedPointType() && "Expected destination type to be a fixed point type"); @@ -13391,9 +13371,9 @@ APFixedPoint Result = Src.convert(DestFXSema, &Overflowed); if (Overflowed) { if (Info.checkingForUndefinedBehavior()) - Info.Ctx.getDiagnostics().Report(E->getExprLoc(), - diag::warn_fixedpoint_constant_overflow) - << Result.toString() << E->getType(); + Info.Ctx.getDiagnostics().Report( + E->getExprLoc(), diag::warn_fixedpoint_constant_overflow) + << Result.toString() << E->getType(); if (!HandleOverflow(Info, E, Result, E->getType())) return false; } @@ -13410,9 +13390,9 @@ if (Overflowed) { if (Info.checkingForUndefinedBehavior()) - Info.Ctx.getDiagnostics().Report(E->getExprLoc(), - diag::warn_fixedpoint_constant_overflow) - << IntResult.toString() << E->getType(); + Info.Ctx.getDiagnostics().Report( + E->getExprLoc(), diag::warn_fixedpoint_constant_overflow) + << IntResult.toString() << E->getType(); if (!HandleOverflow(Info, E, IntResult, E->getType())) return false; } @@ -13430,9 +13410,9 @@ if (Overflowed) { if (Info.checkingForUndefinedBehavior()) - Info.Ctx.getDiagnostics().Report(E->getExprLoc(), - diag::warn_fixedpoint_constant_overflow) - << Result.toString() << E->getType(); + Info.Ctx.getDiagnostics().Report( + E->getExprLoc(), diag::warn_fixedpoint_constant_overflow) + << Result.toString() << E->getType(); if (!HandleOverflow(Info, E, Result, E->getType())) return false; } @@ -13447,12 +13427,12 @@ } } -bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { +bool FixedPointExprEvaluator::VisitBinaryOperator(BinaryOperator const *E) { if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) return ExprEvaluatorBaseTy::VisitBinaryOperator(E); - const Expr *LHS = E->getLHS(); - const Expr *RHS = E->getRHS(); + Expr const *LHS = E->getLHS(); + Expr const *RHS = E->getRHS(); FixedPointSemantics ResultFXSema = Info.Ctx.getFixedPointSemantics(E->getType()); @@ -13468,17 +13448,17 @@ switch (E->getOpcode()) { case BO_Add: { Result = LHSFX.add(RHSFX, &OpOverflow) - .convert(ResultFXSema, &ConversionOverflow); + .convert(ResultFXSema, &ConversionOverflow); break; } case BO_Sub: { Result = LHSFX.sub(RHSFX, &OpOverflow) - .convert(ResultFXSema, &ConversionOverflow); + .convert(ResultFXSema, &ConversionOverflow); break; } case BO_Mul: { Result = LHSFX.mul(RHSFX, &OpOverflow) - .convert(ResultFXSema, &ConversionOverflow); + .convert(ResultFXSema, &ConversionOverflow); break; } case BO_Div: { @@ -13487,7 +13467,7 @@ return false; } Result = LHSFX.div(RHSFX, &OpOverflow) - .convert(ResultFXSema, &ConversionOverflow); + .convert(ResultFXSema, &ConversionOverflow); break; } case BO_Shl: @@ -13520,7 +13500,7 @@ if (Info.checkingForUndefinedBehavior()) Info.Ctx.getDiagnostics().Report(E->getExprLoc(), diag::warn_fixedpoint_constant_overflow) - << Result.toString() << E->getType(); + << Result.toString() << E->getType(); if (!HandleOverflow(Info, E, Result, E->getType())) return false; } @@ -13532,52 +13512,51 @@ //===----------------------------------------------------------------------===// namespace { -class FloatExprEvaluator - : public ExprEvaluatorBase { +class FloatExprEvaluator : public ExprEvaluatorBase { APFloat &Result; + public: FloatExprEvaluator(EvalInfo &info, APFloat &result) - : ExprEvaluatorBaseTy(info), Result(result) {} + : ExprEvaluatorBaseTy(info), Result(result) {} - bool Success(const APValue &V, const Expr *e) { + bool Success(APValue const &V, Expr const *e) { Result = V.getFloat(); return true; } - bool ZeroInitialization(const Expr *E) { + bool ZeroInitialization(Expr const *E) { Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType())); return true; } - bool VisitCallExpr(const CallExpr *E); + bool VisitCallExpr(CallExpr const *E); - bool VisitUnaryOperator(const UnaryOperator *E); - bool VisitBinaryOperator(const BinaryOperator *E); - bool VisitFloatingLiteral(const FloatingLiteral *E); - bool VisitCastExpr(const CastExpr *E); + bool VisitUnaryOperator(UnaryOperator const *E); + bool VisitBinaryOperator(BinaryOperator const *E); + bool VisitFloatingLiteral(FloatingLiteral const *E); + bool VisitCastExpr(CastExpr const *E); - bool VisitUnaryReal(const UnaryOperator *E); - bool VisitUnaryImag(const UnaryOperator *E); + bool VisitUnaryReal(UnaryOperator const *E); + bool VisitUnaryImag(UnaryOperator const *E); // FIXME: Missing: array subscript of vector, member of vector }; } // end anonymous namespace -static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) { +static bool EvaluateFloat(Expr const *E, APFloat &Result, EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isRealFloatingType()); return FloatExprEvaluator(Info, Result).Visit(E); } -static bool TryEvaluateBuiltinNaN(const ASTContext &Context, - QualType ResultTy, - const Expr *Arg, - bool SNaN, +static bool TryEvaluateBuiltinNaN(ASTContext const &Context, QualType ResultTy, + Expr const *Arg, bool SNaN, llvm::APFloat &Result) { - const StringLiteral *S = dyn_cast(Arg->IgnoreParenCasts()); - if (!S) return false; + StringLiteral const *S = dyn_cast(Arg->IgnoreParenCasts()); + if (!S) + return false; - const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy); + llvm::fltSemantics const &Sem = Context.getFloatTypeSemantics(ResultTy); llvm::APInt fill; @@ -13607,7 +13586,7 @@ return true; } -bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) { +bool FloatExprEvaluator::VisitCallExpr(CallExpr const *E) { switch (E->getBuiltinCallee()) { default: return ExprEvaluatorBaseTy::VisitCallExpr(E); @@ -13620,8 +13599,8 @@ case Builtin::BI__builtin_inff: case Builtin::BI__builtin_infl: case Builtin::BI__builtin_inff128: { - const llvm::fltSemantics &Sem = - Info.Ctx.getFloatTypeSemantics(E->getType()); + llvm::fltSemantics const &Sem = + Info.Ctx.getFloatTypeSemantics(E->getType()); Result = llvm::APFloat::getInf(Sem); return true; } @@ -13630,8 +13609,8 @@ case Builtin::BI__builtin_nansf: case Builtin::BI__builtin_nansl: case Builtin::BI__builtin_nansf128: - if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), - true, Result)) + if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), true, + Result)) return Error(E); return true; @@ -13641,8 +13620,8 @@ case Builtin::BI__builtin_nanf128: // If this is __builtin_nan() turn this into a nan, otherwise we // can't constant fold it. - if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), - false, Result)) + if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0), false, + Result)) return Error(E); return true; @@ -13665,9 +13644,9 @@ case Builtin::BI__arithmetic_fence: return EvaluateFloat(E->getArg(0), Result, Info); - // FIXME: Builtin::BI__builtin_powi - // FIXME: Builtin::BI__builtin_powif - // FIXME: Builtin::BI__builtin_powil + // FIXME: Builtin::BI__builtin_powi + // FIXME: Builtin::BI__builtin_powif + // FIXME: Builtin::BI__builtin_powil case Builtin::BI__builtin_copysign: case Builtin::BI__builtin_copysignf: @@ -13683,7 +13662,7 @@ } } -bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) { +bool FloatExprEvaluator::VisitUnaryReal(UnaryOperator const *E) { if (E->getSubExpr()->getType()->isAnyComplexType()) { ComplexValue CV; if (!EvaluateComplex(E->getSubExpr(), CV, Info)) @@ -13695,7 +13674,7 @@ return Visit(E->getSubExpr()); } -bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) { +bool FloatExprEvaluator::VisitUnaryImag(UnaryOperator const *E) { if (E->getSubExpr()->getType()->isAnyComplexType()) { ComplexValue CV; if (!EvaluateComplex(E->getSubExpr(), CV, Info)) @@ -13705,14 +13684,15 @@ } VisitIgnoredValue(E->getSubExpr()); - const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); + llvm::fltSemantics const &Sem = Info.Ctx.getFloatTypeSemantics(E->getType()); Result = llvm::APFloat::getZero(Sem); return true; } -bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { +bool FloatExprEvaluator::VisitUnaryOperator(UnaryOperator const *E) { switch (E->getOpcode()) { - default: return Error(E); + default: + return Error(E); case UO_Plus: return EvaluateFloat(E->getSubExpr(), Result, Info); case UO_Minus: @@ -13726,7 +13706,7 @@ } } -bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { +bool FloatExprEvaluator::VisitBinaryOperator(BinaryOperator const *E) { if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) return ExprEvaluatorBaseTy::VisitBinaryOperator(E); @@ -13738,13 +13718,13 @@ handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS); } -bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) { +bool FloatExprEvaluator::VisitFloatingLiteral(FloatingLiteral const *E) { Result = E->getValue(); return true; } -bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) { - const Expr* SubExpr = E->getSubExpr(); +bool FloatExprEvaluator::VisitCastExpr(CastExpr const *E) { + Expr const *SubExpr = E->getSubExpr(); switch (E->getCastKind()) { default: @@ -13752,11 +13732,10 @@ case CK_IntegralToFloating: { APSInt IntResult; - const FPOptions FPO = E->getFPFeaturesInEffect( - Info.Ctx.getLangOpts()); + const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); return EvaluateInteger(SubExpr, IntResult, Info) && - HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), - IntResult, E->getType(), Result); + HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(), IntResult, + E->getType(), Result); } case CK_FixedPointToFloating: { @@ -13790,42 +13769,41 @@ //===----------------------------------------------------------------------===// namespace { -class ComplexExprEvaluator - : public ExprEvaluatorBase { +class ComplexExprEvaluator : public ExprEvaluatorBase { ComplexValue &Result; public: ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result) - : ExprEvaluatorBaseTy(info), Result(Result) {} + : ExprEvaluatorBaseTy(info), Result(Result) {} - bool Success(const APValue &V, const Expr *e) { + bool Success(APValue const &V, Expr const *e) { Result.setFrom(V); return true; } - bool ZeroInitialization(const Expr *E); + bool ZeroInitialization(Expr const *E); //===--------------------------------------------------------------------===// // Visitor Methods //===--------------------------------------------------------------------===// - bool VisitImaginaryLiteral(const ImaginaryLiteral *E); - bool VisitCastExpr(const CastExpr *E); - bool VisitBinaryOperator(const BinaryOperator *E); - bool VisitUnaryOperator(const UnaryOperator *E); - bool VisitInitListExpr(const InitListExpr *E); - bool VisitCallExpr(const CallExpr *E); + bool VisitImaginaryLiteral(ImaginaryLiteral const *E); + bool VisitCastExpr(CastExpr const *E); + bool VisitBinaryOperator(BinaryOperator const *E); + bool VisitUnaryOperator(UnaryOperator const *E); + bool VisitInitListExpr(InitListExpr const *E); + bool VisitCallExpr(CallExpr const *E); }; } // end anonymous namespace -static bool EvaluateComplex(const Expr *E, ComplexValue &Result, +static bool EvaluateComplex(Expr const *E, ComplexValue &Result, EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isAnyComplexType()); return ComplexExprEvaluator(Info, Result).Visit(E); } -bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) { +bool ComplexExprEvaluator::ZeroInitialization(Expr const *E) { QualType ElemTy = E->getType()->castAs()->getElementType(); if (ElemTy->isRealFloatingType()) { Result.makeComplexFloat(); @@ -13841,8 +13819,8 @@ return true; } -bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) { - const Expr* SubExpr = E->getSubExpr(); +bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral const *E) { + Expr const *SubExpr = E->getSubExpr(); if (SubExpr->getType()->isRealFloatingType()) { Result.makeComplexFloat(); @@ -13866,7 +13844,7 @@ } } -bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) { +bool ComplexExprEvaluator::VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { case CK_BitCast: @@ -13949,8 +13927,8 @@ return false; QualType To = E->getType()->castAs()->getElementType(); - QualType From - = E->getSubExpr()->getType()->castAs()->getElementType(); + QualType From = + E->getSubExpr()->getType()->castAs()->getElementType(); return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) && HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag); @@ -13961,13 +13939,13 @@ return false; QualType To = E->getType()->castAs()->getElementType(); - QualType From - = E->getSubExpr()->getType()->castAs()->getElementType(); + QualType From = + E->getSubExpr()->getType()->castAs()->getElementType(); Result.makeComplexInt(); - return HandleFloatToIntCast(Info, E, From, Result.FloatReal, - To, Result.IntReal) && - HandleFloatToIntCast(Info, E, From, Result.FloatImag, - To, Result.IntImag); + return HandleFloatToIntCast(Info, E, From, Result.FloatReal, To, + Result.IntReal) && + HandleFloatToIntCast(Info, E, From, Result.FloatImag, To, + Result.IntImag); } case CK_IntegralRealToComplex: { @@ -13985,8 +13963,8 @@ return false; QualType To = E->getType()->castAs()->getElementType(); - QualType From - = E->getSubExpr()->getType()->castAs()->getElementType(); + QualType From = + E->getSubExpr()->getType()->castAs()->getElementType(); Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal); Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag); @@ -13997,23 +13975,22 @@ if (!Visit(E->getSubExpr())) return false; - const FPOptions FPO = E->getFPFeaturesInEffect( - Info.Ctx.getLangOpts()); + const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()); QualType To = E->getType()->castAs()->getElementType(); - QualType From - = E->getSubExpr()->getType()->castAs()->getElementType(); + QualType From = + E->getSubExpr()->getType()->castAs()->getElementType(); Result.makeComplexFloat(); - return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, - To, Result.FloatReal) && - HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, - To, Result.FloatImag); + return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal, To, + Result.FloatReal) && + HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag, To, + Result.FloatImag); } } llvm_unreachable("unknown cast resulting in complex value"); } -bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { +bool ComplexExprEvaluator::VisitBinaryOperator(BinaryOperator const *E) { if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma) return ExprEvaluatorBaseTy::VisitBinaryOperator(E); @@ -14050,7 +14027,8 @@ assert(!(LHSReal && RHSReal) && "Cannot have both operands of a complex operation be real."); switch (E->getOpcode()) { - default: return Error(E); + default: + return Error(E); case BO_Add: if (Result.isComplexFloat()) { Result.getComplexFloatReal().add(RHS.getComplexFloatReal(), @@ -14155,11 +14133,11 @@ } else { ComplexValue LHS = Result; Result.getComplexIntReal() = - (LHS.getComplexIntReal() * RHS.getComplexIntReal() - - LHS.getComplexIntImag() * RHS.getComplexIntImag()); + (LHS.getComplexIntReal() * RHS.getComplexIntReal() - + LHS.getComplexIntImag() * RHS.getComplexIntImag()); Result.getComplexIntImag() = - (LHS.getComplexIntReal() * RHS.getComplexIntImag() + - LHS.getComplexIntImag() * RHS.getComplexIntReal()); + (LHS.getComplexIntReal() * RHS.getComplexIntImag() + + LHS.getComplexIntImag() * RHS.getComplexIntReal()); } break; case BO_Div: @@ -14223,13 +14201,15 @@ ComplexValue LHS = Result; APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() + - RHS.getComplexIntImag() * RHS.getComplexIntImag(); + RHS.getComplexIntImag() * RHS.getComplexIntImag(); Result.getComplexIntReal() = - (LHS.getComplexIntReal() * RHS.getComplexIntReal() + - LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den; + (LHS.getComplexIntReal() * RHS.getComplexIntReal() + + LHS.getComplexIntImag() * RHS.getComplexIntImag()) / + Den; Result.getComplexIntImag() = - (LHS.getComplexIntImag() * RHS.getComplexIntReal() - - LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den; + (LHS.getComplexIntImag() * RHS.getComplexIntReal() - + LHS.getComplexIntReal() * RHS.getComplexIntImag()) / + Den; } break; } @@ -14237,7 +14217,7 @@ return true; } -bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) { +bool ComplexExprEvaluator::VisitUnaryOperator(UnaryOperator const *E) { // Get the operand value into 'Result'. if (!Visit(E->getSubExpr())) return false; @@ -14254,8 +14234,7 @@ if (Result.isComplexFloat()) { Result.getComplexFloatReal().changeSign(); Result.getComplexFloatImag().changeSign(); - } - else { + } else { Result.getComplexIntReal() = -Result.getComplexIntReal(); Result.getComplexIntImag() = -Result.getComplexIntImag(); } @@ -14269,7 +14248,7 @@ } } -bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) { +bool ComplexExprEvaluator::VisitInitListExpr(InitListExpr const *E) { if (E->getNumInits() == 2) { if (E->getType()->isComplexType()) { Result.makeComplexFloat(); @@ -14289,7 +14268,7 @@ return ExprEvaluatorBaseTy::VisitInitListExpr(E); } -bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) { +bool ComplexExprEvaluator::VisitCallExpr(CallExpr const *E) { switch (E->getBuiltinCallee()) { case Builtin::BI__builtin_complex: Result.makeComplexFloat(); @@ -14312,20 +14291,20 @@ //===----------------------------------------------------------------------===// namespace { -class AtomicExprEvaluator : - public ExprEvaluatorBase { - const LValue *This; +class AtomicExprEvaluator : public ExprEvaluatorBase { + LValue const *This; APValue &Result; + public: - AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result) + AtomicExprEvaluator(EvalInfo &Info, LValue const *This, APValue &Result) : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {} - bool Success(const APValue &V, const Expr *E) { + bool Success(APValue const &V, Expr const *E) { Result = V; return true; } - bool ZeroInitialization(const Expr *E) { + bool ZeroInitialization(Expr const *E) { ImplicitValueInitExpr VIE( E->getType()->castAs()->getValueType()); // For atomic-qualified class (and array) types in C++, initialize the @@ -14334,7 +14313,7 @@ : Evaluate(Result, Info, &VIE); } - bool VisitCastExpr(const CastExpr *E) { + bool VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { default: return ExprEvaluatorBaseTy::VisitCastExpr(E); @@ -14346,7 +14325,7 @@ }; } // end anonymous namespace -static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, +static bool EvaluateAtomic(Expr const *E, LValue const *This, APValue &Result, EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isAtomicType()); @@ -14359,16 +14338,15 @@ //===----------------------------------------------------------------------===// namespace { -class VoidExprEvaluator - : public ExprEvaluatorBase { +class VoidExprEvaluator : public ExprEvaluatorBase { public: VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {} - bool Success(const APValue &V, const Expr *e) { return true; } + bool Success(APValue const &V, Expr const *e) { return true; } - bool ZeroInitialization(const Expr *E) { return true; } + bool ZeroInitialization(Expr const *E) { return true; } - bool VisitCastExpr(const CastExpr *E) { + bool VisitCastExpr(CastExpr const *E) { switch (E->getCastKind()) { default: return ExprEvaluatorBaseTy::VisitCastExpr(E); @@ -14378,7 +14356,7 @@ } } - bool VisitCallExpr(const CallExpr *E) { + bool VisitCallExpr(CallExpr const *E) { switch (E->getBuiltinCallee()) { case Builtin::BI__assume: case Builtin::BI__builtin_assume: @@ -14395,11 +14373,11 @@ return ExprEvaluatorBaseTy::VisitCallExpr(E); } - bool VisitCXXDeleteExpr(const CXXDeleteExpr *E); + bool VisitCXXDeleteExpr(CXXDeleteExpr const *E); }; } // end anonymous namespace -bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { +bool VoidExprEvaluator::VisitCXXDeleteExpr(CXXDeleteExpr const *E) { // We cannot speculatively evaluate a delete expression. if (Info.SpeculativeEvaluationDepth) return false; @@ -14411,7 +14389,7 @@ return false; } - const Expr *Arg = E->getArgument(); + Expr const *Arg = E->getArgument(); LValue Pointer; if (!EvaluatePointer(Arg, Pointer, Info)) @@ -14447,7 +14425,7 @@ // For a class type with a virtual destructor, the selected operator delete // is the one looked up when building the destructor. if (!E->isArrayForm() && !E->isGlobalDelete()) { - const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType); + FunctionDecl const *VirtualDelete = getVirtualOperatorDelete(AllocType); if (VirtualDelete && !VirtualDelete->isReplaceableGlobalAllocationFunction()) { Info.FFDiag(E, diag::note_constexpr_new_non_replaceable) @@ -14472,7 +14450,7 @@ return true; } -static bool EvaluateVoid(const Expr *E, EvalInfo &Info) { +static bool EvaluateVoid(Expr const *E, EvalInfo &Info) { assert(!E->isValueDependent()); assert(E->isPRValue() && E->getType()->isVoidType()); return VoidExprEvaluator(Info).Visit(E); @@ -14482,7 +14460,7 @@ // Top level Expr::EvaluateAsRValue method. //===----------------------------------------------------------------------===// -static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) { +static bool Evaluate(APValue &Result, EvalInfo &Info, Expr const *E) { assert(!E->isValueDependent()); // In C, function designators are not lvalues, but we evaluate them as if they // are. @@ -14514,7 +14492,8 @@ return false; C.moveInto(Result); } else if (T->isFixedPointType()) { - if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false; + if (!FixedPointExprEvaluator(Info, Result).Visit(E)) + return false; } else if (T->isMemberPointerType()) { MemberPtr P; if (!EvaluateMemberPointer(E, P, Info)) @@ -14537,8 +14516,7 @@ Result = Value; } else if (T->isVoidType()) { if (!Info.getLangOpts().CPlusPlus11) - Info.CCEDiag(E, diag::note_constexpr_nonliteral) - << E->getType(); + Info.CCEDiag(E, diag::note_constexpr_nonliteral) << E->getType(); if (!EvaluateVoid(E, Info)) return false; } else if (T->isAtomicType()) { @@ -14567,8 +14545,8 @@ /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some /// cases, the in-place evaluation is essential, since later initializers for /// an object can indirectly refer to subobjects which were initialized earlier. -static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, - const Expr *E, bool AllowNonLiteralTypes) { +static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, LValue const &This, + Expr const *E, bool AllowNonLiteralTypes) { assert(!E->isValueDependent()); if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This)) @@ -14595,7 +14573,7 @@ /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit /// lvalue-to-rvalue cast if it is an lvalue. -static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) { +static bool EvaluateAsRValue(EvalInfo &Info, Expr const *E, APValue &Result) { assert(!E->isValueDependent()); if (Info.EnableNewConstInterp) { if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result)) @@ -14624,13 +14602,13 @@ CheckMemoryLeaks(Info); } -static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, - const ASTContext &Ctx, bool &IsConst) { +static bool FastEvaluateAsRValue(Expr const *Exp, Expr::EvalResult &Result, + ASTContext const &Ctx, bool &IsConst) { // Fast-path evaluations of integer literals, since we sometimes see files // containing vast quantities of these. - if (const IntegerLiteral *L = dyn_cast(Exp)) { - Result.Val = APValue(APSInt(L->getValue(), - L->getType()->isUnsignedIntegerType())); + if (IntegerLiteral const *L = dyn_cast(Exp)) { + Result.Val = + APValue(APSInt(L->getValue(), L->getType()->isUnsignedIntegerType())); IsConst = true; return true; } @@ -14659,8 +14637,8 @@ (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior); } -static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, - const ASTContext &Ctx, EvalInfo &Info) { +static bool EvaluateAsRValue(Expr const *E, Expr::EvalResult &Result, + ASTContext const &Ctx, EvalInfo &Info) { assert(!E->isValueDependent()); bool IsConst; if (FastEvaluateAsRValue(E, Result, Ctx, IsConst)) @@ -14669,8 +14647,8 @@ return EvaluateAsRValue(Info, E, Result.Val); } -static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, - const ASTContext &Ctx, +static bool EvaluateAsInt(Expr const *E, Expr::EvalResult &ExprResult, + ASTContext const &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info) { assert(!E->isValueDependent()); @@ -14685,8 +14663,8 @@ return true; } -static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, - const ASTContext &Ctx, +static bool EvaluateAsFixedPoint(Expr const *E, Expr::EvalResult &ExprResult, + ASTContext const &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info) { assert(!E->isValueDependent()); @@ -14708,7 +14686,7 @@ /// we want to. If this function returns true, it returns the folded constant /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion /// will be applied to the result. -bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, +bool Expr::EvaluateAsRValue(EvalResult &Result, ASTContext const &Ctx, bool InConstantContext) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -14717,7 +14695,7 @@ return ::EvaluateAsRValue(this, Result, Ctx, Info); } -bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, +bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext const &Ctx, bool InConstantContext) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -14726,7 +14704,7 @@ HandleConversionToBool(Scratch.Val, Result); } -bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, +bool Expr::EvaluateAsInt(EvalResult &Result, ASTContext const &Ctx, SideEffectsKind AllowSideEffects, bool InConstantContext) const { assert(!isValueDependent() && @@ -14736,7 +14714,7 @@ return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info); } -bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, +bool Expr::EvaluateAsFixedPoint(EvalResult &Result, ASTContext const &Ctx, SideEffectsKind AllowSideEffects, bool InConstantContext) const { assert(!isValueDependent() && @@ -14746,7 +14724,7 @@ return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info); } -bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx, +bool Expr::EvaluateAsFloat(APFloat &Result, ASTContext const &Ctx, SideEffectsKind AllowSideEffects, bool InConstantContext) const { assert(!isValueDependent() && @@ -14765,7 +14743,7 @@ return true; } -bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, +bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext const &Ctx, bool InConstantContext) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -14785,7 +14763,7 @@ return true; } -static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, +static bool EvaluateDestruction(ASTContext const &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction) { @@ -14809,7 +14787,7 @@ return true; } -bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, +bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ASTContext const &Ctx, ConstantExprKind Kind) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -14826,7 +14804,7 @@ // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to // represent the result of the evaluation. CheckConstantExpression ensures // this doesn't escape. - MaterializeTemporaryExpr BaseMTE(T, const_cast(this), true); + MaterializeTemporaryExpr BaseMTE(T, const_cast(this), true); APValue::LValueBase Base(&BaseMTE); Info.setEvaluatingDecl(Base, Result.Val); @@ -14859,8 +14837,8 @@ return true; } -bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx, - const VarDecl *VD, +bool Expr::EvaluateAsInitializer(APValue &Value, ASTContext const &Ctx, + VarDecl const *VD, SmallVectorImpl &Notes, bool IsConstantInitialization) const { assert(!isValueDependent() && @@ -14940,7 +14918,7 @@ /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be /// constant folded, but discard the result. -bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const { +bool Expr::isEvaluatable(ASTContext const &Ctx, SideEffectsKind SEK) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -14949,8 +14927,9 @@ !hasUnacceptableSideEffect(Result, SEK); } -APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx, - SmallVectorImpl *Diag) const { +APSInt +Expr::EvaluateKnownConstInt(ASTContext const &Ctx, + SmallVectorImpl *Diag) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -14968,7 +14947,7 @@ } APSInt Expr::EvaluateKnownConstIntCheckOverflow( - const ASTContext &Ctx, SmallVectorImpl *Diag) const { + ASTContext const &Ctx, SmallVectorImpl *Diag) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -14986,7 +14965,7 @@ return EVResult.Val.getInt(); } -void Expr::EvaluateForOverflow(const ASTContext &Ctx) const { +void Expr::EvaluateForOverflow(ASTContext const &Ctx) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -15039,13 +15018,13 @@ ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {} }; -} +} // namespace static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); } static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; } -static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) { +static ICEDiag CheckEvalInICE(Expr const *E, ASTContext const &Ctx) { Expr::EvalResult EVResult; Expr::EvalStatus Status; EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression); @@ -15058,7 +15037,7 @@ return NoDiag(); } -static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) { +static ICEDiag CheckICE(Expr const *E, ASTContext const &Ctx) { assert(!E->isValueDependent() && "Should not see value dependent exprs!"); if (!E->getType()->isIntegralOrEnumerationType()) return ICEDiag(IK_NotICE, E->getBeginLoc()); @@ -15170,8 +15149,8 @@ return NoDiag(); case Expr::SubstNonTypeTemplateParmExprClass: - return - CheckICE(cast(E)->getReplacement(), Ctx); + return CheckICE(cast(E)->getReplacement(), + Ctx); case Expr::ConstantExprClass: return CheckICE(cast(E)->getSubExpr(), Ctx); @@ -15198,7 +15177,7 @@ // C99 6.6/3 allows function calls within unevaluated subexpressions of // constant expressions, but they can never be ICEs because an ICE cannot // contain an operand of (pointer to) function type. - const CallExpr *CE = cast(E); + CallExpr const *CE = cast(E); if (CE->getBuiltinCallee()) return CheckEvalInICE(E, Ctx); return ICEDiag(IK_NotICE, E->getBeginLoc()); @@ -15207,7 +15186,7 @@ return CheckICE(cast(E)->getSemanticForm(), Ctx); case Expr::DeclRefExprClass: { - const NamedDecl *D = cast(E)->getDecl(); + NamedDecl const *D = cast(E)->getDecl(); if (isa(D)) return NoDiag(); @@ -15220,7 +15199,7 @@ // // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In // that mode, use of reference variables should not be allowed. - const VarDecl *VD = dyn_cast(D); + VarDecl const *VD = dyn_cast(D); if (VD && VD->isUsableInConstantExpressions(Ctx) && !VD->getType()->isReferenceType()) return NoDiag(); @@ -15228,7 +15207,7 @@ return ICEDiag(IK_NotICE, E->getBeginLoc()); } case Expr::UnaryOperatorClass: { - const UnaryOperator *Exp = cast(E); + UnaryOperator const *Exp = cast(E); switch (Exp->getOpcode()) { case UO_PostInc: case UO_PostDec: @@ -15262,14 +15241,14 @@ return CheckEvalInICE(E, Ctx); } case Expr::UnaryExprOrTypeTraitExprClass: { - const UnaryExprOrTypeTraitExpr *Exp = cast(E); - if ((Exp->getKind() == UETT_SizeOf) && + UnaryExprOrTypeTraitExpr const *Exp = cast(E); + if ((Exp->getKind() == UETT_SizeOf) && Exp->getTypeOfArgument()->isVariableArrayType()) return ICEDiag(IK_NotICE, E->getBeginLoc()); return NoDiag(); } case Expr::BinaryOperatorClass: { - const BinaryOperator *Exp = cast(E); + BinaryOperator const *Exp = cast(E); switch (Exp->getOpcode()) { case BO_PtrMemD: case BO_PtrMemI: @@ -15309,8 +15288,7 @@ case BO_Cmp: { ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx); ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx); - if (Exp->getOpcode() == BO_Div || - Exp->getOpcode() == BO_Rem) { + if (Exp->getOpcode() == BO_Div || Exp->getOpcode() == BO_Rem) { // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure // we don't evaluate one. if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) { @@ -15363,10 +15341,10 @@ case Expr::CXXReinterpretCastExprClass: case Expr::CXXConstCastExprClass: case Expr::ObjCBridgedCastExprClass: { - const Expr *SubExpr = cast(E)->getSubExpr(); + Expr const *SubExpr = cast(E)->getSubExpr(); if (isa(E)) { - if (const FloatingLiteral *FL - = dyn_cast(SubExpr->IgnoreParenImpCasts())) { + if (FloatingLiteral const *FL = + dyn_cast(SubExpr->IgnoreParenImpCasts())) { unsigned DestWidth = Ctx.getIntWidth(E->getType()); bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType(); APSInt IgnoredVal(DestWidth, !DestSigned); @@ -15374,9 +15352,9 @@ // If the value does not fit in the destination type, the behavior is // undefined, so we are not required to treat it as a constant // expression. - if (FL->getValue().convertToInteger(IgnoredVal, - llvm::APFloat::rmTowardZero, - &Ignored) & APFloat::opInvalidOp) + if (FL->getValue().convertToInteger( + IgnoredVal, llvm::APFloat::rmTowardZero, &Ignored) & + APFloat::opInvalidOp) return ICEDiag(IK_NotICE, E->getBeginLoc()); return NoDiag(); } @@ -15394,24 +15372,28 @@ } } case Expr::BinaryConditionalOperatorClass: { - const BinaryConditionalOperator *Exp = cast(E); + BinaryConditionalOperator const *Exp = cast(E); ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx); - if (CommonResult.Kind == IK_NotICE) return CommonResult; + if (CommonResult.Kind == IK_NotICE) + return CommonResult; ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx); - if (FalseResult.Kind == IK_NotICE) return FalseResult; - if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult; + if (FalseResult.Kind == IK_NotICE) + return FalseResult; + if (CommonResult.Kind == IK_ICEIfUnevaluated) + return CommonResult; if (FalseResult.Kind == IK_ICEIfUnevaluated && - Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag(); + Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) + return NoDiag(); return FalseResult; } case Expr::ConditionalOperatorClass: { - const ConditionalOperator *Exp = cast(E); + ConditionalOperator const *Exp = cast(E); // If the condition (ignoring parens) is a __builtin_constant_p call, // then only the true side is actually considered in an integer constant // expression, and it is fully evaluated. This is an important GNU // extension. See GCC PR38377 for discussion. - if (const CallExpr *CallCE - = dyn_cast(Exp->getCond()->IgnoreParenCasts())) + if (CallExpr const *CallCE = + dyn_cast(Exp->getCond()->IgnoreParenCasts())) if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) return CheckEvalInICE(E, Ctx); ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx); @@ -15454,12 +15436,13 @@ } /// Evaluate an expression as a C++11 integral constant expression. -static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, - const Expr *E, +static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext const &Ctx, + Expr const *E, llvm::APSInt *Value, SourceLocation *Loc) { if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { - if (Loc) *Loc = E->getExprLoc(); + if (Loc) + *Loc = E->getExprLoc(); return false; } @@ -15468,15 +15451,17 @@ return false; if (!Result.isInt()) { - if (Loc) *Loc = E->getExprLoc(); + if (Loc) + *Loc = E->getExprLoc(); return false; } - if (Value) *Value = Result.getInt(); + if (Value) + *Value = Result.getInt(); return true; } -bool Expr::isIntegerConstantExpr(const ASTContext &Ctx, +bool Expr::isIntegerConstantExpr(ASTContext const &Ctx, SourceLocation *Loc) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -15486,13 +15471,14 @@ ICEDiag D = CheckICE(this, Ctx); if (D.Kind != IK_ICE) { - if (Loc) *Loc = D.Loc; + if (Loc) + *Loc = D.Loc; return false; } return true; } -Optional Expr::getIntegerConstantExpr(const ASTContext &Ctx, +Optional Expr::getIntegerConstantExpr(ASTContext const &Ctx, SourceLocation *Loc, bool isEvaluated) const { assert(!isValueDependent() && @@ -15524,14 +15510,14 @@ return ExprResult.Val.getInt(); } -bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const { +bool Expr::isCXX98IntegralConstantExpr(ASTContext const &Ctx) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); return CheckICE(this, Ctx).Kind == IK_ICE; } -bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result, +bool Expr::isCXX11ConstantExpr(ASTContext const &Ctx, APValue *Result, SourceLocation *Loc) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -15555,19 +15541,21 @@ if (!Diags.empty()) { IsConstExpr = false; - if (Loc) *Loc = Diags[0].first; + if (Loc) + *Loc = Diags[0].first; } else if (!IsConstExpr) { // FIXME: This shouldn't happen. - if (Loc) *Loc = getExprLoc(); + if (Loc) + *Loc = getExprLoc(); } return IsConstExpr; } bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, - const FunctionDecl *Callee, - ArrayRef Args, - const Expr *This) const { + FunctionDecl const *Callee, + ArrayRef Args, + Expr const *This) const { assert(!isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -15576,7 +15564,7 @@ Info.InConstantContext = true; LValue ThisVal; - const LValue *ThisPtr = nullptr; + LValue const *ThisPtr = nullptr; if (This) { #ifndef NDEBUG auto *MD = dyn_cast(Callee); @@ -15594,14 +15582,13 @@ } CallRef Call = Info.CurrentCall->createCall(Callee); - for (ArrayRef::iterator I = Args.begin(), E = Args.end(); + for (ArrayRef::iterator I = Args.begin(), E = Args.end(); I != E; ++I) { unsigned Idx = I - Args.begin(); if (Idx >= Callee->getNumParams()) break; - const ParmVarDecl *PVD = Callee->getParamDecl(Idx); - if ((*I)->isValueDependent() || - !EvaluateCallArg(PVD, *I, Call, Info) || + ParmVarDecl const *PVD = Callee->getParamDecl(Idx); + if ((*I)->isValueDependent() || !EvaluateCallArg(PVD, *I, Call, Info) || Info.EvalStatus.HasSideEffects) { // If evaluation fails, throw away the argument entirely. if (APValue *Slot = Info.getParamSlot(Call, PVD)) @@ -15626,9 +15613,8 @@ !Info.EvalStatus.HasSideEffects; } -bool Expr::isPotentialConstantExpr(const FunctionDecl *FD, - SmallVectorImpl< - PartialDiagnosticAt> &Diags) { +bool Expr::isPotentialConstantExpr( + FunctionDecl const *FD, SmallVectorImpl &Diags) { // FIXME: It would be useful to check constexpr function templates, but at the // moment the constant expression evaluator cannot cope with the non-rigorous // ASTs which we build for dependent expressions. @@ -15648,8 +15634,8 @@ return Diags.empty(); } - const CXXMethodDecl *MD = dyn_cast(FD); - const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; + CXXMethodDecl const *MD = dyn_cast(FD); + CXXRecordDecl const *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr; // Fabricate an arbitrary expression on the stack and pretend that it // is a temporary being used as the 'this' pointer. @@ -15657,10 +15643,10 @@ ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy); This.set({&VIE, Info.CurrentCall->Index}); - ArrayRef Args; + ArrayRef Args; APValue Scratch; - if (const CXXConstructorDecl *CD = dyn_cast(FD)) { + if (CXXConstructorDecl const *CD = dyn_cast(FD)) { // Evaluate the call as a constant initializer, to allow the construction // of objects of non-literal types. Info.setEvaluatingDecl(This.getLValueBase(), Scratch); @@ -15674,10 +15660,9 @@ return Diags.empty(); } -bool Expr::isPotentialConstantExprUnevaluated(Expr *E, - const FunctionDecl *FD, - SmallVectorImpl< - PartialDiagnosticAt> &Diags) { +bool Expr::isPotentialConstantExprUnevaluated( + Expr *E, FunctionDecl const *FD, + SmallVectorImpl &Diags) { assert(!E->isValueDependent() && "Expression evaluator can't be called on a dependent expression."); @@ -15707,7 +15692,7 @@ return tryEvaluateBuiltinObjectSize(this, Type, Info, Result); } -static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, +static bool EvaluateBuiltinStrLen(Expr const *E, uint64_t &Result, EvalInfo &Info) { if (!E->getType()->hasPointerRepresentation() || !E->isPRValue()) return false; @@ -15720,8 +15705,8 @@ QualType CharTy = E->getType()->getPointeeType(); // Fast path: if it's a string literal, search the string value. - if (const StringLiteral *S = dyn_cast_or_null( - String.getLValueBase().dyn_cast())) { + if (StringLiteral const *S = dyn_cast_or_null( + String.getLValueBase().dyn_cast())) { StringRef Str = S->getBytes(); int64_t Off = String.Offset.getQuantity(); if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && Index: clang/lib/AST/ExprObjC.cpp =================================================================== --- clang/lib/AST/ExprObjC.cpp +++ clang/lib/AST/ExprObjC.cpp @@ -36,7 +36,7 @@ setDependence(computeDependence(this)); } -ObjCArrayLiteral *ObjCArrayLiteral::Create(const ASTContext &C, +ObjCArrayLiteral *ObjCArrayLiteral::Create(ASTContext const &C, ArrayRef Elements, QualType T, ObjCMethodDecl *Method, SourceRange SR) { @@ -44,7 +44,7 @@ return new (Mem) ObjCArrayLiteral(Elements, T, Method, SR); } -ObjCArrayLiteral *ObjCArrayLiteral::CreateEmpty(const ASTContext &C, +ObjCArrayLiteral *ObjCArrayLiteral::CreateEmpty(ASTContext const &C, unsigned NumElements) { void *Mem = C.Allocate(totalSizeToAlloc(NumElements)); return new (Mem) ObjCArrayLiteral(EmptyShell(), NumElements); @@ -75,7 +75,7 @@ } ObjCDictionaryLiteral * -ObjCDictionaryLiteral::Create(const ASTContext &C, +ObjCDictionaryLiteral::Create(ASTContext const &C, ArrayRef VK, bool HasPackExpansions, QualType T, ObjCMethodDecl *method, SourceRange SR) { @@ -85,7 +85,7 @@ } ObjCDictionaryLiteral * -ObjCDictionaryLiteral::CreateEmpty(const ASTContext &C, unsigned NumElements, +ObjCDictionaryLiteral::CreateEmpty(ASTContext const &C, unsigned NumElements, bool HasPackExpansions) { void *Mem = C.Allocate(totalSizeToAlloc( NumElements, HasPackExpansions ? NumElements : 0)); @@ -93,7 +93,7 @@ ObjCDictionaryLiteral(EmptyShell(), NumElements, HasPackExpansions); } -QualType ObjCPropertyRefExpr::getReceiverType(const ASTContext &ctx) const { +QualType ObjCPropertyRefExpr::getReceiverType(ASTContext const &ctx) const { if (isClassReceiver()) return ctx.getObjCInterfaceType(getClassReceiver()); @@ -172,7 +172,7 @@ } ObjCMessageExpr * -ObjCMessageExpr::Create(const ASTContext &Context, QualType T, ExprValueKind VK, +ObjCMessageExpr::Create(ASTContext const &Context, QualType T, ExprValueKind VK, SourceLocation LBracLoc, SourceLocation SuperLoc, bool IsInstanceSuper, QualType SuperType, Selector Sel, ArrayRef SelLocs, @@ -192,7 +192,7 @@ } ObjCMessageExpr * -ObjCMessageExpr::Create(const ASTContext &Context, QualType T, ExprValueKind VK, +ObjCMessageExpr::Create(ASTContext const &Context, QualType T, ExprValueKind VK, SourceLocation LBracLoc, TypeSourceInfo *Receiver, Selector Sel, ArrayRef SelLocs, ObjCMethodDecl *Method, ArrayRef Args, @@ -211,7 +211,7 @@ } ObjCMessageExpr * -ObjCMessageExpr::Create(const ASTContext &Context, QualType T, ExprValueKind VK, +ObjCMessageExpr::Create(ASTContext const &Context, QualType T, ExprValueKind VK, SourceLocation LBracLoc, Expr *Receiver, Selector Sel, ArrayRef SelLocs, ObjCMethodDecl *Method, ArrayRef Args, @@ -229,14 +229,14 @@ Args, RBracLoc, isImplicit); } -ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(const ASTContext &Context, +ObjCMessageExpr *ObjCMessageExpr::CreateEmpty(ASTContext const &Context, unsigned NumArgs, unsigned NumStoredSelLocs) { ObjCMessageExpr *Mem = alloc(Context, NumArgs, NumStoredSelLocs); return new (Mem) ObjCMessageExpr(EmptyShell(), NumArgs); } -ObjCMessageExpr *ObjCMessageExpr::alloc(const ASTContext &C, +ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext const &C, ArrayRef Args, SourceLocation RBraceLoc, ArrayRef SelLocs, @@ -248,7 +248,7 @@ return alloc(C, Args.size(), NumStoredSelLocs); } -ObjCMessageExpr *ObjCMessageExpr::alloc(const ASTContext &C, unsigned NumArgs, +ObjCMessageExpr *ObjCMessageExpr::alloc(ASTContext const &C, unsigned NumArgs, unsigned NumStoredSelLocs) { return (ObjCMessageExpr *)C.Allocate( totalSizeToAlloc(NumArgs + 1, NumStoredSelLocs), @@ -261,9 +261,8 @@ SelLocs.push_back(getSelectorLoc(i)); } - QualType ObjCMessageExpr::getCallReturnType(ASTContext &Ctx) const { - if (const ObjCMethodDecl *MD = getMethodDecl()) { + if (ObjCMethodDecl const *MD = getMethodDecl()) { QualType QT = MD->getReturnType(); if (QT == Ctx.getObjCInstanceType()) { // instancetype corresponds to expression types. @@ -292,7 +291,7 @@ Selector ObjCMessageExpr::getSelector() const { if (HasMethod) - return reinterpret_cast(SelectorOrMethod) + return reinterpret_cast(SelectorOrMethod) ->getSelector(); return Selector(SelectorOrMethod); } @@ -314,10 +313,10 @@ ObjCInterfaceDecl *ObjCMessageExpr::getReceiverInterface() const { QualType T = getReceiverType(); - if (const ObjCObjectPointerType *Ptr = T->getAs()) + if (ObjCObjectPointerType const *Ptr = T->getAs()) return Ptr->getInterfaceDecl(); - if (const ObjCObjectType *Ty = T->getAs()) + if (ObjCObjectType const *Ty = T->getAs()) return Ty->getInterface(); return nullptr; Index: clang/lib/AST/ExternalASTMerger.cpp =================================================================== --- clang/lib/AST/ExternalASTMerger.cpp +++ clang/lib/AST/ExternalASTMerger.cpp @@ -11,12 +11,12 @@ // //===----------------------------------------------------------------------===// +#include "clang/AST/ExternalASTMerger.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" -#include "clang/AST/ExternalASTMerger.h" using namespace clang; @@ -35,20 +35,20 @@ /// For the given DC, return the DC that is safe to perform lookups on. This is /// the DC we actually want to work with most of the time. -const DeclContext *CanonicalizeDC(const DeclContext *DC) { +DeclContext const *CanonicalizeDC(DeclContext const *DC) { if (isa(DC)) return DC->getRedeclContext(); return DC; } -Source -LookupSameContext(Source SourceTU, const DeclContext *DC, +Source +LookupSameContext(Source SourceTU, DeclContext const *DC, ASTImporter &ReverseImporter) { DC = CanonicalizeDC(DC); if (DC->isTranslationUnit()) { return SourceTU; } - Source SourceParentDC = + Source SourceParentDC = LookupSameContext(SourceTU, DC->getParent(), ReverseImporter); if (!SourceParentDC) { // If we couldn't find the parent DC in this TranslationUnit, give up. @@ -100,7 +100,7 @@ private: ExternalASTMerger &Parent; ASTImporter Reverse; - const ExternalASTMerger::OriginMap &FromOrigins; + ExternalASTMerger::OriginMap const &FromOrigins; /// @see ExternalASTMerger::ImporterSource::Temporary bool TemporarySource; /// Map of imported declarations back to the declarations they originated @@ -109,10 +109,11 @@ /// @see ExternalASTMerger::ImporterSource::Merger ExternalASTMerger *SourceMerger; llvm::raw_ostream &logs() { return Parent.logs(); } + public: LazyASTImporter(ExternalASTMerger &_Parent, ASTContext &ToContext, FileManager &ToFileManager, - const ExternalASTMerger::ImporterSource &S, + ExternalASTMerger::ImporterSource const &S, std::shared_ptr SharedState) : ASTImporter(ToContext, ToFileManager, S.getASTContext(), S.getFileManager(), @@ -199,32 +200,29 @@ ToOrigin[To] = From; if (auto *ToDC = dyn_cast(To)) { - const bool LoggingEnabled = Parent.LoggingEnabled(); + bool const LoggingEnabled = Parent.LoggingEnabled(); if (LoggingEnabled) - logs() << "(ExternalASTMerger*)" << (void*)&Parent - << " imported (DeclContext*)" << (void*)ToDC - << ", (ASTContext*)" << (void*)&getToContext() - << " from (DeclContext*)" << (void*)llvm::cast(From) - << ", (ASTContext*)" << (void*)&getFromContext() - << "\n"; + logs() << "(ExternalASTMerger*)" << (void *)&Parent + << " imported (DeclContext*)" << (void *)ToDC + << ", (ASTContext*)" << (void *)&getToContext() + << " from (DeclContext*)" + << (void *)llvm::cast(From) << ", (ASTContext*)" + << (void *)&getFromContext() << "\n"; Source FromDC( cast(From)->getPrimaryContext()); if (FromOrigins.count(FromDC) && Parent.HasImporterForOrigin(*FromOrigins.at(FromDC).AST)) { if (LoggingEnabled) - logs() << "(ExternalASTMerger*)" << (void*)&Parent + logs() << "(ExternalASTMerger*)" << (void *)&Parent << " forced origin (DeclContext*)" - << (void*)FromOrigins.at(FromDC).DC - << ", (ASTContext*)" - << (void*)FromOrigins.at(FromDC).AST - << "\n"; + << (void *)FromOrigins.at(FromDC).DC << ", (ASTContext*)" + << (void *)FromOrigins.at(FromDC).AST << "\n"; Parent.ForceRecordOrigin(ToDC, FromOrigins.at(FromDC)); } else { if (LoggingEnabled) - logs() << "(ExternalASTMerger*)" << (void*)&Parent - << " maybe recording origin (DeclContext*)" << (void*)FromDC - << ", (ASTContext*)" << (void*)&getFromContext() - << "\n"; + logs() << "(ExternalASTMerger*)" << (void *)&Parent + << " maybe recording origin (DeclContext*)" << (void *)FromDC + << ", (ASTContext*)" << (void *)&getFromContext() << "\n"; Parent.MaybeRecordOrigin(ToDC, {FromDC, &getFromContext()}); } } @@ -244,10 +242,10 @@ ASTImporter &GetReverse() { return Reverse; } }; -bool HasDeclOfSameType(llvm::ArrayRef Decls, const Candidate &C) { +bool HasDeclOfSameType(llvm::ArrayRef Decls, Candidate const &C) { if (isa(C.first.get())) return false; - return llvm::any_of(Decls, [&](const Candidate &D) { + return llvm::any_of(Decls, [&](Candidate const &D) { return C.first.get()->getKind() == D.first.get()->getKind(); }); } @@ -255,7 +253,7 @@ } // end namespace ASTImporter &ExternalASTMerger::ImporterForOrigin(ASTContext &OriginContext) { - for (const std::unique_ptr &I : Importers) + for (std::unique_ptr const &I : Importers) if (&I->getFromContext() == &OriginContext) return *I; llvm_unreachable("We should have an importer for this origin!"); @@ -263,21 +261,21 @@ namespace { LazyASTImporter &LazyImporterForOrigin(ExternalASTMerger &Merger, - ASTContext &OriginContext) { + ASTContext &OriginContext) { return static_cast( Merger.ImporterForOrigin(OriginContext)); } -} +} // namespace bool ExternalASTMerger::HasImporterForOrigin(ASTContext &OriginContext) { - for (const std::unique_ptr &I : Importers) + for (std::unique_ptr const &I : Importers) if (&I->getFromContext() == &OriginContext) return true; return false; } template -void ExternalASTMerger::ForEachMatchingDC(const DeclContext *DC, +void ExternalASTMerger::ForEachMatchingDC(DeclContext const *DC, CallbackType Callback) { if (Origins.count(DC)) { ExternalASTMerger::DCOrigin Origin = Origins[DC]; @@ -285,7 +283,7 @@ Callback(Importer, Importer.GetReverse(), Origin.DC); } else { bool DidCallback = false; - for (const std::unique_ptr &Importer : Importers) { + for (std::unique_ptr const &Importer : Importers) { Source SourceTU = Importer->getFromContext().getTranslationUnitDecl(); ASTImporter &Reverse = @@ -297,36 +295,39 @@ } } if (!DidCallback && LoggingEnabled()) - logs() << "(ExternalASTMerger*)" << (void*)this - << " asserting for (DeclContext*)" << (const void*)DC - << ", (ASTContext*)" << (void*)&Target.AST - << "\n"; + logs() << "(ExternalASTMerger*)" << (void *)this + << " asserting for (DeclContext*)" << (void const *)DC + << ", (ASTContext*)" << (void *)&Target.AST << "\n"; assert(DidCallback && "Couldn't find a source context matching our DC"); } } void ExternalASTMerger::CompleteType(TagDecl *Tag) { assert(Tag->hasExternalLexicalStorage()); - ForEachMatchingDC(Tag, [&](ASTImporter &Forward, ASTImporter &Reverse, - Source SourceDC) -> bool { - auto *SourceTag = const_cast(cast(SourceDC.get())); - if (SourceTag->hasExternalLexicalStorage()) - SourceTag->getASTContext().getExternalSource()->CompleteType(SourceTag); - if (!SourceTag->getDefinition()) - return false; - Forward.MapImported(SourceTag, Tag); - if (llvm::Error Err = Forward.ImportDefinition(SourceTag)) - llvm::consumeError(std::move(Err)); - Tag->setCompleteDefinition(SourceTag->isCompleteDefinition()); - return true; - }); + ForEachMatchingDC( + Tag, + [&](ASTImporter &Forward, ASTImporter &Reverse, + Source SourceDC) -> bool { + auto *SourceTag = const_cast(cast(SourceDC.get())); + if (SourceTag->hasExternalLexicalStorage()) + SourceTag->getASTContext().getExternalSource()->CompleteType( + SourceTag); + if (!SourceTag->getDefinition()) + return false; + Forward.MapImported(SourceTag, Tag); + if (llvm::Error Err = Forward.ImportDefinition(SourceTag)) + llvm::consumeError(std::move(Err)); + Tag->setCompleteDefinition(SourceTag->isCompleteDefinition()); + return true; + }); } void ExternalASTMerger::CompleteType(ObjCInterfaceDecl *Interface) { assert(Interface->hasExternalLexicalStorage()); ForEachMatchingDC( - Interface, [&](ASTImporter &Forward, ASTImporter &Reverse, - Source SourceDC) -> bool { + Interface, + [&](ASTImporter &Forward, ASTImporter &Reverse, + Source SourceDC) -> bool { auto *SourceInterface = const_cast( cast(SourceDC.get())); if (SourceInterface->hasExternalLexicalStorage()) @@ -347,7 +348,7 @@ bool FoundMatchingDC = false; ForEachMatchingDC(Interface, [&](ASTImporter &Forward, ASTImporter &Reverse, - Source SourceDC) -> bool { + Source SourceDC) -> bool { FoundMatchingDC = true; return true; }); @@ -355,7 +356,7 @@ } namespace { -bool IsSameDC(const DeclContext *D1, const DeclContext *D2) { +bool IsSameDC(DeclContext const *D1, DeclContext const *D2) { if (isa(D1) && isa(D2)) return true; // There are many cases where Objective-C is ambiguous. if (auto *T1 = dyn_cast(D1)) @@ -364,38 +365,40 @@ return true; return D1 == D2 || D1 == CanonicalizeDC(D2); } -} +} // namespace -void ExternalASTMerger::MaybeRecordOrigin(const DeclContext *ToDC, +void ExternalASTMerger::MaybeRecordOrigin(DeclContext const *ToDC, DCOrigin Origin) { LazyASTImporter &Importer = LazyImporterForOrigin(*this, *Origin.AST); ASTImporter &Reverse = Importer.GetReverse(); - Source FoundFromDC = + Source FoundFromDC = LookupSameContext(Origin.AST->getTranslationUnitDecl(), ToDC, Reverse); - const bool DoRecord = !FoundFromDC || !IsSameDC(FoundFromDC.get(), Origin.DC); + bool const DoRecord = !FoundFromDC || !IsSameDC(FoundFromDC.get(), Origin.DC); if (DoRecord) RecordOriginImpl(ToDC, Origin, Importer); if (LoggingEnabled()) - logs() << "(ExternalASTMerger*)" << (void*)this - << (DoRecord ? " decided " : " decided NOT") - << " to record origin (DeclContext*)" << (void*)Origin.DC - << ", (ASTContext*)" << (void*)&Origin.AST - << "\n"; + logs() << "(ExternalASTMerger*)" << (void *)this + << (DoRecord ? " decided " : " decided NOT") + << " to record origin (DeclContext*)" << (void *)Origin.DC + << ", (ASTContext*)" << (void *)&Origin.AST << "\n"; } -void ExternalASTMerger::ForceRecordOrigin(const DeclContext *ToDC, +void ExternalASTMerger::ForceRecordOrigin(DeclContext const *ToDC, DCOrigin Origin) { RecordOriginImpl(ToDC, Origin, ImporterForOrigin(*Origin.AST)); } -void ExternalASTMerger::RecordOriginImpl(const DeclContext *ToDC, DCOrigin Origin, +void ExternalASTMerger::RecordOriginImpl(DeclContext const *ToDC, + DCOrigin Origin, ASTImporter &Importer) { Origins[ToDC] = Origin; - Importer.ASTImporter::MapImported(cast(Origin.DC), const_cast(cast(ToDC))); + Importer.ASTImporter::MapImported(cast(Origin.DC), + const_cast(cast(ToDC))); } -ExternalASTMerger::ExternalASTMerger(const ImporterTarget &Target, - llvm::ArrayRef Sources) : LogStream(&llvm::nulls()), Target(Target) { +ExternalASTMerger::ExternalASTMerger(ImporterTarget const &Target, + llvm::ArrayRef Sources) + : LogStream(&llvm::nulls()), Target(Target) { SharedState = std::make_shared( *Target.AST.getTranslationUnitDecl()); AddSources(Sources); @@ -403,14 +406,14 @@ Decl *ExternalASTMerger::FindOriginalDecl(Decl *D) { assert(&D->getASTContext() == &Target.AST); - for (const auto &I : Importers) + for (auto const &I : Importers) if (auto Result = I->GetOriginalDecl(D)) return Result; return nullptr; } void ExternalASTMerger::AddSources(llvm::ArrayRef Sources) { - for (const ImporterSource &S : Sources) { + for (ImporterSource const &S : Sources) { assert(&S.getASTContext() != &Target.AST); // Check that the associated merger actually imports into the source AST. assert(!S.getMerger() || &S.getMerger()->Target.AST == &S.getASTContext()); @@ -421,24 +424,26 @@ void ExternalASTMerger::RemoveSources(llvm::ArrayRef Sources) { if (LoggingEnabled()) - for (const ImporterSource &S : Sources) + for (ImporterSource const &S : Sources) logs() << "(ExternalASTMerger*)" << (void *)this << " removing source (ASTContext*)" << (void *)&S.getASTContext() << "\n"; Importers.erase( - std::remove_if(Importers.begin(), Importers.end(), - [&Sources](std::unique_ptr &Importer) -> bool { - for (const ImporterSource &S : Sources) { - if (&Importer->getFromContext() == &S.getASTContext()) - return true; - } - return false; - }), + std::remove_if( + Importers.begin(), Importers.end(), + [&Sources](std::unique_ptr &Importer) -> bool { + for (const ImporterSource &S : Sources) { + if (&Importer->getFromContext() == &S.getASTContext()) + return true; + } + return false; + }), Importers.end()); - for (OriginMap::iterator OI = Origins.begin(), OE = Origins.end(); OI != OE; ) { - std::pair Origin = *OI; + for (OriginMap::iterator OI = Origins.begin(), OE = Origins.end(); + OI != OE;) { + std::pair Origin = *OI; bool Erase = false; - for (const ImporterSource &S : Sources) { + for (ImporterSource const &S : Sources) { if (&S.getASTContext() == Origin.second.AST) { Erase = true; break; @@ -476,19 +481,19 @@ return false; } -bool ExternalASTMerger::FindExternalVisibleDeclsByName(const DeclContext *DC, +bool ExternalASTMerger::FindExternalVisibleDeclsByName(DeclContext const *DC, DeclarationName Name) { llvm::SmallVector Decls; llvm::SmallVector Candidates; - auto FilterFoundDecl = [&Candidates](const Candidate &C) { - if (!HasDeclOfSameType(Candidates, C)) - Candidates.push_back(C); + auto FilterFoundDecl = [&Candidates](Candidate const &C) { + if (!HasDeclOfSameType(Candidates, C)) + Candidates.push_back(C); }; ForEachMatchingDC(DC, [&](ASTImporter &Forward, ASTImporter &Reverse, - Source SourceDC) -> bool { + Source SourceDC) -> bool { auto FromNameOrErr = Reverse.Import(Name); if (!FromNameOrErr) { llvm::consumeError(FromNameOrErr.takeError()); @@ -506,7 +511,7 @@ return false; Decls.reserve(Candidates.size()); - for (const Candidate &C : Candidates) { + for (Candidate const &C : Candidates) { Decl *LookupRes = C.first.get(); ASTImporter *Importer = C.second; auto NDOrErr = Importer->Import(LookupRes); @@ -526,21 +531,22 @@ } void ExternalASTMerger::FindExternalLexicalDecls( - const DeclContext *DC, llvm::function_ref IsKindWeWant, + DeclContext const *DC, llvm::function_ref IsKindWeWant, SmallVectorImpl &Result) { - ForEachMatchingDC(DC, [&](ASTImporter &Forward, ASTImporter &Reverse, - Source SourceDC) -> bool { - for (const Decl *SourceDecl : SourceDC.get()->decls()) { - if (IsKindWeWant(SourceDecl->getKind())) { - auto ImportedDeclOrErr = Forward.Import(SourceDecl); - if (ImportedDeclOrErr) - assert(!(*ImportedDeclOrErr) || - IsSameDC((*ImportedDeclOrErr)->getDeclContext(), DC)); - else - llvm::consumeError(ImportedDeclOrErr.takeError()); - } - } - return false; - }); + ForEachMatchingDC( + DC, + [&](ASTImporter &Forward, ASTImporter &Reverse, + Source SourceDC) -> bool { + for (const Decl *SourceDecl : SourceDC.get()->decls()) { + if (IsKindWeWant(SourceDecl->getKind())) { + auto ImportedDeclOrErr = Forward.Import(SourceDecl); + if (ImportedDeclOrErr) + assert(!(*ImportedDeclOrErr) || + IsSameDC((*ImportedDeclOrErr)->getDeclContext(), DC)); + else + llvm::consumeError(ImportedDeclOrErr.takeError()); + } + } + return false; + }); } - Index: clang/lib/AST/ExternalASTSource.cpp =================================================================== --- clang/lib/AST/ExternalASTSource.cpp +++ clang/lib/AST/ExternalASTSource.cpp @@ -36,7 +36,7 @@ } ExternalASTSource::ExtKind -ExternalASTSource::hasExternalDefinitions(const Decl *D) { +ExternalASTSource::hasExternalDefinitions(Decl const *D) { return EK_ReplyHazy; } @@ -44,7 +44,7 @@ unsigned Length, SmallVectorImpl &Decls) {} -void ExternalASTSource::CompleteRedeclChain(const Decl *D) {} +void ExternalASTSource::CompleteRedeclChain(Decl const *D) {} void ExternalASTSource::CompleteType(TagDecl *Tag) {} @@ -61,24 +61,20 @@ void ExternalASTSource::PrintStats() {} bool ExternalASTSource::layoutRecordType( - const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment, - llvm::DenseMap &FieldOffsets, - llvm::DenseMap &BaseOffsets, - llvm::DenseMap &VirtualBaseOffsets) { + RecordDecl const *Record, uint64_t &Size, uint64_t &Alignment, + llvm::DenseMap &FieldOffsets, + llvm::DenseMap &BaseOffsets, + llvm::DenseMap &VirtualBaseOffsets) { return false; } -Decl *ExternalASTSource::GetExternalDecl(uint32_t ID) { - return nullptr; -} +Decl *ExternalASTSource::GetExternalDecl(uint32_t ID) { return nullptr; } Selector ExternalASTSource::GetExternalSelector(uint32_t ID) { return Selector(); } -uint32_t ExternalASTSource::GetNumExternalSelectors() { - return 0; -} +uint32_t ExternalASTSource::GetNumExternalSelectors() { return 0; } Stmt *ExternalASTSource::GetExternalDeclStmt(uint64_t Offset) { return nullptr; @@ -94,16 +90,15 @@ return nullptr; } -bool -ExternalASTSource::FindExternalVisibleDeclsByName(const DeclContext *DC, - DeclarationName Name) { +bool ExternalASTSource::FindExternalVisibleDeclsByName(DeclContext const *DC, + DeclarationName Name) { return false; } -void ExternalASTSource::completeVisibleDeclsMap(const DeclContext *DC) {} +void ExternalASTSource::completeVisibleDeclsMap(DeclContext const *DC) {} void ExternalASTSource::FindExternalLexicalDecls( - const DeclContext *DC, llvm::function_ref IsKindWeWant, + DeclContext const *DC, llvm::function_ref IsKindWeWant, SmallVectorImpl &Result) {} void ExternalASTSource::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {} Index: clang/lib/AST/FormatString.cpp =================================================================== --- clang/lib/AST/FormatString.cpp +++ clang/lib/AST/FormatString.cpp @@ -17,12 +17,12 @@ #include "llvm/Support/ConvertUTF.h" using clang::analyze_format_string::ArgType; -using clang::analyze_format_string::FormatStringHandler; +using clang::analyze_format_string::ConversionSpecifier; using clang::analyze_format_string::FormatSpecifier; +using clang::analyze_format_string::FormatStringHandler; using clang::analyze_format_string::LengthModifier; using clang::analyze_format_string::OptionalAmount; using clang::analyze_format_string::PositionContext; -using clang::analyze_format_string::ConversionSpecifier; using namespace clang; // Key function to FormatStringHandler. @@ -33,15 +33,15 @@ // scanf format strings. //===----------------------------------------------------------------------===// -OptionalAmount -clang::analyze_format_string::ParseAmount(const char *&Beg, const char *E) { - const char *I = Beg; - UpdateOnReturn UpdateBeg(Beg, I); +OptionalAmount clang::analyze_format_string::ParseAmount(char const *&Beg, + char const *E) { + char const *I = Beg; + UpdateOnReturn UpdateBeg(Beg, I); unsigned accumulator = 0; bool hasDigits = false; - for ( ; I != E; ++I) { + for (; I != E; ++I) { char c = *I; if (c >= '0' && c <= '9') { hasDigits = true; @@ -51,7 +51,7 @@ if (hasDigits) return OptionalAmount(OptionalAmount::Constant, accumulator, Beg, I - Beg, - false); + false); break; } @@ -59,10 +59,8 @@ return OptionalAmount(); } -OptionalAmount -clang::analyze_format_string::ParseNonPositionAmount(const char *&Beg, - const char *E, - unsigned &argIndex) { +OptionalAmount clang::analyze_format_string::ParseNonPositionAmount( + char const *&Beg, char const *E, unsigned &argIndex) { if (*Beg == '*') { ++Beg; return OptionalAmount(OptionalAmount::Arg, argIndex++, Beg, 0, false); @@ -71,15 +69,12 @@ return ParseAmount(Beg, E); } -OptionalAmount -clang::analyze_format_string::ParsePositionAmount(FormatStringHandler &H, - const char *Start, - const char *&Beg, - const char *E, - PositionContext p) { +OptionalAmount clang::analyze_format_string::ParsePositionAmount( + FormatStringHandler &H, char const *Start, char const *&Beg, char const *E, + PositionContext p) { if (*Beg == '*') { - const char *I = Beg + 1; - const OptionalAmount &Amt = ParseAmount(I, E); + char const *I = Beg + 1; + OptionalAmount const &Amt = ParseAmount(I, E); if (Amt.getHowSpecified() == OptionalAmount::NotSpecified) { H.HandleInvalidPosition(Beg, I - Beg, p); @@ -103,7 +98,7 @@ return OptionalAmount(false); } - const char *Tmp = Beg; + char const *Tmp = Beg; Beg = ++I; return OptionalAmount(OptionalAmount::Arg, Amt.getConstantAmount() - 1, @@ -117,21 +112,15 @@ return ParseAmount(Beg, E); } - -bool -clang::analyze_format_string::ParseFieldWidth(FormatStringHandler &H, - FormatSpecifier &CS, - const char *Start, - const char *&Beg, const char *E, - unsigned *argIndex) { +bool clang::analyze_format_string::ParseFieldWidth( + FormatStringHandler &H, FormatSpecifier &CS, char const *Start, + char const *&Beg, char const *E, unsigned *argIndex) { // FIXME: Support negative field widths. if (argIndex) { CS.setFieldWidth(ParseNonPositionAmount(Beg, E, *argIndex)); - } - else { - const OptionalAmount Amt = - ParsePositionAmount(H, Start, Beg, E, - analyze_format_string::FieldWidthPos); + } else { + const OptionalAmount Amt = ParsePositionAmount( + H, Start, Beg, E, analyze_format_string::FieldWidthPos); if (Amt.isInvalid()) return true; @@ -140,15 +129,14 @@ return false; } -bool -clang::analyze_format_string::ParseArgPosition(FormatStringHandler &H, - FormatSpecifier &FS, - const char *Start, - const char *&Beg, - const char *E) { - const char *I = Beg; +bool clang::analyze_format_string::ParseArgPosition(FormatStringHandler &H, + FormatSpecifier &FS, + char const *Start, + char const *&Beg, + char const *E) { + char const *I = Beg; - const OptionalAmount &Amt = ParseAmount(I, E); + OptionalAmount const &Amt = ParseAmount(I, E); if (I == E) { // No more characters left? @@ -177,16 +165,15 @@ return false; } -bool -clang::analyze_format_string::ParseVectorModifier(FormatStringHandler &H, - FormatSpecifier &FS, - const char *&I, - const char *E, - const LangOptions &LO) { +bool clang::analyze_format_string::ParseVectorModifier(FormatStringHandler &H, + FormatSpecifier &FS, + char const *&I, + char const *E, + LangOptions const &LO) { if (!LO.OpenCL) return false; - const char *Start = I; + char const *Start = I; if (*I == 'v') { ++I; @@ -207,86 +194,102 @@ return false; } -bool -clang::analyze_format_string::ParseLengthModifier(FormatSpecifier &FS, - const char *&I, - const char *E, - const LangOptions &LO, - bool IsScanf) { +bool clang::analyze_format_string::ParseLengthModifier(FormatSpecifier &FS, + char const *&I, + char const *E, + LangOptions const &LO, + bool IsScanf) { LengthModifier::Kind lmKind = LengthModifier::None; - const char *lmPosition = I; + char const *lmPosition = I; switch (*I) { - default: - return false; - case 'h': + default: + return false; + case 'h': + ++I; + if (I != E && *I == 'h') { ++I; - if (I != E && *I == 'h') { - ++I; - lmKind = LengthModifier::AsChar; - } else if (I != E && *I == 'l' && LO.OpenCL) { - ++I; - lmKind = LengthModifier::AsShortLong; - } else { - lmKind = LengthModifier::AsShort; - } - break; - case 'l': + lmKind = LengthModifier::AsChar; + } else if (I != E && *I == 'l' && LO.OpenCL) { + ++I; + lmKind = LengthModifier::AsShortLong; + } else { + lmKind = LengthModifier::AsShort; + } + break; + case 'l': + ++I; + if (I != E && *I == 'l') { + ++I; + lmKind = LengthModifier::AsLongLong; + } else { + lmKind = LengthModifier::AsLong; + } + break; + case 'j': + lmKind = LengthModifier::AsIntMax; + ++I; + break; + case 'z': + lmKind = LengthModifier::AsSizeT; + ++I; + break; + case 't': + lmKind = LengthModifier::AsPtrDiff; + ++I; + break; + case 'L': + lmKind = LengthModifier::AsLongDouble; + ++I; + break; + case 'q': + lmKind = LengthModifier::AsQuad; + ++I; + break; + case 'a': + if (IsScanf && !LO.C99 && !LO.CPlusPlus11) { + // For scanf in C90, look at the next character to see if this should + // be parsed as the GNU extension 'a' length modifier. If not, this + // will be parsed as a conversion specifier. ++I; - if (I != E && *I == 'l') { - ++I; - lmKind = LengthModifier::AsLongLong; - } else { - lmKind = LengthModifier::AsLong; + if (I != E && (*I == 's' || *I == 'S' || *I == '[')) { + lmKind = LengthModifier::AsAllocate; + break; } + --I; + } + return false; + case 'm': + if (IsScanf) { + lmKind = LengthModifier::AsMAllocate; + ++I; break; - case 'j': lmKind = LengthModifier::AsIntMax; ++I; break; - case 'z': lmKind = LengthModifier::AsSizeT; ++I; break; - case 't': lmKind = LengthModifier::AsPtrDiff; ++I; break; - case 'L': lmKind = LengthModifier::AsLongDouble; ++I; break; - case 'q': lmKind = LengthModifier::AsQuad; ++I; break; - case 'a': - if (IsScanf && !LO.C99 && !LO.CPlusPlus11) { - // For scanf in C90, look at the next character to see if this should - // be parsed as the GNU extension 'a' length modifier. If not, this - // will be parsed as a conversion specifier. - ++I; - if (I != E && (*I == 's' || *I == 'S' || *I == '[')) { - lmKind = LengthModifier::AsAllocate; - break; - } - --I; - } - return false; - case 'm': - if (IsScanf) { - lmKind = LengthModifier::AsMAllocate; - ++I; + } + return false; + // printf: AsInt64, AsInt32, AsInt3264 + // scanf: AsInt64 + case 'I': + if (I + 1 != E && I + 2 != E) { + if (I[1] == '6' && I[2] == '4') { + I += 3; + lmKind = LengthModifier::AsInt64; break; } - return false; - // printf: AsInt64, AsInt32, AsInt3264 - // scanf: AsInt64 - case 'I': - if (I + 1 != E && I + 2 != E) { - if (I[1] == '6' && I[2] == '4') { - I += 3; - lmKind = LengthModifier::AsInt64; - break; - } - if (IsScanf) - return false; - - if (I[1] == '3' && I[2] == '2') { - I += 3; - lmKind = LengthModifier::AsInt32; - break; - } + if (IsScanf) + return false; + + if (I[1] == '3' && I[2] == '2') { + I += 3; + lmKind = LengthModifier::AsInt32; + break; } - ++I; - lmKind = LengthModifier::AsInt3264; - break; - case 'w': - lmKind = LengthModifier::AsWide; ++I; break; + } + ++I; + lmKind = LengthModifier::AsInt3264; + break; + case 'w': + lmKind = LengthModifier::AsWide; + ++I; + break; } LengthModifier lm(lmPosition, lmKind); FS.setLengthModifier(lm); @@ -294,14 +297,14 @@ } bool clang::analyze_format_string::ParseUTF8InvalidSpecifier( - const char *SpecifierBegin, const char *FmtStrEnd, unsigned &Len) { + char const *SpecifierBegin, char const *FmtStrEnd, unsigned &Len) { if (SpecifierBegin + 1 >= FmtStrEnd) return false; - const llvm::UTF8 *SB = - reinterpret_cast(SpecifierBegin + 1); - const llvm::UTF8 *SE = reinterpret_cast(FmtStrEnd); - const char FirstByte = *SB; + llvm::UTF8 const *SB = + reinterpret_cast(SpecifierBegin + 1); + llvm::UTF8 const *SE = reinterpret_cast(FmtStrEnd); + char const FirstByte = *SB; // If the invalid specifier is a multibyte UTF-8 string, return the // total length accordingly so that the conversion specifier can be @@ -324,7 +327,7 @@ ArgType::matchesType(ASTContext &C, QualType argTy) const { if (Ptr) { // It has to be a pointer. - const PointerType *PT = argTy->getAs(); + PointerType const *PT = argTy->getAs(); if (!PT) return NoMatch; @@ -336,157 +339,157 @@ } switch (K) { - case InvalidTy: - llvm_unreachable("ArgType must be valid"); + case InvalidTy: + llvm_unreachable("ArgType must be valid"); - case UnknownTy: - return Match; + case UnknownTy: + return Match; - case AnyCharTy: { - if (const EnumType *ETy = argTy->getAs()) { - // If the enum is incomplete we know nothing about the underlying type. - // Assume that it's 'int'. - if (!ETy->getDecl()->isComplete()) - return NoMatch; - argTy = ETy->getDecl()->getIntegerType(); + case AnyCharTy: { + if (EnumType const *ETy = argTy->getAs()) { + // If the enum is incomplete we know nothing about the underlying type. + // Assume that it's 'int'. + if (!ETy->getDecl()->isComplete()) + return NoMatch; + argTy = ETy->getDecl()->getIntegerType(); + } + + if (BuiltinType const *BT = argTy->getAs()) + switch (BT->getKind()) { + default: + break; + case BuiltinType::Char_S: + case BuiltinType::SChar: + case BuiltinType::UChar: + case BuiltinType::Char_U: + case BuiltinType::Bool: + return Match; } + return NoMatch; + } - if (const BuiltinType *BT = argTy->getAs()) - switch (BT->getKind()) { - default: - break; - case BuiltinType::Char_S: - case BuiltinType::SChar: - case BuiltinType::UChar: - case BuiltinType::Char_U: - case BuiltinType::Bool: - return Match; - } - return NoMatch; + case SpecificTy: { + if (EnumType const *ETy = argTy->getAs()) { + // If the enum is incomplete we know nothing about the underlying type. + // Assume that it's 'int'. + if (!ETy->getDecl()->isComplete()) + argTy = C.IntTy; + else + argTy = ETy->getDecl()->getIntegerType(); } + argTy = C.getCanonicalType(argTy).getUnqualifiedType(); - case SpecificTy: { - if (const EnumType *ETy = argTy->getAs()) { - // If the enum is incomplete we know nothing about the underlying type. - // Assume that it's 'int'. - if (!ETy->getDecl()->isComplete()) - argTy = C.IntTy; - else - argTy = ETy->getDecl()->getIntegerType(); + if (T == argTy) + return Match; + // Check for "compatible types". + if (BuiltinType const *BT = argTy->getAs()) + switch (BT->getKind()) { + default: + break; + case BuiltinType::Char_S: + case BuiltinType::SChar: + case BuiltinType::Char_U: + case BuiltinType::UChar: + case BuiltinType::Bool: + if (T == C.UnsignedShortTy || T == C.ShortTy) + return NoMatchTypeConfusion; + return T == C.UnsignedCharTy || T == C.SignedCharTy ? Match : NoMatch; + case BuiltinType::Short: + return T == C.UnsignedShortTy ? Match : NoMatch; + case BuiltinType::UShort: + return T == C.ShortTy ? Match : NoMatch; + case BuiltinType::Int: + return T == C.UnsignedIntTy ? Match : NoMatch; + case BuiltinType::UInt: + return T == C.IntTy ? Match : NoMatch; + case BuiltinType::Long: + return T == C.UnsignedLongTy ? Match : NoMatch; + case BuiltinType::ULong: + return T == C.LongTy ? Match : NoMatch; + case BuiltinType::LongLong: + return T == C.UnsignedLongLongTy ? Match : NoMatch; + case BuiltinType::ULongLong: + return T == C.LongLongTy ? Match : NoMatch; } - argTy = C.getCanonicalType(argTy).getUnqualifiedType(); + return NoMatch; + } - if (T == argTy) - return Match; - // Check for "compatible types". - if (const BuiltinType *BT = argTy->getAs()) - switch (BT->getKind()) { - default: - break; - case BuiltinType::Char_S: - case BuiltinType::SChar: - case BuiltinType::Char_U: - case BuiltinType::UChar: - case BuiltinType::Bool: - if (T == C.UnsignedShortTy || T == C.ShortTy) - return NoMatchTypeConfusion; - return T == C.UnsignedCharTy || T == C.SignedCharTy ? Match - : NoMatch; - case BuiltinType::Short: - return T == C.UnsignedShortTy ? Match : NoMatch; - case BuiltinType::UShort: - return T == C.ShortTy ? Match : NoMatch; - case BuiltinType::Int: - return T == C.UnsignedIntTy ? Match : NoMatch; - case BuiltinType::UInt: - return T == C.IntTy ? Match : NoMatch; - case BuiltinType::Long: - return T == C.UnsignedLongTy ? Match : NoMatch; - case BuiltinType::ULong: - return T == C.LongTy ? Match : NoMatch; - case BuiltinType::LongLong: - return T == C.UnsignedLongLongTy ? Match : NoMatch; - case BuiltinType::ULongLong: - return T == C.LongLongTy ? Match : NoMatch; - } + case CStrTy: { + PointerType const *PT = argTy->getAs(); + if (!PT) return NoMatch; - } + QualType pointeeTy = PT->getPointeeType(); + if (BuiltinType const *BT = pointeeTy->getAs()) + switch (BT->getKind()) { + case BuiltinType::Char_U: + case BuiltinType::UChar: + case BuiltinType::Char_S: + case BuiltinType::SChar: + return Match; + default: + break; + } - case CStrTy: { - const PointerType *PT = argTy->getAs(); - if (!PT) - return NoMatch; - QualType pointeeTy = PT->getPointeeType(); - if (const BuiltinType *BT = pointeeTy->getAs()) - switch (BT->getKind()) { - case BuiltinType::Char_U: - case BuiltinType::UChar: - case BuiltinType::Char_S: - case BuiltinType::SChar: - return Match; - default: - break; - } + return NoMatch; + } + case WCStrTy: { + PointerType const *PT = argTy->getAs(); + if (!PT) return NoMatch; - } - - case WCStrTy: { - const PointerType *PT = argTy->getAs(); - if (!PT) - return NoMatch; - QualType pointeeTy = + QualType pointeeTy = C.getCanonicalType(PT->getPointeeType()).getUnqualifiedType(); - return pointeeTy == C.getWideCharType() ? Match : NoMatch; - } + return pointeeTy == C.getWideCharType() ? Match : NoMatch; + } - case WIntTy: { - QualType WInt = C.getCanonicalType(C.getWIntType()).getUnqualifiedType(); + case WIntTy: { + QualType WInt = C.getCanonicalType(C.getWIntType()).getUnqualifiedType(); - if (C.getCanonicalType(argTy).getUnqualifiedType() == WInt) - return Match; + if (C.getCanonicalType(argTy).getUnqualifiedType() == WInt) + return Match; - QualType PromoArg = argTy->isPromotableIntegerType() - ? C.getPromotedIntegerType(argTy) - : argTy; - PromoArg = C.getCanonicalType(PromoArg).getUnqualifiedType(); + QualType PromoArg = argTy->isPromotableIntegerType() + ? C.getPromotedIntegerType(argTy) + : argTy; + PromoArg = C.getCanonicalType(PromoArg).getUnqualifiedType(); - // If the promoted argument is the corresponding signed type of the - // wint_t type, then it should match. - if (PromoArg->hasSignedIntegerRepresentation() && - C.getCorrespondingUnsignedType(PromoArg) == WInt) - return Match; + // If the promoted argument is the corresponding signed type of the + // wint_t type, then it should match. + if (PromoArg->hasSignedIntegerRepresentation() && + C.getCorrespondingUnsignedType(PromoArg) == WInt) + return Match; + + return WInt == PromoArg ? Match : NoMatch; + } - return WInt == PromoArg ? Match : NoMatch; + case CPointerTy: + if (argTy->isVoidPointerType()) { + return Match; + } + if (argTy->isPointerType() || argTy->isObjCObjectPointerType() || + argTy->isBlockPointerType() || argTy->isNullPtrType()) { + return NoMatchPedantic; + } else { + return NoMatch; } - case CPointerTy: - if (argTy->isVoidPointerType()) { - return Match; - } if (argTy->isPointerType() || argTy->isObjCObjectPointerType() || - argTy->isBlockPointerType() || argTy->isNullPtrType()) { - return NoMatchPedantic; - } else { - return NoMatch; - } + case ObjCPointerTy: { + if (argTy->getAs() || + argTy->getAs()) + return Match; - case ObjCPointerTy: { - if (argTy->getAs() || - argTy->getAs()) + // Handle implicit toll-free bridging. + if (PointerType const *PT = argTy->getAs()) { + // Things such as CFTypeRef are really just opaque pointers + // to C structs representing CF types that can often be bridged + // to Objective-C objects. Since the compiler doesn't know which + // structs can be toll-free bridged, we just accept them all. + QualType pointee = PT->getPointeeType(); + if (pointee->getAsStructureType() || pointee->isVoidType()) return Match; - - // Handle implicit toll-free bridging. - if (const PointerType *PT = argTy->getAs()) { - // Things such as CFTypeRef are really just opaque pointers - // to C structs representing CF types that can often be bridged - // to Objective-C objects. Since the compiler doesn't know which - // structs can be toll-free bridged, we just accept them all. - QualType pointee = PT->getPointeeType(); - if (pointee->getAsStructureType() || pointee->isVoidType()) - return Match; - } - return NoMatch; } + return NoMatch; + } } llvm_unreachable("Invalid ArgType Kind!"); @@ -504,32 +507,32 @@ QualType ArgType::getRepresentativeType(ASTContext &C) const { QualType Res; switch (K) { - case InvalidTy: - llvm_unreachable("No representative type for Invalid ArgType"); - case UnknownTy: - llvm_unreachable("No representative type for Unknown ArgType"); - case AnyCharTy: - Res = C.CharTy; - break; - case SpecificTy: - Res = T; - break; - case CStrTy: - Res = C.getPointerType(C.CharTy); - break; - case WCStrTy: - Res = C.getPointerType(C.getWideCharType()); - break; - case ObjCPointerTy: - Res = C.ObjCBuiltinIdTy; - break; - case CPointerTy: - Res = C.VoidPtrTy; - break; - case WIntTy: { - Res = C.getWIntType(); - break; - } + case InvalidTy: + llvm_unreachable("No representative type for Invalid ArgType"); + case UnknownTy: + llvm_unreachable("No representative type for Unknown ArgType"); + case AnyCharTy: + Res = C.CharTy; + break; + case SpecificTy: + Res = T; + break; + case CStrTy: + Res = C.getPointerType(C.CharTy); + break; + case WCStrTy: + Res = C.getPointerType(C.getWideCharType()); + break; + case ObjCPointerTy: + Res = C.ObjCBuiltinIdTy; + break; + case CPointerTy: + Res = C.VoidPtrTy; + break; + case WIntTy: { + Res = C.getWIntType(); + break; + } } if (Ptr) @@ -546,7 +549,7 @@ Alias = Name; if (Ptr) { // If ArgType is actually a pointer to T, append an asterisk. - Alias += (Alias[Alias.size()-1] == '*') ? "*" : " *"; + Alias += (Alias[Alias.size() - 1] == '*') ? "*" : " *"; } // If Alias is the same as the underlying type, e.g. wchar_t, then drop it. if (S == Alias) @@ -558,7 +561,6 @@ return std::string("'") + S + "'"; } - //===----------------------------------------------------------------------===// // Methods on OptionalAmount. //===----------------------------------------------------------------------===// @@ -572,8 +574,7 @@ // Methods on LengthModifier. //===----------------------------------------------------------------------===// -const char * -analyze_format_string::LengthModifier::toString() const { +char const *analyze_format_string::LengthModifier::toString() const { switch (kind) { case AsChar: return "hh"; @@ -617,53 +618,86 @@ // Methods on ConversionSpecifier. //===----------------------------------------------------------------------===// -const char *ConversionSpecifier::toString() const { +char const *ConversionSpecifier::toString() const { switch (kind) { - case dArg: return "d"; - case DArg: return "D"; - case iArg: return "i"; - case oArg: return "o"; - case OArg: return "O"; - case uArg: return "u"; - case UArg: return "U"; - case xArg: return "x"; - case XArg: return "X"; - case fArg: return "f"; - case FArg: return "F"; - case eArg: return "e"; - case EArg: return "E"; - case gArg: return "g"; - case GArg: return "G"; - case aArg: return "a"; - case AArg: return "A"; - case cArg: return "c"; - case sArg: return "s"; - case pArg: return "p"; + case dArg: + return "d"; + case DArg: + return "D"; + case iArg: + return "i"; + case oArg: + return "o"; + case OArg: + return "O"; + case uArg: + return "u"; + case UArg: + return "U"; + case xArg: + return "x"; + case XArg: + return "X"; + case fArg: + return "f"; + case FArg: + return "F"; + case eArg: + return "e"; + case EArg: + return "E"; + case gArg: + return "g"; + case GArg: + return "G"; + case aArg: + return "a"; + case AArg: + return "A"; + case cArg: + return "c"; + case sArg: + return "s"; + case pArg: + return "p"; case PArg: return "P"; - case nArg: return "n"; - case PercentArg: return "%"; - case ScanListArg: return "["; - case InvalidSpecifier: return nullptr; + case nArg: + return "n"; + case PercentArg: + return "%"; + case ScanListArg: + return "["; + case InvalidSpecifier: + return nullptr; // POSIX unicode extensions. - case CArg: return "C"; - case SArg: return "S"; + case CArg: + return "C"; + case SArg: + return "S"; // Objective-C specific specifiers. - case ObjCObjArg: return "@"; + case ObjCObjArg: + return "@"; // FreeBSD kernel specific specifiers. - case FreeBSDbArg: return "b"; - case FreeBSDDArg: return "D"; - case FreeBSDrArg: return "r"; - case FreeBSDyArg: return "y"; + case FreeBSDbArg: + return "b"; + case FreeBSDDArg: + return "D"; + case FreeBSDrArg: + return "r"; + case FreeBSDyArg: + return "y"; // GlibC specific specifiers. - case PrintErrno: return "m"; + case PrintErrno: + return "m"; // MS specific specifiers. - case ZArg: return "Z"; + case ZArg: + return "Z"; } return nullptr; } @@ -702,7 +736,7 @@ return; case Arg: if (UsesDotPrefix) - os << "."; + os << "."; if (usesPositionalArg()) os << "*" << getPositionalArgIndex() << "$"; else @@ -710,252 +744,252 @@ break; case Constant: if (UsesDotPrefix) - os << "."; + os << "."; os << amt; break; } } -bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target, - const LangOptions &LO) const { +bool FormatSpecifier::hasValidLengthModifier(TargetInfo const &Target, + LangOptions const &LO) const { switch (LM.getKind()) { - case LengthModifier::None: - return true; - - // Handle most integer flags - case LengthModifier::AsShort: - // Length modifier only applies to FP vectors. - if (LO.OpenCL && CS.isDoubleArg()) - return !VectorNumElts.isInvalid(); - - if (Target.getTriple().isOSMSVCRT()) { - switch (CS.getKind()) { - case ConversionSpecifier::cArg: - case ConversionSpecifier::CArg: - case ConversionSpecifier::sArg: - case ConversionSpecifier::SArg: - case ConversionSpecifier::ZArg: - return true; - default: - break; - } - } - LLVM_FALLTHROUGH; - case LengthModifier::AsChar: - case LengthModifier::AsLongLong: - case LengthModifier::AsQuad: - case LengthModifier::AsIntMax: - case LengthModifier::AsSizeT: - case LengthModifier::AsPtrDiff: - switch (CS.getKind()) { - case ConversionSpecifier::dArg: - case ConversionSpecifier::DArg: - case ConversionSpecifier::iArg: - case ConversionSpecifier::oArg: - case ConversionSpecifier::OArg: - case ConversionSpecifier::uArg: - case ConversionSpecifier::UArg: - case ConversionSpecifier::xArg: - case ConversionSpecifier::XArg: - case ConversionSpecifier::nArg: - return true; - case ConversionSpecifier::FreeBSDrArg: - case ConversionSpecifier::FreeBSDyArg: - return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS4(); - default: - return false; - } - - case LengthModifier::AsShortLong: - return LO.OpenCL && !VectorNumElts.isInvalid(); - - // Handle 'l' flag - case LengthModifier::AsLong: // or AsWideChar - if (CS.isDoubleArg()) { - // Invalid for OpenCL FP scalars. - if (LO.OpenCL && VectorNumElts.isInvalid()) - return false; - return true; - } + case LengthModifier::None: + return true; - switch (CS.getKind()) { - case ConversionSpecifier::dArg: - case ConversionSpecifier::DArg: - case ConversionSpecifier::iArg: - case ConversionSpecifier::oArg: - case ConversionSpecifier::OArg: - case ConversionSpecifier::uArg: - case ConversionSpecifier::UArg: - case ConversionSpecifier::xArg: - case ConversionSpecifier::XArg: - case ConversionSpecifier::nArg: - case ConversionSpecifier::cArg: - case ConversionSpecifier::sArg: - case ConversionSpecifier::ScanListArg: - case ConversionSpecifier::ZArg: - return true; - case ConversionSpecifier::FreeBSDrArg: - case ConversionSpecifier::FreeBSDyArg: - return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS4(); - default: - return false; - } + // Handle most integer flags + case LengthModifier::AsShort: + // Length modifier only applies to FP vectors. + if (LO.OpenCL && CS.isDoubleArg()) + return !VectorNumElts.isInvalid(); - case LengthModifier::AsLongDouble: + if (Target.getTriple().isOSMSVCRT()) { switch (CS.getKind()) { - case ConversionSpecifier::aArg: - case ConversionSpecifier::AArg: - case ConversionSpecifier::fArg: - case ConversionSpecifier::FArg: - case ConversionSpecifier::eArg: - case ConversionSpecifier::EArg: - case ConversionSpecifier::gArg: - case ConversionSpecifier::GArg: - return true; - // GNU libc extension. - case ConversionSpecifier::dArg: - case ConversionSpecifier::iArg: - case ConversionSpecifier::oArg: - case ConversionSpecifier::uArg: - case ConversionSpecifier::xArg: - case ConversionSpecifier::XArg: - return !Target.getTriple().isOSDarwin() && - !Target.getTriple().isOSWindows(); - default: - return false; - } - - case LengthModifier::AsAllocate: - switch (CS.getKind()) { - case ConversionSpecifier::sArg: - case ConversionSpecifier::SArg: - case ConversionSpecifier::ScanListArg: - return true; - default: - return false; + case ConversionSpecifier::cArg: + case ConversionSpecifier::CArg: + case ConversionSpecifier::sArg: + case ConversionSpecifier::SArg: + case ConversionSpecifier::ZArg: + return true; + default: + break; } + } + LLVM_FALLTHROUGH; + case LengthModifier::AsChar: + case LengthModifier::AsLongLong: + case LengthModifier::AsQuad: + case LengthModifier::AsIntMax: + case LengthModifier::AsSizeT: + case LengthModifier::AsPtrDiff: + switch (CS.getKind()) { + case ConversionSpecifier::dArg: + case ConversionSpecifier::DArg: + case ConversionSpecifier::iArg: + case ConversionSpecifier::oArg: + case ConversionSpecifier::OArg: + case ConversionSpecifier::uArg: + case ConversionSpecifier::UArg: + case ConversionSpecifier::xArg: + case ConversionSpecifier::XArg: + case ConversionSpecifier::nArg: + return true; + case ConversionSpecifier::FreeBSDrArg: + case ConversionSpecifier::FreeBSDyArg: + return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS4(); + default: + return false; + } - case LengthModifier::AsMAllocate: - switch (CS.getKind()) { - case ConversionSpecifier::cArg: - case ConversionSpecifier::CArg: - case ConversionSpecifier::sArg: - case ConversionSpecifier::SArg: - case ConversionSpecifier::ScanListArg: - return true; - default: - return false; - } - case LengthModifier::AsInt32: - case LengthModifier::AsInt3264: - case LengthModifier::AsInt64: - switch (CS.getKind()) { - case ConversionSpecifier::dArg: - case ConversionSpecifier::iArg: - case ConversionSpecifier::oArg: - case ConversionSpecifier::uArg: - case ConversionSpecifier::xArg: - case ConversionSpecifier::XArg: - return Target.getTriple().isOSMSVCRT(); - default: - return false; - } - case LengthModifier::AsWide: - switch (CS.getKind()) { - case ConversionSpecifier::cArg: - case ConversionSpecifier::CArg: - case ConversionSpecifier::sArg: - case ConversionSpecifier::SArg: - case ConversionSpecifier::ZArg: - return Target.getTriple().isOSMSVCRT(); - default: - return false; - } - } - llvm_unreachable("Invalid LengthModifier Kind!"); -} + case LengthModifier::AsShortLong: + return LO.OpenCL && !VectorNumElts.isInvalid(); -bool FormatSpecifier::hasStandardLengthModifier() const { - switch (LM.getKind()) { - case LengthModifier::None: - case LengthModifier::AsChar: - case LengthModifier::AsShort: - case LengthModifier::AsLong: - case LengthModifier::AsLongLong: - case LengthModifier::AsIntMax: - case LengthModifier::AsSizeT: - case LengthModifier::AsPtrDiff: - case LengthModifier::AsLongDouble: + // Handle 'l' flag + case LengthModifier::AsLong: // or AsWideChar + if (CS.isDoubleArg()) { + // Invalid for OpenCL FP scalars. + if (LO.OpenCL && VectorNumElts.isInvalid()) + return false; return true; - case LengthModifier::AsAllocate: - case LengthModifier::AsMAllocate: - case LengthModifier::AsQuad: - case LengthModifier::AsInt32: - case LengthModifier::AsInt3264: - case LengthModifier::AsInt64: - case LengthModifier::AsWide: - case LengthModifier::AsShortLong: // ??? - return false; - } - llvm_unreachable("Invalid LengthModifier Kind!"); -} + } -bool FormatSpecifier::hasStandardConversionSpecifier( - const LangOptions &LangOpt) const { - switch (CS.getKind()) { - case ConversionSpecifier::cArg: + switch (CS.getKind()) { case ConversionSpecifier::dArg: + case ConversionSpecifier::DArg: case ConversionSpecifier::iArg: case ConversionSpecifier::oArg: + case ConversionSpecifier::OArg: case ConversionSpecifier::uArg: + case ConversionSpecifier::UArg: case ConversionSpecifier::xArg: case ConversionSpecifier::XArg: + case ConversionSpecifier::nArg: + case ConversionSpecifier::cArg: + case ConversionSpecifier::sArg: + case ConversionSpecifier::ScanListArg: + case ConversionSpecifier::ZArg: + return true; + case ConversionSpecifier::FreeBSDrArg: + case ConversionSpecifier::FreeBSDyArg: + return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS4(); + default: + return false; + } + + case LengthModifier::AsLongDouble: + switch (CS.getKind()) { + case ConversionSpecifier::aArg: + case ConversionSpecifier::AArg: case ConversionSpecifier::fArg: case ConversionSpecifier::FArg: case ConversionSpecifier::eArg: case ConversionSpecifier::EArg: case ConversionSpecifier::gArg: case ConversionSpecifier::GArg: - case ConversionSpecifier::aArg: - case ConversionSpecifier::AArg: + return true; + // GNU libc extension. + case ConversionSpecifier::dArg: + case ConversionSpecifier::iArg: + case ConversionSpecifier::oArg: + case ConversionSpecifier::uArg: + case ConversionSpecifier::xArg: + case ConversionSpecifier::XArg: + return !Target.getTriple().isOSDarwin() && + !Target.getTriple().isOSWindows(); + default: + return false; + } + + case LengthModifier::AsAllocate: + switch (CS.getKind()) { case ConversionSpecifier::sArg: - case ConversionSpecifier::pArg: - case ConversionSpecifier::nArg: - case ConversionSpecifier::ObjCObjArg: + case ConversionSpecifier::SArg: case ConversionSpecifier::ScanListArg: - case ConversionSpecifier::PercentArg: - case ConversionSpecifier::PArg: return true; + default: + return false; + } + + case LengthModifier::AsMAllocate: + switch (CS.getKind()) { + case ConversionSpecifier::cArg: case ConversionSpecifier::CArg: + case ConversionSpecifier::sArg: + case ConversionSpecifier::SArg: + case ConversionSpecifier::ScanListArg: + return true; + default: + return false; + } + case LengthModifier::AsInt32: + case LengthModifier::AsInt3264: + case LengthModifier::AsInt64: + switch (CS.getKind()) { + case ConversionSpecifier::dArg: + case ConversionSpecifier::iArg: + case ConversionSpecifier::oArg: + case ConversionSpecifier::uArg: + case ConversionSpecifier::xArg: + case ConversionSpecifier::XArg: + return Target.getTriple().isOSMSVCRT(); + default: + return false; + } + case LengthModifier::AsWide: + switch (CS.getKind()) { + case ConversionSpecifier::cArg: + case ConversionSpecifier::CArg: + case ConversionSpecifier::sArg: case ConversionSpecifier::SArg: - return LangOpt.ObjC; - case ConversionSpecifier::InvalidSpecifier: - case ConversionSpecifier::FreeBSDbArg: - case ConversionSpecifier::FreeBSDDArg: - case ConversionSpecifier::FreeBSDrArg: - case ConversionSpecifier::FreeBSDyArg: - case ConversionSpecifier::PrintErrno: - case ConversionSpecifier::DArg: - case ConversionSpecifier::OArg: - case ConversionSpecifier::UArg: case ConversionSpecifier::ZArg: + return Target.getTriple().isOSMSVCRT(); + default: return false; + } + } + llvm_unreachable("Invalid LengthModifier Kind!"); +} + +bool FormatSpecifier::hasStandardLengthModifier() const { + switch (LM.getKind()) { + case LengthModifier::None: + case LengthModifier::AsChar: + case LengthModifier::AsShort: + case LengthModifier::AsLong: + case LengthModifier::AsLongLong: + case LengthModifier::AsIntMax: + case LengthModifier::AsSizeT: + case LengthModifier::AsPtrDiff: + case LengthModifier::AsLongDouble: + return true; + case LengthModifier::AsAllocate: + case LengthModifier::AsMAllocate: + case LengthModifier::AsQuad: + case LengthModifier::AsInt32: + case LengthModifier::AsInt3264: + case LengthModifier::AsInt64: + case LengthModifier::AsWide: + case LengthModifier::AsShortLong: // ??? + return false; + } + llvm_unreachable("Invalid LengthModifier Kind!"); +} + +bool FormatSpecifier::hasStandardConversionSpecifier( + LangOptions const &LangOpt) const { + switch (CS.getKind()) { + case ConversionSpecifier::cArg: + case ConversionSpecifier::dArg: + case ConversionSpecifier::iArg: + case ConversionSpecifier::oArg: + case ConversionSpecifier::uArg: + case ConversionSpecifier::xArg: + case ConversionSpecifier::XArg: + case ConversionSpecifier::fArg: + case ConversionSpecifier::FArg: + case ConversionSpecifier::eArg: + case ConversionSpecifier::EArg: + case ConversionSpecifier::gArg: + case ConversionSpecifier::GArg: + case ConversionSpecifier::aArg: + case ConversionSpecifier::AArg: + case ConversionSpecifier::sArg: + case ConversionSpecifier::pArg: + case ConversionSpecifier::nArg: + case ConversionSpecifier::ObjCObjArg: + case ConversionSpecifier::ScanListArg: + case ConversionSpecifier::PercentArg: + case ConversionSpecifier::PArg: + return true; + case ConversionSpecifier::CArg: + case ConversionSpecifier::SArg: + return LangOpt.ObjC; + case ConversionSpecifier::InvalidSpecifier: + case ConversionSpecifier::FreeBSDbArg: + case ConversionSpecifier::FreeBSDDArg: + case ConversionSpecifier::FreeBSDrArg: + case ConversionSpecifier::FreeBSDyArg: + case ConversionSpecifier::PrintErrno: + case ConversionSpecifier::DArg: + case ConversionSpecifier::OArg: + case ConversionSpecifier::UArg: + case ConversionSpecifier::ZArg: + return false; } llvm_unreachable("Invalid ConversionSpecifier Kind!"); } bool FormatSpecifier::hasStandardLengthConversionCombination() const { if (LM.getKind() == LengthModifier::AsLongDouble) { - switch(CS.getKind()) { - case ConversionSpecifier::dArg: - case ConversionSpecifier::iArg: - case ConversionSpecifier::oArg: - case ConversionSpecifier::uArg: - case ConversionSpecifier::xArg: - case ConversionSpecifier::XArg: - return false; - default: - return true; + switch (CS.getKind()) { + case ConversionSpecifier::dArg: + case ConversionSpecifier::iArg: + case ConversionSpecifier::oArg: + case ConversionSpecifier::uArg: + case ConversionSpecifier::xArg: + case ConversionSpecifier::XArg: + return false; + default: + return true; } } return true; @@ -977,10 +1011,10 @@ bool FormatSpecifier::namedTypeToLengthModifier(QualType QT, LengthModifier &LM) { assert(isa(QT) && "Expected a TypedefType"); - const TypedefNameDecl *Typedef = cast(QT)->getDecl(); + TypedefNameDecl const *Typedef = cast(QT)->getDecl(); for (;;) { - const IdentifierInfo *Identifier = Typedef->getIdentifier(); + IdentifierInfo const *Identifier = Typedef->getIdentifier(); if (Identifier->getName() == "size_t") { LM.setKind(LengthModifier::AsSizeT); return true; Index: clang/lib/AST/InheritViz.cpp =================================================================== --- clang/lib/AST/InheritViz.cpp +++ clang/lib/AST/InheritViz.cpp @@ -31,14 +31,14 @@ /// differentiate between uses of types as virtual bases /// vs. non-virtual bases. class InheritanceHierarchyWriter { - ASTContext& Context; + ASTContext &Context; raw_ostream &Out; std::map DirectBaseCount; std::set KnownVirtualBases; public: - InheritanceHierarchyWriter(ASTContext& Context, raw_ostream& Out) - : Context(Context), Out(Out) { } + InheritanceHierarchyWriter(ASTContext &Context, raw_ostream &Out) + : Context(Context), Out(Out) {} void WriteGraph(QualType Type) { Out << "digraph \"" << llvm::DOT::EscapeString(Type.getAsString()) @@ -55,7 +55,7 @@ /// WriteNodeReference - Write out a reference to the given node, /// using a unique identifier for each direct base and for the /// (only) virtual base. - raw_ostream& WriteNodeReference(QualType Type, bool FromVirtual); + raw_ostream &WriteNodeReference(QualType Type, bool FromVirtual); }; } // namespace @@ -90,9 +90,9 @@ Out << " \"];\n"; // Display the base classes. - const auto *Decl = - static_cast(Type->castAs()->getDecl()); - for (const auto &Base : Decl->bases()) { + auto const *Decl = + static_cast(Type->castAs()->getDecl()); + for (auto const &Base : Decl->bases()) { QualType CanonBaseType = Context.getCanonicalType(Base.getType()); // If this is not virtual inheritance, bump the direct base @@ -120,9 +120,8 @@ /// WriteNodeReference - Write out a reference to the given node, /// using a unique identifier for each direct base and for the /// (only) virtual base. -raw_ostream& -InheritanceHierarchyWriter::WriteNodeReference(QualType Type, - bool FromVirtual) { +raw_ostream &InheritanceHierarchyWriter::WriteNodeReference(QualType Type, + bool FromVirtual) { QualType CanonType = Context.getCanonicalType(Type); Out << "Class_" << CanonType.getAsOpaquePtr(); @@ -133,7 +132,7 @@ /// viewInheritance - Display the inheritance hierarchy of this C++ /// class using GraphViz. -void CXXRecordDecl::viewInheritance(ASTContext& Context) const { +void CXXRecordDecl::viewInheritance(ASTContext &Context) const { QualType Self = Context.getTypeDeclType(this); int FD; Index: clang/lib/AST/ItaniumCXXABI.cpp =================================================================== --- clang/lib/AST/ItaniumCXXABI.cpp +++ clang/lib/AST/ItaniumCXXABI.cpp @@ -38,14 +38,15 @@ /// the anonymous union. /// If there is no such data member (i.e., if all of the data members /// in the union are unnamed), then there is no way for a program to -/// refer to the anonymous union, and there is therefore no need to mangle its name. +/// refer to the anonymous union, and there is therefore no need to mangle its +/// name. /// /// Returns the name of anonymous union VarDecl or nullptr if it is not found. -static const IdentifierInfo *findAnonymousUnionVarDeclName(const VarDecl& VD) { - const RecordType *RT = VD.getType()->getAs(); +static IdentifierInfo const *findAnonymousUnionVarDeclName(VarDecl const &VD) { + RecordType const *RT = VD.getType()->getAs(); assert(RT && "type of VarDecl is expected to be RecordType."); assert(RT->getDecl()->isUnion() && "RecordType is expected to be a union."); - if (const FieldDecl *FD = RT->getDecl()->findFirstNamedDataMember()) { + if (FieldDecl const *FD = RT->getDecl()->findFirstNamedDataMember()) { return FD->getIdentifier(); } @@ -54,7 +55,7 @@ /// The name of a decomposition declaration. struct DecompositionDeclName { - using BindingArray = ArrayRef; + using BindingArray = ArrayRef; /// Representative example of a set of bindings with these names. BindingArray Bindings; @@ -63,28 +64,28 @@ struct Iterator : llvm::iterator_adaptor_base { + IdentifierInfo const *> { Iterator(BindingArray::const_iterator It) : iterator_adaptor_base(It) {} - const IdentifierInfo *operator*() const { + IdentifierInfo const *operator*() const { return (*this->I)->getIdentifier(); } }; Iterator begin() const { return Iterator(Bindings.begin()); } Iterator end() const { return Iterator(Bindings.end()); } }; -} +} // namespace namespace llvm { -template bool isDenseMapKeyEmpty(T V) { - return llvm::DenseMapInfo::isEqual( - V, llvm::DenseMapInfo::getEmptyKey()); +template bool isDenseMapKeyEmpty(T V) { + return llvm::DenseMapInfo::isEqual(V, + llvm::DenseMapInfo::getEmptyKey()); } -template bool isDenseMapKeyTombstone(T V) { +template bool isDenseMapKeyTombstone(T V) { return llvm::DenseMapInfo::isEqual( V, llvm::DenseMapInfo::getTombstoneKey()); } -template +template Optional areDenseMapKeysEqualSpecialValues(T LHS, T RHS) { bool LHSEmpty = isDenseMapKeyEmpty(LHS); bool RHSEmpty = isDenseMapKeyEmpty(RHS); @@ -99,9 +100,8 @@ return None; } -template<> -struct DenseMapInfo { - using ArrayInfo = llvm::DenseMapInfo>; +template <> struct DenseMapInfo { + using ArrayInfo = llvm::DenseMapInfo>; static DecompositionDeclName getEmptyKey() { return {ArrayInfo::getEmptyKey()}; } @@ -113,15 +113,15 @@ return llvm::hash_combine_range(Key.begin(), Key.end()); } static bool isEqual(DecompositionDeclName LHS, DecompositionDeclName RHS) { - if (Optional Result = areDenseMapKeysEqualSpecialValues( - LHS.Bindings, RHS.Bindings)) + if (Optional Result = + areDenseMapKeysEqualSpecialValues(LHS.Bindings, RHS.Bindings)) return *Result; return LHS.Bindings.size() == RHS.Bindings.size() && std::equal(LHS.begin(), LHS.end(), RHS.begin()); } }; -} +} // namespace llvm namespace { @@ -131,16 +131,16 @@ ItaniumMangleContext *Mangler; llvm::StringMap LambdaManglingNumbers; unsigned BlockManglingNumber = 0; - llvm::DenseMap VarManglingNumbers; - llvm::DenseMap TagManglingNumbers; + llvm::DenseMap VarManglingNumbers; + llvm::DenseMap TagManglingNumbers; llvm::DenseMap DecompsitionDeclManglingNumbers; public: ItaniumNumberingContext(ItaniumMangleContext *Mangler) : Mangler(Mangler) {} - unsigned getManglingNumber(const CXXMethodDecl *CallOperator) override { - const CXXRecordDecl *Lambda = CallOperator->getParent(); + unsigned getManglingNumber(CXXMethodDecl const *CallOperator) override { + CXXRecordDecl const *Lambda = CallOperator->getParent(); assert(Lambda->isLambda()); // Computation of the is non-trivial and subtle. Rather than @@ -152,22 +152,20 @@ return ++LambdaManglingNumbers[LambdaSig]; } - unsigned getManglingNumber(const BlockDecl *BD) override { + unsigned getManglingNumber(BlockDecl const *BD) override { return ++BlockManglingNumber; } - unsigned getStaticLocalNumber(const VarDecl *VD) override { - return 0; - } + unsigned getStaticLocalNumber(VarDecl const *VD) override { return 0; } /// Variable decls are numbered by identifier. - unsigned getManglingNumber(const VarDecl *VD, unsigned) override { + unsigned getManglingNumber(VarDecl const *VD, unsigned) override { if (auto *DD = dyn_cast(VD)) { DecompositionDeclName Name{DD->bindings()}; return ++DecompsitionDeclManglingNumbers[Name]; } - const IdentifierInfo *Identifier = VD->getIdentifier(); + IdentifierInfo const *Identifier = VD->getIdentifier(); if (!Identifier) { // VarDecl without an identifier represents an anonymous union // declaration. @@ -176,7 +174,7 @@ return ++VarManglingNumbers[Identifier]; } - unsigned getManglingNumber(const TagDecl *TD, unsigned) override { + unsigned getManglingNumber(TagDecl const *TD, unsigned) override { return ++TagManglingNumbers[TD->getIdentifier()]; } }; @@ -184,15 +182,17 @@ class ItaniumCXXABI : public CXXABI { private: std::unique_ptr Mangler; + protected: ASTContext &Context; + public: ItaniumCXXABI(ASTContext &Ctx) : Mangler(Ctx.createMangleContext()), Context(Ctx) {} MemberPointerInfo - getMemberPointerInfo(const MemberPointerType *MPT) const override { - const TargetInfo &Target = Context.getTargetInfo(); + getMemberPointerInfo(MemberPointerType const *MPT) const override { + TargetInfo const &Target = Context.getTargetInfo(); TargetInfo::IntType PtrDiff = Target.getPtrDiffType(0); MemberPointerInfo MPI; MPI.Width = Target.getTypeWidth(PtrDiff); @@ -204,7 +204,7 @@ } CallingConv getDefaultMethodCallConv(bool isVariadic) const override { - const llvm::Triple &T = Context.getTargetInfo().getTriple(); + llvm::Triple const &T = Context.getTargetInfo().getTriple(); if (!isVariadic && T.isWindowsGNUEnvironment() && T.getArch() == llvm::Triple::x86) return CC_X86ThisCall; @@ -213,19 +213,19 @@ // We cheat and just check that the class has a vtable pointer, and that it's // only big enough to have a vtable pointer and nothing more (or less). - bool isNearlyEmpty(const CXXRecordDecl *RD) const override { + bool isNearlyEmpty(CXXRecordDecl const *RD) const override { // Check that the class has a vtable pointer. if (!RD->isDynamicClass()) return false; - const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); + ASTRecordLayout const &Layout = Context.getASTRecordLayout(RD); CharUnits PointerSize = - Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); + Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0)); return Layout.getNonVirtualSize() == PointerSize; } - const CXXConstructorDecl * + CXXConstructorDecl const * getCopyConstructorForExceptionObject(CXXRecordDecl *RD) override { return nullptr; } @@ -236,14 +236,14 @@ void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *DD) override {} - TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD) override { + TypedefNameDecl *getTypedefNameForUnnamedTagDecl(TagDecl const *TD) override { return nullptr; } void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD) override {} - DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD) override { + DeclaratorDecl *getDeclaratorForUnnamedTagDecl(TagDecl const *TD) override { return nullptr; } @@ -253,7 +253,7 @@ cast(Mangler.get())); } }; -} +} // namespace CXXABI *clang::CreateItaniumCXXABI(ASTContext &Ctx) { return new ItaniumCXXABI(Ctx); Index: clang/lib/AST/ItaniumMangle.cpp =================================================================== --- clang/lib/AST/ItaniumMangle.cpp +++ clang/lib/AST/ItaniumMangle.cpp @@ -42,54 +42,54 @@ /// Retrieve the declaration context that should be used when mangling the given /// declaration. -static const DeclContext *getEffectiveDeclContext(const Decl *D) { +static DeclContext const *getEffectiveDeclContext(Decl const *D) { // The ABI assumes that lambda closure types that occur within // default arguments live in the context of the function. However, due to // the way in which Clang parses and creates function declarations, this is // not the case: the lambda closure type ends up living in the context // where the function itself resides, because the function declaration itself // had not yet been created. Fix the context here. - if (const CXXRecordDecl *RD = dyn_cast(D)) { + if (CXXRecordDecl const *RD = dyn_cast(D)) { if (RD->isLambda()) - if (ParmVarDecl *ContextParam - = dyn_cast_or_null(RD->getLambdaContextDecl())) + if (ParmVarDecl *ContextParam = + dyn_cast_or_null(RD->getLambdaContextDecl())) return ContextParam->getDeclContext(); } // Perform the same check for block literals. - if (const BlockDecl *BD = dyn_cast(D)) { - if (ParmVarDecl *ContextParam - = dyn_cast_or_null(BD->getBlockManglingContextDecl())) + if (BlockDecl const *BD = dyn_cast(D)) { + if (ParmVarDecl *ContextParam = + dyn_cast_or_null(BD->getBlockManglingContextDecl())) return ContextParam->getDeclContext(); } - const DeclContext *DC = D->getDeclContext(); + DeclContext const *DC = D->getDeclContext(); if (isa(DC) || isa(DC) || isa(DC)) { return getEffectiveDeclContext(cast(DC)); } - if (const auto *VD = dyn_cast(D)) + if (auto const *VD = dyn_cast(D)) if (VD->isExternC()) return VD->getASTContext().getTranslationUnitDecl(); - if (const auto *FD = dyn_cast(D)) + if (auto const *FD = dyn_cast(D)) if (FD->isExternC()) return FD->getASTContext().getTranslationUnitDecl(); return DC->getRedeclContext(); } -static const DeclContext *getEffectiveParentContext(const DeclContext *DC) { +static DeclContext const *getEffectiveParentContext(DeclContext const *DC) { return getEffectiveDeclContext(cast(DC)); } -static bool isLocalContainerContext(const DeclContext *DC) { +static bool isLocalContainerContext(DeclContext const *DC) { return isa(DC) || isa(DC) || isa(DC); } -static const RecordDecl *GetLocalClassDecl(const Decl *D) { - const DeclContext *DC = getEffectiveDeclContext(D); +static RecordDecl const *GetLocalClassDecl(Decl const *D) { + DeclContext const *DC = getEffectiveDeclContext(D); while (!DC->isNamespace() && !DC->isTranslationUnit()) { if (isLocalContainerContext(DC)) return dyn_cast(D); @@ -99,32 +99,32 @@ return nullptr; } -static const FunctionDecl *getStructor(const FunctionDecl *fn) { - if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate()) +static FunctionDecl const *getStructor(FunctionDecl const *fn) { + if (FunctionTemplateDecl const *ftd = fn->getPrimaryTemplate()) return ftd->getTemplatedDecl(); return fn; } -static const NamedDecl *getStructor(const NamedDecl *decl) { - const FunctionDecl *fn = dyn_cast_or_null(decl); +static NamedDecl const *getStructor(NamedDecl const *decl) { + FunctionDecl const *fn = dyn_cast_or_null(decl); return (fn ? getStructor(fn) : decl); } -static bool isLambda(const NamedDecl *ND) { - const CXXRecordDecl *Record = dyn_cast(ND); +static bool isLambda(NamedDecl const *ND) { + CXXRecordDecl const *Record = dyn_cast(ND); if (!Record) return false; return Record->isLambda(); } -static const unsigned UnknownArity = ~0U; +static unsigned const UnknownArity = ~0U; class ItaniumMangleContextImpl : public ItaniumMangleContext { - typedef std::pair DiscriminatorKeyTy; + typedef std::pair DiscriminatorKeyTy; llvm::DenseMap Discriminator; - llvm::DenseMap Uniquifier; + llvm::DenseMap Uniquifier; const DiscriminatorOverrideTy DiscriminatorOverride = nullptr; bool NeedsUniqueInternalLinkageNames = false; @@ -139,58 +139,58 @@ /// @name Mangler Entry Points /// @{ - bool shouldMangleCXXName(const NamedDecl *D) override; - bool shouldMangleStringLiteral(const StringLiteral *) override { + bool shouldMangleCXXName(NamedDecl const *D) override; + bool shouldMangleStringLiteral(StringLiteral const *) override { return false; } - bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override; + bool isUniqueInternalLinkageDecl(NamedDecl const *ND) override; void needsUniqueInternalLinkageNames() override { NeedsUniqueInternalLinkageNames = true; } void mangleCXXName(GlobalDecl GD, raw_ostream &) override; - void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, + void mangleThunk(CXXMethodDecl const *MD, ThunkInfo const &Thunk, raw_ostream &) override; - void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, - const ThisAdjustment &ThisAdjustment, + void mangleCXXDtorThunk(CXXDestructorDecl const *DD, CXXDtorType Type, + ThisAdjustment const &ThisAdjustment, raw_ostream &) override; - void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, + void mangleReferenceTemporary(VarDecl const *D, unsigned ManglingNumber, raw_ostream &) override; - void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override; - void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override; - void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset, - const CXXRecordDecl *Type, raw_ostream &) override; + void mangleCXXVTable(CXXRecordDecl const *RD, raw_ostream &) override; + void mangleCXXVTT(CXXRecordDecl const *RD, raw_ostream &) override; + void mangleCXXCtorVTable(CXXRecordDecl const *RD, int64_t Offset, + CXXRecordDecl const *Type, raw_ostream &) override; void mangleCXXRTTI(QualType T, raw_ostream &) override; void mangleCXXRTTIName(QualType T, raw_ostream &) override; void mangleTypeName(QualType T, raw_ostream &) override; - void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override; - void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override; - void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override; - void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override; - void mangleDynamicAtExitDestructor(const VarDecl *D, + void mangleCXXCtorComdat(CXXConstructorDecl const *D, raw_ostream &) override; + void mangleCXXDtorComdat(CXXDestructorDecl const *D, raw_ostream &) override; + void mangleStaticGuardVariable(VarDecl const *D, raw_ostream &) override; + void mangleDynamicInitializer(VarDecl const *D, raw_ostream &Out) override; + void mangleDynamicAtExitDestructor(VarDecl const *D, raw_ostream &Out) override; - void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override; - void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl, + void mangleDynamicStermFinalizer(VarDecl const *D, raw_ostream &Out) override; + void mangleSEHFilterExpression(NamedDecl const *EnclosingDecl, raw_ostream &Out) override; - void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl, + void mangleSEHFinallyBlock(NamedDecl const *EnclosingDecl, raw_ostream &Out) override; - void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override; - void mangleItaniumThreadLocalWrapper(const VarDecl *D, + void mangleItaniumThreadLocalInit(VarDecl const *D, raw_ostream &) override; + void mangleItaniumThreadLocalWrapper(VarDecl const *D, raw_ostream &) override; - void mangleStringLiteral(const StringLiteral *, raw_ostream &) override; + void mangleStringLiteral(StringLiteral const *, raw_ostream &) override; - void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override; + void mangleLambdaSig(CXXRecordDecl const *Lambda, raw_ostream &) override; - bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { + bool getNextDiscriminator(NamedDecl const *ND, unsigned &disc) { // Lambda closure types are already numbered. if (isLambda(ND)) return false; // Anonymous tags are already numbered. - if (const TagDecl *Tag = dyn_cast(ND)) { + if (TagDecl const *Tag = dyn_cast(ND)) { if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl()) return false; } @@ -207,16 +207,16 @@ // Make up a reasonable number for internal decls. unsigned &discriminator = Uniquifier[ND]; if (!discriminator) { - const DeclContext *DC = getEffectiveDeclContext(ND); + DeclContext const *DC = getEffectiveDeclContext(ND); discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())]; } if (discriminator == 1) return false; - disc = discriminator-2; + disc = discriminator - 2; return true; } - std::string getLambdaString(const CXXRecordDecl *Lambda) override { + std::string getLambdaString(CXXRecordDecl const *Lambda) override { // This function matches the one in MicrosoftMangle, which returns // the string that is used in lambda mangled names. assert(Lambda->isLambda() && "RD must be a lambda!"); @@ -224,8 +224,8 @@ Decl *LambdaContextDecl = Lambda->getLambdaContextDecl(); unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber(); unsigned LambdaId; - const ParmVarDecl *Parm = dyn_cast_or_null(LambdaContextDecl); - const FunctionDecl *Func = + ParmVarDecl const *Parm = dyn_cast_or_null(LambdaContextDecl); + FunctionDecl const *Func = Parm ? dyn_cast(Parm->getDeclContext()) : nullptr; if (Func) { @@ -266,7 +266,7 @@ /// The "structor" is the top-level declaration being mangled, if /// that's not a template specialization; otherwise it's the pattern /// for that specialization. - const NamedDecl *Structor; + NamedDecl const *Structor; unsigned StructorType; /// The next substitution sequence number. @@ -281,14 +281,10 @@ FunctionTypeDepthState() : Bits(0) {} /// The number of function types we're inside. - unsigned getDepth() const { - return Bits >> 1; - } + unsigned getDepth() const { return Bits >> 1; } /// True if we're in the return type of the innermost function type. - bool isInResultType() const { - return Bits & InResultTypeMask; - } + bool isInResultType() const { return Bits & InResultTypeMask; } FunctionTypeDepthState push() { FunctionTypeDepthState tmp = *this; @@ -296,13 +292,9 @@ return tmp; } - void enterResultType() { - Bits |= InResultTypeMask; - } + void enterResultType() { Bits |= InResultTypeMask; } - void leaveResultType() { - Bits &= ~InResultTypeMask; - } + void leaveResultType() { Bits &= ~InResultTypeMask; } void pop(FunctionTypeDepthState saved) { assert(getDepth() == saved.getDepth() + 1); @@ -328,20 +320,20 @@ } // No copy, no move. - AbiTagState(const AbiTagState &) = delete; - AbiTagState &operator=(const AbiTagState &) = delete; + AbiTagState(AbiTagState const &) = delete; + AbiTagState &operator=(AbiTagState const &) = delete; ~AbiTagState() { pop(); } - void write(raw_ostream &Out, const NamedDecl *ND, - const AbiTagList *AdditionalAbiTags) { + void write(raw_ostream &Out, NamedDecl const *ND, + AbiTagList const *AdditionalAbiTags) { ND = cast(ND->getCanonicalDecl()); if (!isa(ND) && !isa(ND)) { assert( !AdditionalAbiTags && "only function and variables need a list of additional abi tags"); - if (const auto *NS = dyn_cast(ND)) { - if (const auto *AbiTag = NS->getAttr()) { + if (auto const *NS = dyn_cast(ND)) { + if (auto const *AbiTag = NS->getAttr()) { UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(), AbiTag->tags().end()); } @@ -351,7 +343,7 @@ } AbiTagList TagList; - if (const auto *AbiTag = ND->getAttr()) { + if (auto const *AbiTag = ND->getAttr()) { UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(), AbiTag->tags().end()); TagList.insert(TagList.end(), AbiTag->tags().begin(), @@ -371,16 +363,12 @@ writeSortedUniqueAbiTags(Out, TagList); } - const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; } - void setUsedAbiTags(const AbiTagList &AbiTags) { - UsedAbiTags = AbiTags; - } + AbiTagList const &getUsedAbiTags() const { return UsedAbiTags; } + void setUsedAbiTags(AbiTagList const &AbiTags) { UsedAbiTags = AbiTags; } - const AbiTagList &getEmittedAbiTags() const { - return EmittedAbiTags; - } + AbiTagList const &getEmittedAbiTags() const { return EmittedAbiTags; } - const AbiTagList &getSortedUniqueUsedAbiTags() { + AbiTagList const &getSortedUniqueUsedAbiTags() { llvm::sort(UsedAbiTags); UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()), UsedAbiTags.end()); @@ -409,8 +397,8 @@ LinkHead = Parent; } - void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) { - for (const auto &Tag : AbiTags) { + void writeSortedUniqueAbiTags(raw_ostream &Out, AbiTagList const &AbiTags) { + for (auto const &Tag : AbiTags) { EmittedAbiTags.push_back(Tag); Out << "B"; Out << Tag.size(); @@ -429,21 +417,20 @@ public: CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, - const NamedDecl *D = nullptr, bool NullOut_ = false) - : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)), - StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) { + NamedDecl const *D = nullptr, bool NullOut_ = false) + : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)), + StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) { // These can't be mangled without a ctor type or dtor type. - assert(!D || (!isa(D) && - !isa(D))); + assert(!D || (!isa(D) && !isa(D))); } CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, - const CXXConstructorDecl *D, CXXCtorType Type) - : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), - SeqID(0), AbiTagsRoot(AbiTags) { } + CXXConstructorDecl const *D, CXXCtorType Type) + : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), + SeqID(0), AbiTagsRoot(AbiTags) {} CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, - const CXXDestructorDecl *D, CXXDtorType Type) - : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), - SeqID(0), AbiTagsRoot(AbiTags) { } + CXXDestructorDecl const *D, CXXDtorType Type) + : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), + SeqID(0), AbiTagsRoot(AbiTags) {} CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_) : Context(Outer.Context), Out(Out_), NullOut(false), @@ -460,32 +447,31 @@ raw_ostream &getStream() { return Out; } void disableDerivedAbiTags() { DisableDerivedAbiTags = true; } - static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD); + static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, VarDecl const *VD); void mangle(GlobalDecl GD); void mangleCallOffset(int64_t NonVirtual, int64_t Virtual); - void mangleNumber(const llvm::APSInt &I); + void mangleNumber(llvm::APSInt const &I); void mangleNumber(int64_t Number); - void mangleFloat(const llvm::APFloat &F); + void mangleFloat(llvm::APFloat const &F); void mangleFunctionEncoding(GlobalDecl GD); void mangleSeqID(unsigned SeqID); void mangleName(GlobalDecl GD); void mangleType(QualType T); - void mangleNameOrStandardSubstitution(const NamedDecl *ND); - void mangleLambdaSig(const CXXRecordDecl *Lambda); + void mangleNameOrStandardSubstitution(NamedDecl const *ND); + void mangleLambdaSig(CXXRecordDecl const *Lambda); private: - - bool mangleSubstitution(const NamedDecl *ND); + bool mangleSubstitution(NamedDecl const *ND); bool mangleSubstitution(QualType T); bool mangleSubstitution(TemplateName Template); bool mangleSubstitution(uintptr_t Ptr); void mangleExistingSubstitution(TemplateName name); - bool mangleStandardSubstitution(const NamedDecl *ND); + bool mangleStandardSubstitution(NamedDecl const *ND); - void addSubstitution(const NamedDecl *ND) { + void addSubstitution(NamedDecl const *ND) { ND = cast(ND->getCanonicalDecl()); addSubstitution(reinterpret_cast(ND)); @@ -494,73 +480,73 @@ void addSubstitution(TemplateName Template); void addSubstitution(uintptr_t Ptr); // Destructive copy substitutions from other mangler. - void extendSubstitutions(CXXNameMangler* Other); + void extendSubstitutions(CXXNameMangler *Other); void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, bool recursive = false); void mangleUnresolvedName(NestedNameSpecifier *qualifier, DeclarationName name, - const TemplateArgumentLoc *TemplateArgs, + TemplateArgumentLoc const *TemplateArgs, unsigned NumTemplateArgs, unsigned KnownArity = UnknownArity); - void mangleFunctionEncodingBareType(const FunctionDecl *FD); + void mangleFunctionEncodingBareType(FunctionDecl const *FD); void mangleNameWithAbiTags(GlobalDecl GD, - const AbiTagList *AdditionalAbiTags); - void mangleModuleName(const Module *M); + AbiTagList const *AdditionalAbiTags); + void mangleModuleName(Module const *M); void mangleModuleNamePrefix(StringRef Name); - void mangleTemplateName(const TemplateDecl *TD, - const TemplateArgument *TemplateArgs, + void mangleTemplateName(TemplateDecl const *TD, + TemplateArgument const *TemplateArgs, unsigned NumTemplateArgs); void mangleUnqualifiedName(GlobalDecl GD, - const AbiTagList *AdditionalAbiTags) { - mangleUnqualifiedName(GD, cast(GD.getDecl())->getDeclName(), UnknownArity, - AdditionalAbiTags); + AbiTagList const *AdditionalAbiTags) { + mangleUnqualifiedName(GD, cast(GD.getDecl())->getDeclName(), + UnknownArity, AdditionalAbiTags); } void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name, unsigned KnownArity, - const AbiTagList *AdditionalAbiTags); - void mangleUnscopedName(GlobalDecl GD, - const AbiTagList *AdditionalAbiTags); + AbiTagList const *AdditionalAbiTags); + void mangleUnscopedName(GlobalDecl GD, AbiTagList const *AdditionalAbiTags); void mangleUnscopedTemplateName(GlobalDecl GD, - const AbiTagList *AdditionalAbiTags); - void mangleSourceName(const IdentifierInfo *II); - void mangleRegCallName(const IdentifierInfo *II); - void mangleDeviceStubName(const IdentifierInfo *II); - void mangleSourceNameWithAbiTags( - const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr); - void mangleLocalName(GlobalDecl GD, - const AbiTagList *AdditionalAbiTags); - void mangleBlockForPrefix(const BlockDecl *Block); - void mangleUnqualifiedBlock(const BlockDecl *Block); - void mangleTemplateParamDecl(const NamedDecl *Decl); - void mangleLambda(const CXXRecordDecl *Lambda); - void mangleNestedName(GlobalDecl GD, const DeclContext *DC, - const AbiTagList *AdditionalAbiTags, - bool NoFunction=false); - void mangleNestedName(const TemplateDecl *TD, - const TemplateArgument *TemplateArgs, + AbiTagList const *AdditionalAbiTags); + void mangleSourceName(IdentifierInfo const *II); + void mangleRegCallName(IdentifierInfo const *II); + void mangleDeviceStubName(IdentifierInfo const *II); + void + mangleSourceNameWithAbiTags(NamedDecl const *ND, + AbiTagList const *AdditionalAbiTags = nullptr); + void mangleLocalName(GlobalDecl GD, AbiTagList const *AdditionalAbiTags); + void mangleBlockForPrefix(BlockDecl const *Block); + void mangleUnqualifiedBlock(BlockDecl const *Block); + void mangleTemplateParamDecl(NamedDecl const *Decl); + void mangleLambda(CXXRecordDecl const *Lambda); + void mangleNestedName(GlobalDecl GD, DeclContext const *DC, + AbiTagList const *AdditionalAbiTags, + bool NoFunction = false); + void mangleNestedName(TemplateDecl const *TD, + TemplateArgument const *TemplateArgs, unsigned NumTemplateArgs); void mangleNestedNameWithClosurePrefix(GlobalDecl GD, - const NamedDecl *PrefixND, - const AbiTagList *AdditionalAbiTags); + NamedDecl const *PrefixND, + AbiTagList const *AdditionalAbiTags); void manglePrefix(NestedNameSpecifier *qualifier); - void manglePrefix(const DeclContext *DC, bool NoFunction=false); + void manglePrefix(DeclContext const *DC, bool NoFunction = false); void manglePrefix(QualType type); - void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false); + void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction = false); void mangleTemplatePrefix(TemplateName Template); - const NamedDecl *getClosurePrefix(const Decl *ND); - void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false); + NamedDecl const *getClosurePrefix(Decl const *ND); + void mangleClosurePrefix(NamedDecl const *ND, bool NoFunction = false); bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType, StringRef Prefix = ""); void mangleOperatorName(DeclarationName Name, unsigned Arity); void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity); void mangleVendorQualifier(StringRef qualifier); - void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr); + void mangleQualifiers(Qualifiers Quals, + DependentAddressSpaceType const *DAST = nullptr); void mangleRefQualifier(RefQualifierKind RefQualifier); - void mangleObjCMethodName(const ObjCMethodDecl *MD); + void mangleObjCMethodName(ObjCMethodDecl const *MD); // Declare manglers for every type class. #define ABSTRACT_TYPE(CLASS, PARENT) @@ -568,67 +554,64 @@ #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T); #include "clang/AST/TypeNodes.inc" - void mangleType(const TagType*); + void mangleType(TagType const *); void mangleType(TemplateName); static StringRef getCallingConvQualifierName(CallingConv CC); void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info); - void mangleExtFunctionInfo(const FunctionType *T); - void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType, - const FunctionDecl *FD = nullptr); - void mangleNeonVectorType(const VectorType *T); - void mangleNeonVectorType(const DependentVectorType *T); - void mangleAArch64NeonVectorType(const VectorType *T); - void mangleAArch64NeonVectorType(const DependentVectorType *T); - void mangleAArch64FixedSveVectorType(const VectorType *T); - void mangleAArch64FixedSveVectorType(const DependentVectorType *T); - - void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value); - void mangleFloatLiteral(QualType T, const llvm::APFloat &V); + void mangleExtFunctionInfo(FunctionType const *T); + void mangleBareFunctionType(FunctionProtoType const *T, bool MangleReturnType, + FunctionDecl const *FD = nullptr); + void mangleNeonVectorType(VectorType const *T); + void mangleNeonVectorType(DependentVectorType const *T); + void mangleAArch64NeonVectorType(VectorType const *T); + void mangleAArch64NeonVectorType(DependentVectorType const *T); + void mangleAArch64FixedSveVectorType(VectorType const *T); + void mangleAArch64FixedSveVectorType(DependentVectorType const *T); + + void mangleIntegerLiteral(QualType T, llvm::APSInt const &Value); + void mangleFloatLiteral(QualType T, llvm::APFloat const &V); void mangleFixedPointLiteral(); void mangleNullPointer(QualType T); - void mangleMemberExprBase(const Expr *base, bool isArrow); - void mangleMemberExpr(const Expr *base, bool isArrow, + void mangleMemberExprBase(Expr const *base, bool isArrow); + void mangleMemberExpr(Expr const *base, bool isArrow, NestedNameSpecifier *qualifier, - NamedDecl *firstQualifierLookup, - DeclarationName name, - const TemplateArgumentLoc *TemplateArgs, - unsigned NumTemplateArgs, - unsigned knownArity); - void mangleCastExpression(const Expr *E, StringRef CastEncoding); - void mangleInitListElements(const InitListExpr *InitList); - void mangleExpression(const Expr *E, unsigned Arity = UnknownArity, + NamedDecl *firstQualifierLookup, DeclarationName name, + TemplateArgumentLoc const *TemplateArgs, + unsigned NumTemplateArgs, unsigned knownArity); + void mangleCastExpression(Expr const *E, StringRef CastEncoding); + void mangleInitListElements(InitListExpr const *InitList); + void mangleExpression(Expr const *E, unsigned Arity = UnknownArity, bool AsTemplateArg = false); - void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom); + void mangleCXXCtorType(CXXCtorType T, CXXRecordDecl const *InheritedFrom); void mangleCXXDtorType(CXXDtorType T); void mangleTemplateArgs(TemplateName TN, - const TemplateArgumentLoc *TemplateArgs, + TemplateArgumentLoc const *TemplateArgs, unsigned NumTemplateArgs); - void mangleTemplateArgs(TemplateName TN, const TemplateArgument *TemplateArgs, + void mangleTemplateArgs(TemplateName TN, TemplateArgument const *TemplateArgs, unsigned NumTemplateArgs); - void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL); + void mangleTemplateArgs(TemplateName TN, TemplateArgumentList const &AL); void mangleTemplateArg(TemplateArgument A, bool NeedExactType); - void mangleTemplateArgExpr(const Expr *E); - void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel, + void mangleTemplateArgExpr(Expr const *E); + void mangleValueInTemplateArg(QualType T, APValue const &V, bool TopLevel, bool NeedExactType = false); void mangleTemplateParameter(unsigned Depth, unsigned Index); - void mangleFunctionParam(const ParmVarDecl *parm); + void mangleFunctionParam(ParmVarDecl const *parm); - void writeAbiTags(const NamedDecl *ND, - const AbiTagList *AdditionalAbiTags); + void writeAbiTags(NamedDecl const *ND, AbiTagList const *AdditionalAbiTags); // Returns sorted unique list of ABI tags. - AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD); + AbiTagList makeFunctionReturnTypeTags(FunctionDecl const *FD); // Returns sorted unique list of ABI tags. - AbiTagList makeVariableTypeTags(const VarDecl *VD); + AbiTagList makeVariableTypeTags(VarDecl const *VD); }; -} +} // namespace -static bool isInternalLinkageDecl(const NamedDecl *ND) { +static bool isInternalLinkageDecl(NamedDecl const *ND) { if (ND && ND->getFormalLinkage() == InternalLinkage && !ND->isExternallyVisible() && getEffectiveDeclContext(ND)->isFileContext() && @@ -639,11 +622,11 @@ // Check if this Function Decl needs a unique internal linkage name. bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl( - const NamedDecl *ND) { + NamedDecl const *ND) { if (!NeedsUniqueInternalLinkageNames || !ND) return false; - const auto *FD = dyn_cast(ND); + auto const *FD = dyn_cast(ND); if (!FD) return false; @@ -658,8 +641,8 @@ return false; } -bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) { - const FunctionDecl *FD = dyn_cast(D); +bool ItaniumMangleContextImpl::shouldMangleCXXName(NamedDecl const *D) { + FunctionDecl const *FD = dyn_cast(D); if (FD) { LanguageLinkage L = FD->getLanguageLinkage(); // Overloadable functions need mangling. @@ -696,14 +679,14 @@ if (!getASTContext().getLangOpts().CPlusPlus) return false; - const VarDecl *VD = dyn_cast(D); + VarDecl const *VD = dyn_cast(D); if (VD && !isa(D)) { // C variables are not mangled. if (VD->isExternC()) return false; // Variables at global scope with non-internal linkage are not mangled - const DeclContext *DC = getEffectiveDeclContext(D); + DeclContext const *DC = getEffectiveDeclContext(D); // Check for extern variable declared locally. if (DC->isFunctionOrMethod() && D->hasLinkage()) while (!DC->isNamespace() && !DC->isTranslationUnit()) @@ -717,14 +700,14 @@ return true; } -void CXXNameMangler::writeAbiTags(const NamedDecl *ND, - const AbiTagList *AdditionalAbiTags) { +void CXXNameMangler::writeAbiTags(NamedDecl const *ND, + AbiTagList const *AdditionalAbiTags) { assert(AbiTags && "require AbiTagState"); AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags); } void CXXNameMangler::mangleSourceNameWithAbiTags( - const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) { + NamedDecl const *ND, AbiTagList const *AdditionalAbiTags) { mangleSourceName(ND->getIdentifier()); writeAbiTags(ND, AdditionalAbiTags); } @@ -739,7 +722,7 @@ else if (isa(GD.getDecl())) mangleName(GD); - else if (const IndirectFieldDecl *IFD = + else if (IndirectFieldDecl const *IFD = dyn_cast(GD.getDecl())) mangleName(IFD->getAnonField()); else @@ -747,7 +730,7 @@ } void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) { - const FunctionDecl *FD = cast(GD.getDecl()); + FunctionDecl const *FD = cast(GD.getDecl()); // ::= // Don't mangle in the type if this isn't a decl we should typically mangle. @@ -780,7 +763,7 @@ // Get tags from return type that are not present in function name or // encoding. - const AbiTagList &UsedAbiTags = + AbiTagList const &UsedAbiTags = FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags(); AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size()); AdditionalAbiTags.erase( @@ -798,7 +781,7 @@ extendSubstitutions(&FunctionEncodingMangler); } -void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) { +void CXXNameMangler::mangleFunctionEncodingBareType(FunctionDecl const *FD) { if (FD->hasAttr()) { FunctionTypeDepthState Saved = FunctionTypeDepth.push(); Out << "Ua9enable_ifI"; @@ -860,7 +843,7 @@ MangleReturnType, FD); } -static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) { +static DeclContext const *IgnoreLinkageSpecDecls(DeclContext const *DC) { while (isa(DC)) { DC = getEffectiveParentContext(DC); } @@ -869,44 +852,44 @@ } /// Return whether a given namespace is the 'std' namespace. -static bool isStd(const NamespaceDecl *NS) { +static bool isStd(NamespaceDecl const *NS) { if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS)) - ->isTranslationUnit()) + ->isTranslationUnit()) return false; - const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); + IdentifierInfo const *II = NS->getOriginalNamespace()->getIdentifier(); return II && II->isStr("std"); } // isStdNamespace - Return whether a given decl context is a toplevel 'std' // namespace. -static bool isStdNamespace(const DeclContext *DC) { +static bool isStdNamespace(DeclContext const *DC) { if (!DC->isNamespace()) return false; return isStd(cast(DC)); } -static const GlobalDecl -isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) { - const NamedDecl *ND = cast(GD.getDecl()); +static const GlobalDecl isTemplate(GlobalDecl GD, + TemplateArgumentList const *&TemplateArgs) { + NamedDecl const *ND = cast(GD.getDecl()); // Check if we have a function template. - if (const FunctionDecl *FD = dyn_cast(ND)) { - if (const TemplateDecl *TD = FD->getPrimaryTemplate()) { + if (FunctionDecl const *FD = dyn_cast(ND)) { + if (TemplateDecl const *TD = FD->getPrimaryTemplate()) { TemplateArgs = FD->getTemplateSpecializationArgs(); return GD.getWithDecl(TD); } } // Check if we have a class template. - if (const ClassTemplateSpecializationDecl *Spec = - dyn_cast(ND)) { + if (ClassTemplateSpecializationDecl const *Spec = + dyn_cast(ND)) { TemplateArgs = &Spec->getTemplateArgs(); return GD.getWithDecl(Spec->getSpecializedTemplate()); } // Check if we have a variable template. - if (const VarTemplateSpecializationDecl *Spec = + if (VarTemplateSpecializationDecl const *Spec = dyn_cast(ND)) { TemplateArgs = &Spec->getTemplateArgs(); return GD.getWithDecl(Spec->getSpecializedTemplate()); @@ -916,13 +899,13 @@ } static TemplateName asTemplateName(GlobalDecl GD) { - const TemplateDecl *TD = dyn_cast_or_null(GD.getDecl()); - return TemplateName(const_cast(TD)); + TemplateDecl const *TD = dyn_cast_or_null(GD.getDecl()); + return TemplateName(const_cast(TD)); } void CXXNameMangler::mangleName(GlobalDecl GD) { - const NamedDecl *ND = cast(GD.getDecl()); - if (const VarDecl *VD = dyn_cast(ND)) { + NamedDecl const *ND = cast(GD.getDecl()); + if (VarDecl const *VD = dyn_cast(ND)) { // Variables should have implicit tags from its type. AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD); if (VariableTypeAbiTags.empty()) { @@ -938,7 +921,7 @@ VariableNameMangler.mangleNameWithAbiTags(VD, nullptr); // Get tags from variable type that are not present in its name. - const AbiTagList &UsedAbiTags = + AbiTagList const &UsedAbiTags = VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags(); AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size()); AdditionalAbiTags.erase( @@ -954,15 +937,15 @@ } } -void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD, - const AbiTagList *AdditionalAbiTags) { - const NamedDecl *ND = cast(GD.getDecl()); +void CXXNameMangler::mangleNameWithAbiTags( + GlobalDecl GD, AbiTagList const *AdditionalAbiTags) { + NamedDecl const *ND = cast(GD.getDecl()); // ::= [] // ::= [] // ::= [] // ::= // - const DeclContext *DC = getEffectiveDeclContext(ND); + DeclContext const *DC = getEffectiveDeclContext(ND); // If this is an extern variable declared locally, the relevant DeclContext // is that of the containing namespace, or the translation unit. @@ -993,14 +976,14 @@ // Closures can require a nested-name mangling even if they're semantically // in the global namespace. - if (const NamedDecl *PrefixND = getClosurePrefix(ND)) { + if (NamedDecl const *PrefixND = getClosurePrefix(ND)) { mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags); return; } if (DC->isTranslationUnit() || isStdNamespace(DC)) { // Check if we have a template. - const TemplateArgumentList *TemplateArgs = nullptr; + TemplateArgumentList const *TemplateArgs = nullptr; if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) { mangleUnscopedTemplateName(TD, AdditionalAbiTags); mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); @@ -1014,7 +997,7 @@ mangleNestedName(GD, DC, AdditionalAbiTags); } -void CXXNameMangler::mangleModuleName(const Module *M) { +void CXXNameMangler::mangleModuleName(Module const *M) { // Implement the C++ Modules TS name mangling proposal; see // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile // @@ -1049,10 +1032,10 @@ ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()}); } -void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD, - const TemplateArgument *TemplateArgs, +void CXXNameMangler::mangleTemplateName(TemplateDecl const *TD, + TemplateArgument const *TemplateArgs, unsigned NumTemplateArgs) { - const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD)); + DeclContext const *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD)); if (DC->isTranslationUnit() || isStdNamespace(DC)) { mangleUnscopedTemplateName(TD, nullptr); @@ -1063,8 +1046,8 @@ } void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, - const AbiTagList *AdditionalAbiTags) { - const NamedDecl *ND = cast(GD.getDecl()); + AbiTagList const *AdditionalAbiTags) { + NamedDecl const *ND = cast(GD.getDecl()); // ::= // ::= St # ::std:: @@ -1075,28 +1058,29 @@ } void CXXNameMangler::mangleUnscopedTemplateName( - GlobalDecl GD, const AbiTagList *AdditionalAbiTags) { - const TemplateDecl *ND = cast(GD.getDecl()); + GlobalDecl GD, AbiTagList const *AdditionalAbiTags) { + TemplateDecl const *ND = cast(GD.getDecl()); // ::= // ::= if (mangleSubstitution(ND)) return; // ::= - if (const auto *TTP = dyn_cast(ND)) { + if (auto const *TTP = dyn_cast(ND)) { assert(!AdditionalAbiTags && "template template param cannot have abi tags"); mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); } else if (isa(ND) || isa(ND)) { mangleUnscopedName(GD, AdditionalAbiTags); } else { - mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), AdditionalAbiTags); + mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), + AdditionalAbiTags); } addSubstitution(ND); } -void CXXNameMangler::mangleFloat(const llvm::APFloat &f) { +void CXXNameMangler::mangleFloat(llvm::APFloat const &f) { // ABI: // Floating-point literals are encoded using a fixed-length // lowercase hexadecimal string corresponding to the internal @@ -1128,17 +1112,15 @@ hexDigit &= 0xF; // Map that over to a lowercase hex digit. - static const char charForHex[16] = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' - }; + static char const charForHex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; buffer[stringIndex] = charForHex[hexDigit]; } Out.write(buffer.data(), numCharacters); } -void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) { +void CXXNameMangler::mangleFloatLiteral(QualType T, llvm::APFloat const &V) { Out << 'L'; mangleType(T); mangleFloat(V); @@ -1159,7 +1141,7 @@ Out << "0E"; } -void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) { +void CXXNameMangler::mangleNumber(llvm::APSInt const &Value) { if (Value.isSigned() && Value.isNegative()) { Out << 'n'; Value.abs().print(Out, /*signed*/ false); @@ -1199,7 +1181,7 @@ } void CXXNameMangler::manglePrefix(QualType type) { - if (const auto *TST = type->getAs()) { + if (auto const *TST = type->getAs()) { if (!mangleSubstitution(QualType(TST, 0))) { mangleTemplatePrefix(TST->getTemplateName()); @@ -1210,7 +1192,7 @@ TST->getNumArgs()); addSubstitution(QualType(TST, 0)); } - } else if (const auto *DTST = + } else if (auto const *DTST = type->getAs()) { if (!mangleSubstitution(QualType(DTST, 0))) { TemplateName Template = getASTContext().getDependentTemplateName( @@ -1284,7 +1266,7 @@ case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: { - const Type *type = qualifier->getAsType(); + Type const *type = qualifier->getAsType(); // We only want to use an unresolved-type encoding if this is one of: // - a decltype @@ -1328,36 +1310,37 @@ /// weren't resolved to specific entities. void CXXNameMangler::mangleUnresolvedName( NestedNameSpecifier *qualifier, DeclarationName name, - const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs, + TemplateArgumentLoc const *TemplateArgs, unsigned NumTemplateArgs, unsigned knownArity) { - if (qualifier) mangleUnresolvedPrefix(qualifier); + if (qualifier) + mangleUnresolvedPrefix(qualifier); switch (name.getNameKind()) { - // ::= - case DeclarationName::Identifier: - mangleSourceName(name.getAsIdentifierInfo()); - break; - // ::= dn - case DeclarationName::CXXDestructorName: - Out << "dn"; - mangleUnresolvedTypeOrSimpleId(name.getCXXNameType()); - break; - // ::= on - case DeclarationName::CXXConversionFunctionName: - case DeclarationName::CXXLiteralOperatorName: - case DeclarationName::CXXOperatorName: - Out << "on"; - mangleOperatorName(name, knownArity); - break; - case DeclarationName::CXXConstructorName: - llvm_unreachable("Can't mangle a constructor name!"); - case DeclarationName::CXXUsingDirective: - llvm_unreachable("Can't mangle a using directive name!"); - case DeclarationName::CXXDeductionGuideName: - llvm_unreachable("Can't mangle a deduction guide name!"); - case DeclarationName::ObjCMultiArgSelector: - case DeclarationName::ObjCOneArgSelector: - case DeclarationName::ObjCZeroArgSelector: - llvm_unreachable("Can't mangle Objective-C selector names here!"); + // ::= + case DeclarationName::Identifier: + mangleSourceName(name.getAsIdentifierInfo()); + break; + // ::= dn + case DeclarationName::CXXDestructorName: + Out << "dn"; + mangleUnresolvedTypeOrSimpleId(name.getCXXNameType()); + break; + // ::= on + case DeclarationName::CXXConversionFunctionName: + case DeclarationName::CXXLiteralOperatorName: + case DeclarationName::CXXOperatorName: + Out << "on"; + mangleOperatorName(name, knownArity); + break; + case DeclarationName::CXXConstructorName: + llvm_unreachable("Can't mangle a constructor name!"); + case DeclarationName::CXXUsingDirective: + llvm_unreachable("Can't mangle a using directive name!"); + case DeclarationName::CXXDeductionGuideName: + llvm_unreachable("Can't mangle a deduction guide name!"); + case DeclarationName::ObjCMultiArgSelector: + case DeclarationName::ObjCOneArgSelector: + case DeclarationName::ObjCZeroArgSelector: + llvm_unreachable("Can't mangle Objective-C selector names here!"); } // The and on productions end in an optional @@ -1366,18 +1349,17 @@ mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs); } -void CXXNameMangler::mangleUnqualifiedName(GlobalDecl GD, - DeclarationName Name, - unsigned KnownArity, - const AbiTagList *AdditionalAbiTags) { - const NamedDecl *ND = cast_or_null(GD.getDecl()); +void CXXNameMangler::mangleUnqualifiedName( + GlobalDecl GD, DeclarationName Name, unsigned KnownArity, + AbiTagList const *AdditionalAbiTags) { + NamedDecl const *ND = cast_or_null(GD.getDecl()); unsigned Arity = KnownArity; // ::= // ::= // ::= switch (Name.getNameKind()) { case DeclarationName::Identifier: { - const IdentifierInfo *II = Name.getAsIdentifierInfo(); + IdentifierInfo const *II = Name.getAsIdentifierInfo(); // We mangle decomposition declarations as the names of their bindings. if (auto *DD = dyn_cast(ND)) { @@ -1432,9 +1414,9 @@ Out << 'L'; auto *FD = dyn_cast(ND); - bool IsRegCall = FD && - FD->getType()->castAs()->getCallConv() == - clang::CC_X86RegCall; + bool IsRegCall = + FD && FD->getType()->castAs()->getCallConv() == + clang::CC_X86RegCall; bool IsDeviceStub = FD && FD->hasAttr() && GD.getKernelReferenceKind() == KernelReferenceKind::Stub; @@ -1452,7 +1434,7 @@ // Otherwise, an anonymous entity. We must have a declaration. assert(ND && "mangling empty name without declaration"); - if (const NamespaceDecl *NS = dyn_cast(ND)) { + if (NamespaceDecl const *NS = dyn_cast(ND)) { if (NS->isAnonymousNamespace()) { // This is how gcc mangles these names. Out << "12_GLOBAL__N_1"; @@ -1460,9 +1442,9 @@ } } - if (const VarDecl *VD = dyn_cast(ND)) { + if (VarDecl const *VD = dyn_cast(ND)) { // We must have an anonymous union or struct declaration. - const RecordDecl *RD = VD->getType()->castAs()->getDecl(); + RecordDecl const *RD = VD->getType()->castAs()->getDecl(); // Itanium C++ ABI 5.1.2: // @@ -1473,14 +1455,15 @@ // the data members in the union are unnamed), then there is no way for // a program to refer to the anonymous union, and there is therefore no // need to mangle its name. - assert(RD->isAnonymousStructOrUnion() - && "Expected anonymous struct or union!"); - const FieldDecl *FD = RD->findFirstNamedDataMember(); + assert(RD->isAnonymousStructOrUnion() && + "Expected anonymous struct or union!"); + FieldDecl const *FD = RD->findFirstNamedDataMember(); // It's actually possible for various reasons for us to get here // with an empty anonymous struct / union. Fortunately, it // doesn't really matter what name we generate. - if (!FD) break; + if (!FD) + break; assert(FD->getIdentifier() && "Data member name isn't an identifier!"); mangleSourceName(FD->getIdentifier()); @@ -1498,8 +1481,8 @@ break; // We must have an anonymous struct. - const TagDecl *TD = cast(ND); - if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { + TagDecl const *TD = cast(ND); + if (TypedefNameDecl const *D = TD->getTypedefNameForAnonDecl()) { assert(TD->getDeclContext() == D->getDeclContext() && "Typedef should not be in another decl context!"); assert(D->getDeclName().getAsIdentifierInfo() && @@ -1517,7 +1500,7 @@ // ::= Ul E [ ] _ // ::= * + // # Parameter types or 'v' for 'void'. - if (const CXXRecordDecl *Record = dyn_cast(TD)) { + if (CXXRecordDecl const *Record = dyn_cast(TD)) { if (Record->isLambda() && (Record->getLambdaManglingNumber() || Context.getDiscriminatorOverride()( Context.getASTContext(), Record))) { @@ -1560,9 +1543,9 @@ llvm_unreachable("Can't mangle Objective-C selector names here!"); case DeclarationName::CXXConstructorName: { - const CXXRecordDecl *InheritedFrom = nullptr; + CXXRecordDecl const *InheritedFrom = nullptr; TemplateName InheritedTemplateName; - const TemplateArgumentList *InheritedTemplateArgs = nullptr; + TemplateArgumentList const *InheritedTemplateArgs = nullptr; if (auto Inherited = cast(ND)->getInheritedConstructor()) { InheritedFrom = Inherited.getConstructor()->getParent(); @@ -1607,7 +1590,7 @@ Arity = cast(ND)->getNumParams(); // If we have a member function, we need to include the 'this' pointer. - if (const auto *MD = dyn_cast(ND)) + if (auto const *MD = dyn_cast(ND)) if (!MD->isStatic()) Arity++; } @@ -1626,7 +1609,7 @@ } } -void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) { +void CXXNameMangler::mangleRegCallName(IdentifierInfo const *II) { // ::= __regcall3__ // ::= [n] // ::= @@ -1634,7 +1617,7 @@ << II->getName(); } -void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) { +void CXXNameMangler::mangleDeviceStubName(IdentifierInfo const *II) { // ::= __device_stub__ // ::= [n] // ::= @@ -1642,25 +1625,24 @@ << II->getName(); } -void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) { +void CXXNameMangler::mangleSourceName(IdentifierInfo const *II) { // ::= // ::= [n] // ::= Out << II->getLength() << II->getName(); } -void CXXNameMangler::mangleNestedName(GlobalDecl GD, - const DeclContext *DC, - const AbiTagList *AdditionalAbiTags, +void CXXNameMangler::mangleNestedName(GlobalDecl GD, DeclContext const *DC, + AbiTagList const *AdditionalAbiTags, bool NoFunction) { - const NamedDecl *ND = cast(GD.getDecl()); + NamedDecl const *ND = cast(GD.getDecl()); // // ::= N [] [] E // ::= N [] [] // E Out << 'N'; - if (const CXXMethodDecl *Method = dyn_cast(ND)) { + if (CXXMethodDecl const *Method = dyn_cast(ND)) { Qualifiers MethodQuals = Method->getMethodQualifiers(); // We do not consider restrict a distinguishing attribute for overloading // purposes so we must not mangle it. @@ -1670,7 +1652,7 @@ } // Check if we have a template. - const TemplateArgumentList *TemplateArgs = nullptr; + TemplateArgumentList const *TemplateArgs = nullptr; if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) { mangleTemplatePrefix(TD, NoFunction); mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); @@ -1681,8 +1663,8 @@ Out << 'E'; } -void CXXNameMangler::mangleNestedName(const TemplateDecl *TD, - const TemplateArgument *TemplateArgs, +void CXXNameMangler::mangleNestedName(TemplateDecl const *TD, + TemplateArgument const *TemplateArgs, unsigned NumTemplateArgs) { // ::= N [] E @@ -1695,8 +1677,8 @@ } void CXXNameMangler::mangleNestedNameWithClosurePrefix( - GlobalDecl GD, const NamedDecl *PrefixND, - const AbiTagList *AdditionalAbiTags) { + GlobalDecl GD, NamedDecl const *PrefixND, + AbiTagList const *AdditionalAbiTags) { // A represents a variable or field, not a regular // DeclContext, so needs special handling. In this case we're mangling a // limited form of : @@ -1711,7 +1693,7 @@ Out << 'E'; } -static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) { +static GlobalDecl getParentOfLocalEntity(DeclContext const *DC) { GlobalDecl GD; // The Itanium spec says: // For entities in constructors and destructors, the mangling of the @@ -1727,25 +1709,25 @@ } void CXXNameMangler::mangleLocalName(GlobalDecl GD, - const AbiTagList *AdditionalAbiTags) { - const Decl *D = GD.getDecl(); + AbiTagList const *AdditionalAbiTags) { + Decl const *D = GD.getDecl(); // := Z E [] // := Z E s [] // := Z E d [ ] // _ // := _ assert(isa(D) || isa(D)); - const RecordDecl *RD = GetLocalClassDecl(D); - const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D); + RecordDecl const *RD = GetLocalClassDecl(D); + DeclContext const *DC = getEffectiveDeclContext(RD ? RD : D); Out << 'Z'; { AbiTagState LocalAbiTags(AbiTags); - if (const ObjCMethodDecl *MD = dyn_cast(DC)) + if (ObjCMethodDecl const *MD = dyn_cast(DC)) mangleObjCMethodName(MD); - else if (const BlockDecl *BD = dyn_cast(DC)) + else if (BlockDecl const *BD = dyn_cast(DC)) mangleBlockForPrefix(BD); else mangleFunctionEncoding(getParentOfLocalEntity(DC)); @@ -1766,12 +1748,12 @@ // will of course contain a : Its // numbering will be local to the particular argument in which it appears // -- other default arguments do not affect its encoding. - const CXXRecordDecl *CXXRD = dyn_cast(RD); + CXXRecordDecl const *CXXRD = dyn_cast(RD); if (CXXRD && CXXRD->isLambda()) { - if (const ParmVarDecl *Parm - = dyn_cast_or_null(CXXRD->getLambdaContextDecl())) { - if (const FunctionDecl *Func - = dyn_cast(Parm->getDeclContext())) { + if (ParmVarDecl const *Parm = + dyn_cast_or_null(CXXRD->getLambdaContextDecl())) { + if (FunctionDecl const *Func = + dyn_cast(Parm->getDeclContext())) { Out << 'd'; unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); if (Num > 1) @@ -1783,27 +1765,27 @@ // Mangle the name relative to the closest enclosing function. // equality ok because RD derived from ND above - if (D == RD) { + if (D == RD) { mangleUnqualifiedName(RD, AdditionalAbiTags); - } else if (const BlockDecl *BD = dyn_cast(D)) { - if (const NamedDecl *PrefixND = getClosurePrefix(BD)) + } else if (BlockDecl const *BD = dyn_cast(D)) { + if (NamedDecl const *PrefixND = getClosurePrefix(BD)) mangleClosurePrefix(PrefixND, true /*NoFunction*/); else manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/); assert(!AdditionalAbiTags && "Block cannot have additional abi tags"); mangleUnqualifiedBlock(BD); } else { - const NamedDecl *ND = cast(D); + NamedDecl const *ND = cast(D); mangleNestedName(GD, getEffectiveDeclContext(ND), AdditionalAbiTags, true /*NoFunction*/); } - } else if (const BlockDecl *BD = dyn_cast(D)) { + } else if (BlockDecl const *BD = dyn_cast(D)) { // Mangle a block in a default parameter; see above explanation for // lambdas. - if (const ParmVarDecl *Parm - = dyn_cast_or_null(BD->getBlockManglingContextDecl())) { - if (const FunctionDecl *Func - = dyn_cast(Parm->getDeclContext())) { + if (ParmVarDecl const *Parm = + dyn_cast_or_null(BD->getBlockManglingContextDecl())) { + if (FunctionDecl const *Func = + dyn_cast(Parm->getDeclContext())) { Out << 'd'; unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); if (Num > 1) @@ -1818,7 +1800,7 @@ mangleUnqualifiedName(GD, AdditionalAbiTags); } - if (const NamedDecl *ND = dyn_cast(RD ? RD : D)) { + if (NamedDecl const *ND = dyn_cast(RD ? RD : D)) { unsigned disc; if (Context.getNextDiscriminator(ND, disc)) { if (disc < 10) @@ -1829,24 +1811,24 @@ } } -void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) { +void CXXNameMangler::mangleBlockForPrefix(BlockDecl const *Block) { if (GetLocalClassDecl(Block)) { mangleLocalName(Block, /* AdditionalAbiTags */ nullptr); return; } - const DeclContext *DC = getEffectiveDeclContext(Block); + DeclContext const *DC = getEffectiveDeclContext(Block); if (isLocalContainerContext(DC)) { mangleLocalName(Block, /* AdditionalAbiTags */ nullptr); return; } - if (const NamedDecl *PrefixND = getClosurePrefix(Block)) + if (NamedDecl const *PrefixND = getClosurePrefix(Block)) mangleClosurePrefix(PrefixND); else manglePrefix(DC); mangleUnqualifiedBlock(Block); } -void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) { +void CXXNameMangler::mangleUnqualifiedBlock(BlockDecl const *Block) { // When trying to be ABI-compatibility with clang 12 and before, mangle a // now, with no substitutions and no . if (Decl *Context = Block->getBlockManglingContextDecl()) { @@ -1854,7 +1836,7 @@ LangOptions::ClangABI::Ver12 && (isa(Context) || isa(Context)) && Context->getDeclContext()->isRecord()) { - const auto *ND = cast(Context); + auto const *ND = cast(Context); if (ND->getIdentifier()) { mangleSourceNameWithAbiTags(ND); Out << 'M'; @@ -1883,7 +1865,7 @@ // ::= Tn # template non-type parameter // ::= Tt * E # template template parameter // ::= Tp # template parameter pack -void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) { +void CXXNameMangler::mangleTemplateParamDecl(NamedDecl const *Decl) { if (auto *Ty = dyn_cast(Decl)) { if (Ty->isParameterPack()) Out << "Tp"; @@ -1924,7 +1906,7 @@ } } -void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { +void CXXNameMangler::mangleLambda(CXXRecordDecl const *Lambda) { // When trying to be ABI-compatibility with clang 12 and before, mangle a // now, with no substitutions. if (Decl *Context = Lambda->getLambdaContextDecl()) { @@ -1932,10 +1914,10 @@ LangOptions::ClangABI::Ver12 && (isa(Context) || isa(Context)) && !isa(Context)) { - if (const IdentifierInfo *Name - = cast(Context)->getIdentifier()) { + if (IdentifierInfo const *Name = + cast(Context)->getIdentifier()) { mangleSourceName(Name); - const TemplateArgumentList *TemplateArgs = nullptr; + TemplateArgumentList const *TemplateArgs = nullptr; if (GlobalDecl TD = isTemplate(cast(Context), TemplateArgs)) mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); Out << 'M'; @@ -1969,7 +1951,7 @@ Out << '_'; } -void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) { +void CXXNameMangler::mangleLambdaSig(CXXRecordDecl const *Lambda) { for (auto *D : Lambda->getLambdaExplicitTemplateParameters()) mangleTemplateParamDecl(D); auto *Proto = @@ -2013,7 +1995,7 @@ llvm_unreachable("unexpected nested name specifier"); } -void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { +void CXXNameMangler::manglePrefix(DeclContext const *DC, bool NoFunction) { // ::= // ::= // ::= @@ -2031,16 +2013,16 @@ assert(!isLocalContainerContext(DC)); - const NamedDecl *ND = cast(DC); + NamedDecl const *ND = cast(DC); if (mangleSubstitution(ND)) return; // Check if we have a template-prefix or a closure-prefix. - const TemplateArgumentList *TemplateArgs = nullptr; + TemplateArgumentList const *TemplateArgs = nullptr; if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) { mangleTemplatePrefix(TD); mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); - } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) { + } else if (NamedDecl const *PrefixND = getClosurePrefix(ND)) { mangleClosurePrefix(PrefixND, NoFunction); mangleUnqualifiedName(ND, nullptr); } else { @@ -2074,7 +2056,7 @@ if (Clang11Compat && mangleSubstitution(Template)) return; - if (const IdentifierInfo *Id = Dependent->getIdentifier()) + if (IdentifierInfo const *Id = Dependent->getIdentifier()) mangleSourceName(Id); else mangleOperatorName(Dependent->getOperator(), UnknownArity); @@ -2082,9 +2064,8 @@ addSubstitution(Template); } -void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD, - bool NoFunction) { - const TemplateDecl *ND = cast(GD.getDecl()); +void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD, bool NoFunction) { + TemplateDecl const *ND = cast(GD.getDecl()); // ::=