diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp --- a/clang/lib/Sema/SemaDeclCXX.cpp +++ b/clang/lib/Sema/SemaDeclCXX.cpp @@ -41,9 +41,9 @@ #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/SemaInternal.h" #include "clang/Sema/Template.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/SmallString.h" -#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include #include @@ -171,15 +171,14 @@ } } // namespace -void -Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, - const CXXMethodDecl *Method) { +void Sema::ImplicitExceptionSpecification::CalledDecl( + SourceLocation CallLoc, const CXXMethodDecl *Method) { // If we have an MSAny spec already, don't bother. if (!Method || ComputedEST == EST_MSAny) return; - const FunctionProtoType *Proto - = Method->getType()->getAs(); + const FunctionProtoType *Proto = + Method->getType()->getAs(); Proto = Self->ResolveExceptionSpec(CallLoc, Proto); if (!Proto) return; @@ -281,10 +280,10 @@ // the same semantic constraints as the initializer expression in // a declaration of a variable of the parameter type, using the // copy-initialization semantics (8.5). - InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, - Param); - InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), - EqualLoc); + InitializedEntity Entity = + InitializedEntity::InitializeParameter(Context, Param); + InitializationKind Kind = + InitializationKind::CreateCopy(Param->getLocation(), EqualLoc); InitializationSequence InitSeq(*this, Entity, Kind, Arg); ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); if (Result.isInvalid()) @@ -304,8 +303,8 @@ // We have already instantiated this parameter; provide each of the // instantiations with the uninstantiated default argument. - UnparsedDefaultArgInstantiationsMap::iterator InstPos - = UnparsedDefaultArgInstantiations.find(Param); + UnparsedDefaultArgInstantiationsMap::iterator InstPos = + UnparsedDefaultArgInstantiations.find(Param); if (InstPos != UnparsedDefaultArgInstantiations.end()) { for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) InstPos->second[I]->setUninstantiatedDefaultArg(Arg); @@ -318,9 +317,8 @@ /// ActOnParamDefaultArgument - Check whether the default argument /// provided for a function parameter is well-formed. If so, attach it /// to the parameter declaration. -void -Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, - Expr *DefaultArg) { +void Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, + Expr *DefaultArg) { if (!param || !DefaultArg) return; @@ -336,7 +334,7 @@ // Default arguments are only permitted in C++ if (!getLangOpts().CPlusPlus) { Diag(EqualLoc, diag::err_param_default_argument) - << DefaultArg->getSourceRange(); + << DefaultArg->getSourceRange(); return Fail(); } @@ -436,10 +434,10 @@ else SR = UnparsedDefaultArgLocs[Param]; Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) - << SR; + << SR; } else if (Param->getDefaultArg()) { Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) - << Param->getDefaultArg()->getSourceRange(); + << Param->getDefaultArg()->getSourceRange(); Param->setDefaultArg(nullptr); } } @@ -466,9 +464,8 @@ // The declaration context corresponding to the scope is the semantic // parent, unless this is a local function declaration, in which case // it is that surrounding function. - DeclContext *ScopeDC = New->isLocalExternDecl() - ? New->getLexicalDeclContext() - : New->getDeclContext(); + DeclContext *ScopeDC = New->isLocalExternDecl() ? New->getLexicalDeclContext() + : New->getDeclContext(); // Find the previous declaration for the purpose of default arguments. FunctionDecl *PrevForDefaultArgs = Old; @@ -532,7 +529,7 @@ if (OldParamHasDfl && NewParamHasDfl) { unsigned DiagDefaultParamID = - diag::err_param_default_argument_redefinition; + diag::err_param_default_argument_redefinition; // MSVC accepts that default parameters be redefined for member functions // of template class. The new default parameter's value is ignored. @@ -544,7 +541,7 @@ NewParam->setHasInheritedDefaultArg(); if (OldParam->hasUninstantiatedDefaultArg()) NewParam->setUninstantiatedDefaultArg( - OldParam->getUninstantiatedDefaultArg()); + OldParam->getUninstantiatedDefaultArg()); else NewParam->setDefaultArg(OldParam->getInit()); DiagDefaultParamID = diag::ext_param_default_argument_redefinition; @@ -561,18 +558,18 @@ // void g(int (*fp)(int) = f); // void g(int (*fp)(int) = &f); Diag(NewParam->getLocation(), DiagDefaultParamID) - << NewParam->getDefaultArgRange(); + << NewParam->getDefaultArgRange(); // Look for the function declaration where the default argument was // actually written, which may be a declaration prior to Old. - for (auto Older = PrevForDefaultArgs; - OldParam->hasInheritedDefaultArg(); /**/) { + for (auto Older = PrevForDefaultArgs; OldParam->hasInheritedDefaultArg(); + /**/) { Older = Older->getPreviousDecl(); OldParam = Older->getParamDecl(p); } Diag(OldParam->getLocation(), diag::note_previous_definition) - << OldParam->getDefaultArgRange(); + << OldParam->getDefaultArgRange(); } else if (OldParamHasDfl) { // Merge the old default argument into the new parameter unless the new // function is a friend declaration in a template class. In the latter @@ -587,7 +584,7 @@ NewParam->setUnparsedDefaultArg(); else if (OldParam->hasUninstantiatedDefaultArg()) NewParam->setUninstantiatedDefaultArg( - OldParam->getUninstantiatedDefaultArg()); + OldParam->getUninstantiatedDefaultArg()); else NewParam->setDefaultArg(OldParam->getInit()); } @@ -596,12 +593,12 @@ // Paragraph 4, quoted above, only applies to non-template functions. Diag(NewParam->getLocation(), diag::err_param_default_argument_template_redecl) - << NewParam->getDefaultArgRange(); + << NewParam->getDefaultArgRange(); Diag(PrevForDefaultArgs->getLocation(), diag::note_template_prev_declaration) << false; - } else if (New->getTemplateSpecializationKind() - != TSK_ImplicitInstantiation && + } else if (New->getTemplateSpecializationKind() != + TSK_ImplicitInstantiation && New->getTemplateSpecializationKind() != TSK_Undeclared) { // C++ [temp.expr.spec]p21: // Default function arguments shall not be specified in a declaration @@ -613,9 +610,9 @@ // member function specialization belongs is implicitly // instantiated. Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) - << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) - << New->getDeclName() - << NewParam->getDefaultArgRange(); + << (New->getTemplateSpecializationKind() == + TSK_ExplicitSpecialization) + << New->getDeclName() << NewParam->getDefaultArgRange(); } else if (New->getDeclContext()->isDependentContext()) { // C++ [dcl.fct.default]p6 (DR217): // Default arguments for a member function of a class template shall @@ -627,8 +624,8 @@ // arguments for an out-of-line definition of a member function of a // dependent type. int WhichKind = 2; - if (CXXRecordDecl *Record - = dyn_cast(New->getDeclContext())) { + if (CXXRecordDecl *Record = + dyn_cast(New->getDeclContext())) { if (Record->getDescribedClassTemplate()) WhichKind = 0; else if (isa(Record)) @@ -639,8 +636,7 @@ Diag(NewParam->getLocation(), diag::err_param_default_argument_member_template_redecl) - << WhichKind - << NewParam->getDefaultArgRange(); + << WhichKind << NewParam->getDefaultArgRange(); } } } @@ -656,7 +652,7 @@ ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); assert(NewParam->hasDefaultArg()); Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) - << NewParam->getDefaultArgRange() << NewSM; + << NewParam->getDefaultArgRange() << NewSM; Diag(Old->getLocation(), diag::note_previous_declaration); } } @@ -679,8 +675,8 @@ (New->isInlineSpecified() || New->getFriendObjectKind() == Decl::FOK_None)) { // C++11 [dcl.fcn.spec]p4: - // If the definition of a function appears in a translation unit before its - // first declaration as inline, the program is ill-formed. + // If the definition of a function appears in a translation unit before + // its first declaration as inline, the program is ill-formed. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; Diag(Def->getLocation(), diag::note_previous_definition); Invalid = true; @@ -732,7 +728,7 @@ // cases than that. if (!D.mayHaveDecompositionDeclarator()) { Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) - << Decomp.getSourceRange(); + << Decomp.getSourceRange(); return nullptr; } @@ -744,12 +740,11 @@ return nullptr; } - Diag(Decomp.getLSquareLoc(), - !getLangOpts().CPlusPlus17 - ? diag::ext_decomp_decl - : D.getContext() == DeclaratorContext::Condition - ? diag::ext_decomp_decl_cond - : diag::warn_cxx14_compat_decomp_decl) + Diag(Decomp.getLSquareLoc(), !getLangOpts().CPlusPlus17 + ? diag::ext_decomp_decl + : D.getContext() == DeclaratorContext::Condition + ? diag::ext_decomp_decl_cond + : diag::warn_cxx14_compat_decomp_decl) << Decomp.getSourceRange(); // The semantic context is always just the current context. @@ -836,8 +831,8 @@ // The syntax only allows a single ref-qualifier prior to the decomposition // declarator. No other declarator chunks are permitted. Also check the type // specifier here. - if (DS.getTypeSpecType() != DeclSpec::TST_auto || - D.hasGroupingParens() || D.getNumTypeObjects() > 1 || + if (DS.getTypeSpecType() != DeclSpec::TST_auto || D.hasGroupingParens() || + D.getNumTypeObjects() > 1 || (D.getNumTypeObjects() == 1 && D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { Diag(Decomp.getLSquareLoc(), @@ -870,7 +865,7 @@ } // Build the BindingDecls. - SmallVector Bindings; + SmallVector Bindings; // Build the BindingDecls. for (auto &B : D.getDecompositionDeclarator().bindings()) { @@ -879,7 +874,7 @@ LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForVisibleRedeclaration); LookupName(Previous, S, - /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); + /*CreateBuiltins*/ DC->getRedeclContext()->isTranslationUnit()); // It's not permitted to shadow a template parameter name. if (Previous.isSingleResult() && @@ -899,7 +894,7 @@ bool ConsiderLinkage = DC->isFunctionOrMethod() && DS.getStorageClassSpec() == DeclSpec::SCS_extern; FilterLookupForScope(Previous, DC, S, ConsiderLinkage, - /*AllowInlineNamespace*/false); + /*AllowInlineNamespace*/ false); if (!Previous.empty()) { auto *Old = Previous.getRepresentativeDecl(); @@ -978,7 +973,7 @@ }); } -static bool checkArrayDecomposition(Sema &S, ArrayRef Bindings, +static bool checkArrayDecomposition(Sema &S, ArrayRef Bindings, ValueDecl *Src, QualType DecompType, const ConstantArrayType *CAT) { return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, @@ -986,7 +981,7 @@ CAT->getElementType()); } -static bool checkVectorDecomposition(Sema &S, ArrayRef Bindings, +static bool checkVectorDecomposition(Sema &S, ArrayRef Bindings, ValueDecl *Src, QualType DecompType, const VectorType *VT) { return checkArrayLikeDecomposition( @@ -995,8 +990,7 @@ DecompType.getQualifiers())); } -static bool checkComplexDecomposition(Sema &S, - ArrayRef Bindings, +static bool checkComplexDecomposition(Sema &S, ArrayRef Bindings, ValueDecl *Src, QualType DecompType, const ComplexType *CT) { return checkSimpleDecomposition( @@ -1048,8 +1042,8 @@ // missing specialization, because this can only fail if the user has been // declaring their own names in namespace std or we don't support the // standard library implementation in use. - LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), - Loc, Sema::LookupOrdinaryName); + LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), Loc, + Sema::LookupOrdinaryName); if (!S.LookupQualifiedName(Result, Std)) return DiagnoseMissing(); if (Result.isAmbiguous()) @@ -1097,7 +1091,9 @@ return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); } -namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } +namespace { +enum class IsTupleLike { TupleLike, NotTupleLike, Error }; +} static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, llvm::APSInt &Size) { @@ -1134,7 +1130,7 @@ } Diagnoser(R, Args); ExprResult E = - S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); + S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/ false); if (E.isInvalid()) return IsTupleLike::Error; @@ -1146,8 +1142,8 @@ } /// \return std::tuple_element::type. -static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, - unsigned I, QualType T) { +static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, unsigned I, + QualType T) { // Form template argument list for tuple_element. TemplateArgumentListInfo Args(Loc, Loc); Args.addArgument( @@ -1185,11 +1181,9 @@ Ctx.Entity = BD; S.pushCodeSynthesisContext(Ctx); } - ~InitializingBinding() { - S.popCodeSynthesisContext(); - } + ~InitializingBinding() { S.popCodeSynthesisContext(); } }; -} +} // namespace static bool checkTupleLikeDecomposition(Sema &S, ArrayRef Bindings, @@ -1269,7 +1263,7 @@ // in the associated namespaces. Expr *Get = UnresolvedLookupExpr::Create( S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), - DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, + DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/ true, &Args, UnresolvedSetIterator(), UnresolvedSetIterator()); Expr *Arg = E.get(); @@ -1314,9 +1308,8 @@ RefVD->setInit(E.get()); S.CheckCompleteVariableDeclaration(RefVD); - E = S.BuildDeclarationNameExpr(CXXScopeSpec(), - DeclarationNameInfo(B->getDeclName(), Loc), - RefVD); + E = S.BuildDeclarationNameExpr( + CXXScopeSpec(), DeclarationNameInfo(B->getDeclName(), Loc), RefVD); if (E.isInvalid()) return true; @@ -1327,9 +1320,9 @@ return false; } -/// Find the base class to decompose in a built-in decomposition of a class type. -/// This base class search is, unfortunately, not quite like any other that we -/// perform anywhere else in C++. +/// Find the base class to decompose in a built-in decomposition of a class +/// type. This base class search is, unfortunately, not quite like any other +/// that we perform anywhere else in C++. static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, const CXXRecordDecl *RD, CXXCastPath &BasePath) { @@ -1348,11 +1341,11 @@ else { // ... or of ... CXXBasePaths Paths; - Paths.setOrigin(const_cast(RD)); + Paths.setOrigin(const_cast(RD)); if (!RD->lookupInBases(BaseHasFields, Paths)) { // If no classes have fields, just decompose RD itself. (This will work // if and only if zero bindings were provided.) - return DeclAccessPair::make(const_cast(RD), AS_public); + return DeclAccessPair::make(const_cast(RD), AS_public); } CXXBasePath *BestPath = nullptr; @@ -1363,8 +1356,8 @@ BestPath->back().Base->getType())) { // ... the same ... S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) - << false << RD << BestPath->back().Base->getType() - << P.back().Base->getType(); + << false << RD << BestPath->back().Base->getType() + << P.back().Base->getType(); return DeclAccessPair(); } else if (P.Access < BestPath->Access) { BestPath = &P; @@ -1375,7 +1368,7 @@ QualType BaseType = BestPath->back().Base->getType(); if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) - << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); + << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); return DeclAccessPair(); } @@ -1393,15 +1386,15 @@ CXXBasePaths Paths; if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) - << (ClassWithFields == RD) << RD << ClassWithFields - << Paths.front().back().Base->getType(); + << (ClassWithFields == RD) << RD << ClassWithFields + << Paths.front().back().Base->getType(); return DeclAccessPair(); } - return DeclAccessPair::make(const_cast(ClassWithFields), AS); + return DeclAccessPair::make(const_cast(ClassWithFields), AS); } -static bool checkMemberDecomposition(Sema &S, ArrayRef Bindings, +static bool checkMemberDecomposition(Sema &S, ArrayRef Bindings, ValueDecl *Src, QualType DecompType, const CXXRecordDecl *OrigRD) { if (S.RequireCompleteType(Src->getLocation(), DecompType, @@ -1446,7 +1439,7 @@ if (FD->isAnonymousStructOrUnion()) { S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) - << DecompType << FD->getType()->isUnionType(); + << DecompType << FD->getType()->isUnionType(); S.Diag(FD->getLocation(), diag::note_declared_at); return true; } @@ -1513,7 +1506,7 @@ } DecompType = DecompType.getNonReferenceType(); - ArrayRef Bindings = DD->bindings(); + ArrayRef Bindings = DD->bindings(); // C++1z [dcl.decomp]/2: // If E is an array type [...] @@ -1606,8 +1599,8 @@ // libraries are hopefully not as broken so that we don't need these // workarounds. if (CheckEquivalentExceptionSpec( - OldType->getAs(), Old->getLocation(), - NewType->getAs(), New->getLocation())) { + OldType->getAs(), Old->getLocation(), + NewType->getAs(), New->getLocation())) { New->setInvalidDecl(); } } @@ -1650,10 +1643,9 @@ else if (Param->getIdentifier()) Diag(Param->getLocation(), diag::err_param_default_argument_missing_name) - << Param->getIdentifier(); + << Param->getIdentifier(); else - Diag(Param->getLocation(), - diag::err_param_default_argument_missing); + Diag(Param->getLocation(), diag::err_param_default_argument_missing); } } } @@ -1712,8 +1704,7 @@ /// Check whether a function's parameter types are all literal types. If so, /// return true. If not, produce a suitable diagnostic and return false. -static bool CheckConstexprParameterTypes(Sema &SemaRef, - const FunctionDecl *FD, +static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD, Sema::CheckConstexprKind Kind) { unsigned ArgIndex = 0; const auto *FT = FD->getType()->castAs(); @@ -1749,10 +1740,14 @@ /// \returns diagnostic %select index. static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { switch (Tag) { - case TTK_Struct: return 0; - case TTK_Interface: return 1; - case TTK_Class: return 2; - default: llvm_unreachable("Invalid tag kind for record diagnostic!"); + case TTK_Struct: + return 0; + case TTK_Interface: + return 1; + case TTK_Class: + return 2; + default: + llvm_unreachable("Invalid tag kind for record diagnostic!"); } } @@ -1783,8 +1778,8 @@ return false; Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) - << isa(NewFD) - << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); + << isa(NewFD) + << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); for (const auto &I : RD->vbases()) Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) << I.getSourceRange(); @@ -1801,7 +1796,8 @@ if (Method && Method->isVirtual()) { if (getLangOpts().CPlusPlus20) { if (Kind == CheckConstexprKind::Diagnose) - Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); + Diag(Method->getLocation(), + diag::warn_cxx17_compat_constexpr_virtual); } else { if (Kind == CheckConstexprKind::CheckValid) return false; @@ -1884,8 +1880,8 @@ if (Kind == Sema::CheckConstexprKind::Diagnose) { TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) - << TL.getSourceRange() << TL.getType() - << isa(Dcl); + << TL.getSourceRange() << TL.getType() + << isa(Dcl); } return false; } @@ -1946,8 +1942,8 @@ isa(Dcl))) { return false; } - if (!VD->getType()->isDependentType() && - !VD->hasInit() && !VD->isCXXForRangeDecl()) { + if (!VD->getType()->isDependentType() && !VD->hasInit() && + !VD->isCXXForRangeDecl()) { if (Kind == Sema::CheckConstexprKind::Diagnose) { SemaRef.Diag( VD->getLocation(), @@ -1964,9 +1960,9 @@ if (Kind == Sema::CheckConstexprKind::Diagnose) { SemaRef.Diag(VD->getLocation(), SemaRef.getLangOpts().CPlusPlus14 - ? diag::warn_cxx11_compat_constexpr_local_var - : diag::ext_constexpr_local_var) - << isa(Dcl); + ? diag::warn_cxx11_compat_constexpr_local_var + : diag::ext_constexpr_local_var) + << isa(Dcl); } else if (!SemaRef.getLangOpts().CPlusPlus14) { return false; } @@ -2009,7 +2005,7 @@ static bool CheckConstexprCtorInitializer(Sema &SemaRef, const FunctionDecl *Dcl, FieldDecl *Field, - llvm::SmallSet &Inits, + llvm::SmallSet &Inits, bool &Diagnosed, Sema::CheckConstexprKind Kind) { // In C++20 onwards, there's nothing to check for validity. @@ -2079,7 +2075,8 @@ // - using-directives, // - typedef declarations and alias-declarations that do not define // classes or enumerations, - if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast(S), Cxx1yLoc, Kind)) + if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast(S), Cxx1yLoc, + Kind)) return false; return true; @@ -2250,9 +2247,9 @@ case Sema::CheckConstexprKind::Diagnose: SemaRef.Diag(Body->getBeginLoc(), - !SemaRef.getLangOpts().CPlusPlus20 - ? diag::ext_constexpr_function_try_block_cxx20 - : diag::warn_cxx17_compat_constexpr_function_try_block) + !SemaRef.getLangOpts().CPlusPlus20 + ? diag::ext_constexpr_function_try_block_cxx20 + : diag::warn_cxx17_compat_constexpr_function_try_block) << isa(Dcl); break; } @@ -2286,20 +2283,20 @@ << isa(Dcl); } else if (Cxx2aLoc.isValid()) { SemaRef.Diag(Cxx2aLoc, - SemaRef.getLangOpts().CPlusPlus20 - ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt - : diag::ext_constexpr_body_invalid_stmt_cxx20) - << isa(Dcl); + SemaRef.getLangOpts().CPlusPlus20 + ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt + : diag::ext_constexpr_body_invalid_stmt_cxx20) + << isa(Dcl); } else if (Cxx1yLoc.isValid()) { SemaRef.Diag(Cxx1yLoc, - SemaRef.getLangOpts().CPlusPlus14 - ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt - : diag::ext_constexpr_body_invalid_stmt) - << isa(Dcl); + SemaRef.getLangOpts().CPlusPlus14 + ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt + : diag::ext_constexpr_body_invalid_stmt) + << isa(Dcl); } - if (const CXXConstructorDecl *Constructor - = dyn_cast(Dcl)) { + if (const CXXConstructorDecl *Constructor = + dyn_cast(Dcl)) { const CXXRecordDecl *RD = Constructor->getParent(); // DR1359: // - every non-variant non-static data member and base class sub-object @@ -2329,7 +2326,8 @@ bool AnyAnonStructUnionMembers = false; unsigned Fields = 0; for (CXXRecordDecl::field_iterator I = RD->field_begin(), - E = RD->field_end(); I != E; ++I, ++Fields) { + E = RD->field_end(); + I != E; ++I, ++Fields) { if (I->isAnonymousStructOrUnion()) { AnyAnonStructUnionMembers = true; break; @@ -2344,8 +2342,8 @@ // Check initialization of non-static data members. Base classes are // always initialized so do not need to be checked. Dependent bases // might not have initializers in the member initializer list. - llvm::SmallSet Inits; - for (const auto *I: Constructor->inits()) { + llvm::SmallSet Inits; + for (const auto *I : Constructor->inits()) { if (FieldDecl *FD = I->getMember()) Inits.insert(FD); else if (IndirectFieldDecl *ID = I->getIndirectMember()) @@ -2484,8 +2482,8 @@ CurDecl = dyn_cast_or_null(CurContext); if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && - 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) - < II->getLength()) { + 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) < + II->getLength()) { II = CurDecl->getIdentifier(); return true; } @@ -2497,7 +2495,7 @@ /// class, including looking at dependent bases. static bool findCircularInheritance(const CXXRecordDecl *Class, const CXXRecordDecl *Current) { - SmallVector Queue; + SmallVector Queue; Class = Class->getCanonicalDecl(); while (true) { @@ -2529,12 +2527,11 @@ /// /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics /// and returns NULL otherwise. -CXXBaseSpecifier * -Sema::CheckBaseSpecifier(CXXRecordDecl *Class, - SourceRange SpecifierRange, - bool Virtual, AccessSpecifier Access, - TypeSourceInfo *TInfo, - SourceLocation EllipsisLoc) { +CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class, + SourceRange SpecifierRange, + bool Virtual, AccessSpecifier Access, + TypeSourceInfo *TInfo, + SourceLocation EllipsisLoc) { // In HLSL, unspecified class access is public rather than private. if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class && Access == AS_none) @@ -2549,14 +2546,14 @@ // A union shall not have base classes. if (Class->isUnion()) { Diag(Class->getLocation(), diag::err_base_clause_on_union) - << SpecifierRange; + << SpecifierRange; return nullptr; } if (EllipsisLoc.isValid() && !TInfo->getType()->containsUnexpandedParameterPack()) { Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) - << TInfo->getTypeLoc().getSourceRange(); + << TInfo->getTypeLoc().getSourceRange(); EllipsisLoc = SourceLocation(); } @@ -2571,11 +2568,10 @@ ((BaseDecl = BaseDecl->getDefinition()) && findCircularInheritance(Class, BaseDecl))) { Diag(BaseLoc, diag::err_circular_inheritance) - << BaseType << Context.getTypeDeclType(Class); + << BaseType << Context.getTypeDeclType(Class); if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) - Diag(BaseDecl->getLocation(), diag::note_previous_decl) - << BaseType; + Diag(BaseDecl->getLocation(), diag::note_previous_decl) << BaseType; return nullptr; } @@ -2611,8 +2607,9 @@ if (Context.getTargetInfo().getCXXABI().isMicrosoft() || Context.getTargetInfo().getTriple().isPS()) { if (Attr *ClassAttr = getDLLAttr(Class)) { - if (auto *BaseTemplate = dyn_cast_or_null( - BaseType->getAsCXXRecordDecl())) { + if (auto *BaseTemplate = + dyn_cast_or_null( + BaseType->getAsCXXRecordDecl())) { propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, BaseLoc); } @@ -2622,8 +2619,8 @@ // C++ [class.derived]p2: // The class-name in a base-specifier shall not be an incompletely // defined class. - if (RequireCompleteType(BaseLoc, BaseType, - diag::err_incomplete_base_class, SpecifierRange)) { + if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class, + SpecifierRange)) { Class->setInvalidDecl(); return nullptr; } @@ -2642,10 +2639,11 @@ const auto *BaseCSA = CXXBaseDecl->getAttr(); const auto *DerivedCSA = Class->getAttr(); if ((DerivedCSA || BaseCSA) && - (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { + (!BaseCSA || !DerivedCSA || + BaseCSA->getName() != DerivedCSA->getName())) { Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) - << CXXBaseDecl; + << CXXBaseDecl; return nullptr; } @@ -2657,7 +2655,7 @@ // the flexible array member would index into the derived class. if (CXXBaseDecl->hasFlexibleArrayMember()) { Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) - << CXXBaseDecl->getDeclName(); + << CXXBaseDecl->getDeclName(); return nullptr; } @@ -2666,8 +2664,7 @@ // base-clause, the program is ill-formed. if (FinalAttr *FA = CXXBaseDecl->getAttr()) { Diag(BaseLoc, diag::err_class_marked_final_used_as_base) - << CXXBaseDecl->getDeclName() - << FA->isSpelledAsSealed(); + << CXXBaseDecl->getDeclName() << FA->isSpelledAsSealed(); Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) << CXXBaseDecl->getDeclName() << FA->getRange(); return nullptr; @@ -2722,9 +2719,8 @@ UPPC_BaseType)) return true; - if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, - Virtual, Access, TInfo, - EllipsisLoc)) + if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier( + Class, SpecifierRange, Virtual, Access, TInfo, EllipsisLoc)) return BaseSpec; else Class->setInvalidDecl(); @@ -2737,10 +2733,8 @@ typedef llvm::SmallPtrSet IndirectBaseSet; /// Recursively add the bases of Type. Don't add Type itself. -static void -NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, - const QualType &Type) -{ +static void NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, + const QualType &Type) { // Even though the incoming type is a base, it might not be // a class -- it could be a template parm, for instance. if (auto Rec = Type->getAs()) { @@ -2748,8 +2742,8 @@ // Iterate over its bases. for (const auto &BaseSpec : Decl->bases()) { - QualType Base = Context.getCanonicalType(BaseSpec.getType()) - .getUnqualifiedType(); + QualType Base = + Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType(); if (Set.insert(Base).second) // If we've not already seen it, recurse. NoteIndirectBases(Context, Set, Base); @@ -2761,14 +2755,14 @@ /// specifiers to a C++ class. bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef Bases) { - if (Bases.empty()) + if (Bases.empty()) return false; // Used to keep track of which base types we have already seen, so // that we can properly diagnose redundant direct base types. Note // that the key is always the unqualified canonical type of the base // class. - std::map KnownBaseTypes; + std::map KnownBaseTypes; // Used to track indirect bases so we can see if a direct base is // ambiguous. @@ -2778,8 +2772,7 @@ unsigned NumGoodBases = 0; bool Invalid = false; for (unsigned idx = 0; idx < Bases.size(); ++idx) { - QualType NewBaseType - = Context.getCanonicalType(Bases[idx]->getType()); + QualType NewBaseType = Context.getCanonicalType(Bases[idx]->getType()); NewBaseType = NewBaseType.getLocalUnqualifiedType(); CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; @@ -2809,8 +2802,8 @@ if (const RecordType *Record = NewBaseType->getAs()) { const CXXRecordDecl *RD = cast(Record->getDecl()); if (Class->isInterface() && - (!RD->isInterfaceLike() || - KnownBase->getAccessSpecifier() != AS_public)) { + (!RD->isInterfaceLike() || + KnownBase->getAccessSpecifier() != AS_public)) { // The Microsoft extension __interface does not permit bases that // are not themselves public interfaces. Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) @@ -2837,14 +2830,14 @@ if (BaseType->isDependentType()) continue; - CanQualType CanonicalBase = Context.getCanonicalType(BaseType) - .getUnqualifiedType(); + CanQualType CanonicalBase = + Context.getCanonicalType(BaseType).getUnqualifiedType(); if (IndirectBaseTypes.count(CanonicalBase)) { CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, /*DetectVirtual=*/true); - bool found - = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); + bool found = + Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); assert(found); (void)found; @@ -2939,10 +2932,9 @@ // Now add all bases. for (unsigned I = Start, E = Path.size(); I != E; ++I) - BasePathArray.push_back(const_cast(Path[I].Base)); + BasePathArray.push_back(const_cast(Path[I].Base)); } - void Sema::BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePathArray) { assert(BasePathArray.empty() && "Base path array must be empty!"); @@ -2961,14 +2953,10 @@ /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the /// diagnostic for the respective type of error will be suppressed, but the /// check for ill-formed code will still be performed. -bool -Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, - unsigned InaccessibleBaseID, - unsigned AmbiguousBaseConvID, - SourceLocation Loc, SourceRange Range, - DeclarationName Name, - CXXCastPath *BasePath, - bool IgnoreAccess) { +bool Sema::CheckDerivedToBaseConversion( + QualType Derived, QualType Base, unsigned InaccessibleBaseID, + unsigned AmbiguousBaseConvID, SourceLocation Loc, SourceRange Range, + DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess) { // First, determine whether the path from Derived to Base is // ambiguous. This is slightly more expensive than checking whether // the Derived to Base conversion exists, because here we need to @@ -3038,23 +3026,21 @@ std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); Diag(Loc, AmbiguousBaseConvID) - << Derived << Base << PathDisplayStr << Range << Name; + << Derived << Base << PathDisplayStr << Range << Name; } return true; } -bool -Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, - SourceLocation Loc, SourceRange Range, - CXXCastPath *BasePath, - bool IgnoreAccess) { +bool Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, + SourceLocation Loc, SourceRange Range, + CXXCastPath *BasePath, + bool IgnoreAccess) { return CheckDerivedToBaseConversion( Derived, Base, diag::err_upcast_to_inaccessible_base, diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), BasePath, IgnoreAccess); } - /// Builds a string representing ambiguous paths from a /// specific derived class to different subobjects of the same base /// class. @@ -3070,13 +3056,14 @@ std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { std::string PathDisplayStr; std::set DisplayedPaths; - for (CXXBasePaths::paths_iterator Path = Paths.begin(); - Path != Paths.end(); ++Path) { + for (CXXBasePaths::paths_iterator Path = Paths.begin(); Path != Paths.end(); + ++Path) { if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { // We haven't displayed a path to this particular base // class subobject yet. PathDisplayStr += "\n "; - PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); + PathDisplayStr += + Context.getTypeDeclType(Paths.getOrigin()).getAsString(); for (CXXBasePath::const_iterator Element = Path->begin(); Element != Path->end(); ++Element) PathDisplayStr += " -> " + Element->Base->getType().getAsString(); @@ -3095,8 +3082,8 @@ SourceLocation ColonLoc, const ParsedAttributesView &Attrs) { assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); - AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, - ASLoc, ColonLoc); + AccessSpecDecl *ASDecl = + AccessSpecDecl::Create(Context, Access, CurContext, ASLoc, ColonLoc); CurContext->addHiddenDecl(ASDecl); return ProcessAccessDeclAttributeList(ASDecl, Attrs); } @@ -3128,12 +3115,12 @@ if (OverrideAttr *OA = D->getAttr()) { Diag(OA->getLocation(), diag::override_keyword_hides_virtual_member_function) - << "override" << (OverloadedMethods.size() > 1); + << "override" << (OverloadedMethods.size() > 1); } else if (FinalAttr *FA = D->getAttr()) { Diag(FA->getLocation(), diag::override_keyword_hides_virtual_member_function) - << (FA->isSpelledAsSealed() ? "sealed" : "final") - << (OverloadedMethods.size() > 1); + << (FA->isSpelledAsSealed() ? "sealed" : "final") + << (OverloadedMethods.size() > 1); } NoteHiddenVirtualMethods(MD, OverloadedMethods); MD->setInvalidDecl(); @@ -3147,14 +3134,14 @@ if (OverrideAttr *OA = D->getAttr()) { Diag(OA->getLocation(), diag::override_keyword_only_allowed_on_virtual_member_functions) - << "override" << FixItHint::CreateRemoval(OA->getLocation()); + << "override" << FixItHint::CreateRemoval(OA->getLocation()); D->dropAttr(); } if (FinalAttr *FA = D->getAttr()) { Diag(FA->getLocation(), diag::override_keyword_only_allowed_on_virtual_member_functions) - << (FA->isSpelledAsSealed() ? "sealed" : "final") - << FixItHint::CreateRemoval(FA->getLocation()); + << (FA->isSpelledAsSealed() ? "sealed" : "final") + << FixItHint::CreateRemoval(FA->getLocation()); D->dropAttr(); } return; @@ -3167,7 +3154,7 @@ bool HasOverriddenMethods = MD->size_overridden_methods() != 0; if (MD->hasAttr() && !HasOverriddenMethods) Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) - << MD->getDeclName(); + << MD->getDeclName(); } void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { @@ -3183,7 +3170,7 @@ SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) - return; + return; if (MD->size_overridden_methods() > 0) { auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { @@ -3215,8 +3202,7 @@ return false; Diag(New->getLocation(), diag::err_final_function_overridden) - << New->getDeclName() - << FA->isSpelledAsSealed(); + << New->getDeclName() << FA->isSpelledAsSealed(); Diag(Old->getLocation(), diag::note_overridden_virtual_function); return true; } @@ -3225,8 +3211,7 @@ const Type *T = FD.getType()->getBaseElementTypeUnsafe(); // FIXME: Destruction of ObjC lifetime types has side-effects. if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) - return !RD->isCompleteDefinition() || - !RD->hasTrivialDefaultConstructor() || + return !RD->isCompleteDefinition() || !RD->hasTrivialDefaultConstructor() || !RD->hasTrivialDestructor(); return false; } @@ -3250,7 +3235,7 @@ return; // To record a shadowed field in a base - std::map Bases; + std::map Bases; auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { const auto Base = Specifier->getType()->getAsCXXRecordDecl(); @@ -3285,7 +3270,7 @@ if (AS_none != CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { Diag(Loc, diag::warn_shadow_field) - << FieldName << RD << Base << DeclIsField; + << FieldName << RD << Base << DeclIsField; Diag(BaseField->getLocation(), diag::note_shadow_field); Bases.erase(It); } @@ -3311,7 +3296,7 @@ if (Loc.isInvalid()) Loc = D.getBeginLoc(); - Expr *BitWidth = static_cast(BW); + Expr *BitWidth = static_cast(BW); assert(isa(CurContext)); assert(!DS.isFriendSpecified()); @@ -3335,7 +3320,8 @@ InvalidDecl = 2; else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) InvalidDecl = 3; - else switch (Name.getNameKind()) { + else + switch (Name.getNameKind()) { case DeclarationName::CXXConstructorName: InvalidDecl = 4; ShowDeclName = false; @@ -3354,15 +3340,15 @@ default: InvalidDecl = 0; break; - } + } if (InvalidDecl) { if (ShowDeclName) Diag(Loc, diag::err_invalid_member_in_interface) - << (InvalidDecl-1) << Name; + << (InvalidDecl - 1) << Name; else Diag(Loc, diag::err_invalid_member_in_interface) - << (InvalidDecl-1) << ""; + << (InvalidDecl - 1) << ""; return nullptr; } } @@ -3420,8 +3406,8 @@ const char *PrevSpec; unsigned DiagID; if (D.getMutableDeclSpec().SetStorageClassSpec( - *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, - Context.getPrintingPolicy())) { + *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, + Context.getPrintingPolicy())) { assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && "This is the only DeclSpec that should fail to be applied"); B << 1; @@ -3438,8 +3424,7 @@ // Data members must have identifiers for names. if (!Name.isIdentifier()) { - Diag(Loc, diag::err_bad_variable_name) - << Name; + Diag(Loc, diag::err_bad_variable_name) << Name; return nullptr; } @@ -3448,20 +3433,20 @@ // Member field could not be with "template" keyword. // So TemplateParameterLists should be empty in this case. if (TemplateParameterLists.size()) { - TemplateParameterList* TemplateParams = TemplateParameterLists[0]; + TemplateParameterList *TemplateParams = TemplateParameterLists[0]; if (TemplateParams->size()) { // There is no such thing as a member field template. Diag(D.getIdentifierLoc(), diag::err_template_member) << II << SourceRange(TemplateParams->getTemplateLoc(), - TemplateParams->getRAngleLoc()); + TemplateParams->getRAngleLoc()); } else { // There is an extraneous 'template<>' for this member. Diag(TemplateParams->getTemplateLoc(), - diag::err_template_member_noparams) + diag::err_template_member_noparams) << II << SourceRange(TemplateParams->getTemplateLoc(), - TemplateParams->getRAngleLoc()); + TemplateParams->getRAngleLoc()); } return nullptr; } @@ -3488,7 +3473,7 @@ UnqualifiedIdKind::IK_TemplateId); else Diag(D.getIdentifierLoc(), diag::err_member_qualification) - << Name << SS.getRange(); + << Name << SS.getRange(); SS.clear(); } @@ -3500,8 +3485,8 @@ return nullptr; isInstField = false; } else { - Member = HandleField(S, cast(CurContext), Loc, D, - BitWidth, InitStyle, AS); + Member = HandleField(S, cast(CurContext), Loc, D, BitWidth, + InitStyle, AS); if (!Member) return nullptr; } @@ -3520,17 +3505,17 @@ // C++ 9.6p3: A bit-field shall not be a static member. // "static member 'A' cannot be a bit-field" Diag(Loc, diag::err_static_not_bitfield) - << Name << BitWidth->getSourceRange(); + << Name << BitWidth->getSourceRange(); } else if (isa(Member)) { // "typedef member 'x' cannot be a bit-field" Diag(Loc, diag::err_typedef_not_bitfield) - << Name << BitWidth->getSourceRange(); + << Name << BitWidth->getSourceRange(); } else { // A function typedef ("typedef int f(); f a;"). // C++ 9.6p3: A bit-field shall have integral or enumeration type. Diag(Loc, diag::err_not_integral_type_bitfield) - << Name << cast(Member)->getType() - << BitWidth->getSourceRange(); + << Name << cast(Member)->getType() + << BitWidth->getSourceRange(); } BitWidth = nullptr; @@ -3601,8 +3586,7 @@ // Remember all explicit private FieldDecls that have a name, no side // effects and are not part of a dependent type declaration. if (!FD->isImplicit() && FD->getDeclName() && - FD->getAccess() == AS_private && - !FD->hasAttr() && + FD->getAccess() == AS_private && !FD->hasAttr() && !FD->getParent()->isDependentContext() && !InitializationHasSideEffects(*FD)) UnusedPrivateFields.insert(FD); @@ -3613,407 +3597,398 @@ } namespace { - class UninitializedFieldVisitor - : public EvaluatedExprVisitor { - Sema &S; - // List of Decls to generate a warning on. Also remove Decls that become - // initialized. - llvm::SmallPtrSetImpl &Decls; - // List of base classes of the record. Classes are removed after their - // initializers. - llvm::SmallPtrSetImpl &BaseClasses; - // Vector of decls to be removed from the Decl set prior to visiting the - // nodes. These Decls may have been initialized in the prior initializer. - llvm::SmallVector DeclsToRemove; - // If non-null, add a note to the warning pointing back to the constructor. - const CXXConstructorDecl *Constructor; - // Variables to hold state when processing an initializer list. When - // InitList is true, special case initialization of FieldDecls matching - // InitListFieldDecl. - bool InitList; - FieldDecl *InitListFieldDecl; - llvm::SmallVector InitFieldIndex; - - public: - typedef EvaluatedExprVisitor Inherited; - UninitializedFieldVisitor(Sema &S, - llvm::SmallPtrSetImpl &Decls, - llvm::SmallPtrSetImpl &BaseClasses) +class UninitializedFieldVisitor + : public EvaluatedExprVisitor { + Sema &S; + // List of Decls to generate a warning on. Also remove Decls that become + // initialized. + llvm::SmallPtrSetImpl &Decls; + // List of base classes of the record. Classes are removed after their + // initializers. + llvm::SmallPtrSetImpl &BaseClasses; + // Vector of decls to be removed from the Decl set prior to visiting the + // nodes. These Decls may have been initialized in the prior initializer. + llvm::SmallVector DeclsToRemove; + // If non-null, add a note to the warning pointing back to the constructor. + const CXXConstructorDecl *Constructor; + // Variables to hold state when processing an initializer list. When + // InitList is true, special case initialization of FieldDecls matching + // InitListFieldDecl. + bool InitList; + FieldDecl *InitListFieldDecl; + llvm::SmallVector InitFieldIndex; + +public: + typedef EvaluatedExprVisitor Inherited; + UninitializedFieldVisitor(Sema &S, llvm::SmallPtrSetImpl &Decls, + llvm::SmallPtrSetImpl &BaseClasses) : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} - // Returns true if the use of ME is not an uninitialized use. - bool IsInitListMemberExprInitialized(MemberExpr *ME, - bool CheckReferenceOnly) { - llvm::SmallVector Fields; - bool ReferenceField = false; - while (ME) { - FieldDecl *FD = dyn_cast(ME->getMemberDecl()); - if (!FD) - return false; - Fields.push_back(FD); - if (FD->getType()->isReferenceType()) - ReferenceField = true; - ME = dyn_cast(ME->getBase()->IgnoreParenImpCasts()); - } + // Returns true if the use of ME is not an uninitialized use. + bool IsInitListMemberExprInitialized(MemberExpr *ME, + bool CheckReferenceOnly) { + llvm::SmallVector Fields; + bool ReferenceField = false; + while (ME) { + FieldDecl *FD = dyn_cast(ME->getMemberDecl()); + if (!FD) + return false; + Fields.push_back(FD); + if (FD->getType()->isReferenceType()) + ReferenceField = true; + ME = dyn_cast(ME->getBase()->IgnoreParenImpCasts()); + } - // Binding a reference to an uninitialized field is not an - // uninitialized use. - if (CheckReferenceOnly && !ReferenceField) - return true; + // Binding a reference to an uninitialized field is not an + // uninitialized use. + if (CheckReferenceOnly && !ReferenceField) + return true; - llvm::SmallVector UsedFieldIndex; - // Discard the first field since it is the field decl that is being - // initialized. - for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) - UsedFieldIndex.push_back(FD->getFieldIndex()); - - for (auto UsedIter = UsedFieldIndex.begin(), - UsedEnd = UsedFieldIndex.end(), - OrigIter = InitFieldIndex.begin(), - OrigEnd = InitFieldIndex.end(); - UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { - if (*UsedIter < *OrigIter) - return true; - if (*UsedIter > *OrigIter) - break; - } + llvm::SmallVector UsedFieldIndex; + // Discard the first field since it is the field decl that is being + // initialized. + for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) + UsedFieldIndex.push_back(FD->getFieldIndex()); - return false; + for (auto UsedIter = UsedFieldIndex.begin(), UsedEnd = UsedFieldIndex.end(), + OrigIter = InitFieldIndex.begin(), OrigEnd = InitFieldIndex.end(); + UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { + if (*UsedIter < *OrigIter) + return true; + if (*UsedIter > *OrigIter) + break; } - void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, - bool AddressOf) { - if (isa(ME->getMemberDecl())) - return; + return false; + } - // FieldME is the inner-most MemberExpr that is not an anonymous struct - // or union. - MemberExpr *FieldME = ME; + void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, + bool AddressOf) { + if (isa(ME->getMemberDecl())) + return; - bool AllPODFields = FieldME->getType().isPODType(S.Context); + // FieldME is the inner-most MemberExpr that is not an anonymous struct + // or union. + MemberExpr *FieldME = ME; - Expr *Base = ME; - while (MemberExpr *SubME = - dyn_cast(Base->IgnoreParenImpCasts())) { + bool AllPODFields = FieldME->getType().isPODType(S.Context); - if (isa(SubME->getMemberDecl())) - return; + Expr *Base = ME; + while (MemberExpr *SubME = + dyn_cast(Base->IgnoreParenImpCasts())) { - if (FieldDecl *FD = dyn_cast(SubME->getMemberDecl())) - if (!FD->isAnonymousStructOrUnion()) - FieldME = SubME; + if (isa(SubME->getMemberDecl())) + return; - if (!FieldME->getType().isPODType(S.Context)) - AllPODFields = false; + if (FieldDecl *FD = dyn_cast(SubME->getMemberDecl())) + if (!FD->isAnonymousStructOrUnion()) + FieldME = SubME; - Base = SubME->getBase(); - } + if (!FieldME->getType().isPODType(S.Context)) + AllPODFields = false; - if (!isa(Base->IgnoreParenImpCasts())) { - Visit(Base); - return; - } + Base = SubME->getBase(); + } - if (AddressOf && AllPODFields) - return; + if (!isa(Base->IgnoreParenImpCasts())) { + Visit(Base); + return; + } - ValueDecl* FoundVD = FieldME->getMemberDecl(); + if (AddressOf && AllPODFields) + return; - if (ImplicitCastExpr *BaseCast = dyn_cast(Base)) { - while (isa(BaseCast->getSubExpr())) { - BaseCast = cast(BaseCast->getSubExpr()); - } + ValueDecl *FoundVD = FieldME->getMemberDecl(); - if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { - QualType T = BaseCast->getType(); - if (T->isPointerType() && - BaseClasses.count(T->getPointeeType())) { - S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) - << T->getPointeeType() << FoundVD; - } - } + if (ImplicitCastExpr *BaseCast = dyn_cast(Base)) { + while (isa(BaseCast->getSubExpr())) { + BaseCast = cast(BaseCast->getSubExpr()); } - if (!Decls.count(FoundVD)) - return; - - const bool IsReference = FoundVD->getType()->isReferenceType(); - - if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { - // Special checking for initializer lists. - if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { - return; + if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { + QualType T = BaseCast->getType(); + if (T->isPointerType() && BaseClasses.count(T->getPointeeType())) { + S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) + << T->getPointeeType() << FoundVD; } - } else { - // Prevent double warnings on use of unbounded references. - if (CheckReferenceOnly && !IsReference) - return; } - - unsigned diag = IsReference - ? diag::warn_reference_field_is_uninit - : diag::warn_field_is_uninit; - S.Diag(FieldME->getExprLoc(), diag) << FoundVD; - if (Constructor) - S.Diag(Constructor->getLocation(), - diag::note_uninit_in_this_constructor) - << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); - } - void HandleValue(Expr *E, bool AddressOf) { - E = E->IgnoreParens(); + if (!Decls.count(FoundVD)) + return; - if (MemberExpr *ME = dyn_cast(E)) { - HandleMemberExpr(ME, false /*CheckReferenceOnly*/, - AddressOf /*AddressOf*/); - return; - } + const bool IsReference = FoundVD->getType()->isReferenceType(); - if (ConditionalOperator *CO = dyn_cast(E)) { - Visit(CO->getCond()); - HandleValue(CO->getTrueExpr(), AddressOf); - HandleValue(CO->getFalseExpr(), AddressOf); + if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { + // Special checking for initializer lists. + if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { return; } - - if (BinaryConditionalOperator *BCO = - dyn_cast(E)) { - Visit(BCO->getCond()); - HandleValue(BCO->getFalseExpr(), AddressOf); + } else { + // Prevent double warnings on use of unbounded references. + if (CheckReferenceOnly && !IsReference) return; - } + } - if (OpaqueValueExpr *OVE = dyn_cast(E)) { - HandleValue(OVE->getSourceExpr(), AddressOf); - return; - } + unsigned diag = IsReference ? diag::warn_reference_field_is_uninit + : diag::warn_field_is_uninit; + S.Diag(FieldME->getExprLoc(), diag) << FoundVD; + if (Constructor) + S.Diag(Constructor->getLocation(), diag::note_uninit_in_this_constructor) + << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); + } - if (BinaryOperator *BO = dyn_cast(E)) { - switch (BO->getOpcode()) { - default: - break; - case(BO_PtrMemD): - case(BO_PtrMemI): - HandleValue(BO->getLHS(), AddressOf); - Visit(BO->getRHS()); - return; - case(BO_Comma): - Visit(BO->getLHS()); - HandleValue(BO->getRHS(), AddressOf); - return; - } - } + void HandleValue(Expr *E, bool AddressOf) { + E = E->IgnoreParens(); - Visit(E); + if (MemberExpr *ME = dyn_cast(E)) { + HandleMemberExpr(ME, false /*CheckReferenceOnly*/, + AddressOf /*AddressOf*/); + return; } - void CheckInitListExpr(InitListExpr *ILE) { - InitFieldIndex.push_back(0); - for (auto *Child : ILE->children()) { - if (InitListExpr *SubList = dyn_cast(Child)) { - CheckInitListExpr(SubList); - } else { - Visit(Child); - } - ++InitFieldIndex.back(); - } - InitFieldIndex.pop_back(); + if (ConditionalOperator *CO = dyn_cast(E)) { + Visit(CO->getCond()); + HandleValue(CO->getTrueExpr(), AddressOf); + HandleValue(CO->getFalseExpr(), AddressOf); + return; } - void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, - FieldDecl *Field, const Type *BaseClass) { - // Remove Decls that may have been initialized in the previous - // initializer. - for (ValueDecl* VD : DeclsToRemove) - Decls.erase(VD); - DeclsToRemove.clear(); - - Constructor = FieldConstructor; - InitListExpr *ILE = dyn_cast(E); - - if (ILE && Field) { - InitList = true; - InitListFieldDecl = Field; - InitFieldIndex.clear(); - CheckInitListExpr(ILE); - } else { - InitList = false; - Visit(E); - } - - if (Field) - Decls.erase(Field); - if (BaseClass) - BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); + if (BinaryConditionalOperator *BCO = + dyn_cast(E)) { + Visit(BCO->getCond()); + HandleValue(BCO->getFalseExpr(), AddressOf); + return; } - void VisitMemberExpr(MemberExpr *ME) { - // All uses of unbounded reference fields will warn. - HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); + if (OpaqueValueExpr *OVE = dyn_cast(E)) { + HandleValue(OVE->getSourceExpr(), AddressOf); + return; } - void VisitImplicitCastExpr(ImplicitCastExpr *E) { - if (E->getCastKind() == CK_LValueToRValue) { - HandleValue(E->getSubExpr(), false /*AddressOf*/); + if (BinaryOperator *BO = dyn_cast(E)) { + switch (BO->getOpcode()) { + default: + break; + case (BO_PtrMemD): + case (BO_PtrMemI): + HandleValue(BO->getLHS(), AddressOf); + Visit(BO->getRHS()); + return; + case (BO_Comma): + Visit(BO->getLHS()); + HandleValue(BO->getRHS(), AddressOf); return; } - - Inherited::VisitImplicitCastExpr(E); } - void VisitCXXConstructExpr(CXXConstructExpr *E) { - if (E->getConstructor()->isCopyConstructor()) { - Expr *ArgExpr = E->getArg(0); - if (InitListExpr *ILE = dyn_cast(ArgExpr)) - if (ILE->getNumInits() == 1) - ArgExpr = ILE->getInit(0); - if (ImplicitCastExpr *ICE = dyn_cast(ArgExpr)) - if (ICE->getCastKind() == CK_NoOp) - ArgExpr = ICE->getSubExpr(); - HandleValue(ArgExpr, false /*AddressOf*/); - return; + Visit(E); + } + + void CheckInitListExpr(InitListExpr *ILE) { + InitFieldIndex.push_back(0); + for (auto *Child : ILE->children()) { + if (InitListExpr *SubList = dyn_cast(Child)) { + CheckInitListExpr(SubList); + } else { + Visit(Child); } - Inherited::VisitCXXConstructExpr(E); + ++InitFieldIndex.back(); } + InitFieldIndex.pop_back(); + } - void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { - Expr *Callee = E->getCallee(); - if (isa(Callee)) { - HandleValue(Callee, false /*AddressOf*/); - for (auto *Arg : E->arguments()) - Visit(Arg); - return; - } + void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, + FieldDecl *Field, const Type *BaseClass) { + // Remove Decls that may have been initialized in the previous + // initializer. + for (ValueDecl *VD : DeclsToRemove) + Decls.erase(VD); + DeclsToRemove.clear(); + + Constructor = FieldConstructor; + InitListExpr *ILE = dyn_cast(E); - Inherited::VisitCXXMemberCallExpr(E); + if (ILE && Field) { + InitList = true; + InitListFieldDecl = Field; + InitFieldIndex.clear(); + CheckInitListExpr(ILE); + } else { + InitList = false; + Visit(E); } - void VisitCallExpr(CallExpr *E) { - // Treat std::move as a use. - if (E->isCallToStdMove()) { - HandleValue(E->getArg(0), /*AddressOf=*/false); - return; - } + if (Field) + Decls.erase(Field); + if (BaseClass) + BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); + } + + void VisitMemberExpr(MemberExpr *ME) { + // All uses of unbounded reference fields will warn. + HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); + } - Inherited::VisitCallExpr(E); + void VisitImplicitCastExpr(ImplicitCastExpr *E) { + if (E->getCastKind() == CK_LValueToRValue) { + HandleValue(E->getSubExpr(), false /*AddressOf*/); + return; } - void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { - Expr *Callee = E->getCallee(); + Inherited::VisitImplicitCastExpr(E); + } - if (isa(Callee)) - return Inherited::VisitCXXOperatorCallExpr(E); + void VisitCXXConstructExpr(CXXConstructExpr *E) { + if (E->getConstructor()->isCopyConstructor()) { + Expr *ArgExpr = E->getArg(0); + if (InitListExpr *ILE = dyn_cast(ArgExpr)) + if (ILE->getNumInits() == 1) + ArgExpr = ILE->getInit(0); + if (ImplicitCastExpr *ICE = dyn_cast(ArgExpr)) + if (ICE->getCastKind() == CK_NoOp) + ArgExpr = ICE->getSubExpr(); + HandleValue(ArgExpr, false /*AddressOf*/); + return; + } + Inherited::VisitCXXConstructExpr(E); + } - Visit(Callee); + void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { + Expr *Callee = E->getCallee(); + if (isa(Callee)) { + HandleValue(Callee, false /*AddressOf*/); for (auto *Arg : E->arguments()) - HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); + Visit(Arg); + return; } - void VisitBinaryOperator(BinaryOperator *E) { - // If a field assignment is detected, remove the field from the - // uninitiailized field set. - if (E->getOpcode() == BO_Assign) - if (MemberExpr *ME = dyn_cast(E->getLHS())) - if (FieldDecl *FD = dyn_cast(ME->getMemberDecl())) - if (!FD->getType()->isReferenceType()) - DeclsToRemove.push_back(FD); - - if (E->isCompoundAssignmentOp()) { - HandleValue(E->getLHS(), false /*AddressOf*/); - Visit(E->getRHS()); - return; - } + Inherited::VisitCXXMemberCallExpr(E); + } - Inherited::VisitBinaryOperator(E); + void VisitCallExpr(CallExpr *E) { + // Treat std::move as a use. + if (E->isCallToStdMove()) { + HandleValue(E->getArg(0), /*AddressOf=*/false); + return; } - void VisitUnaryOperator(UnaryOperator *E) { - if (E->isIncrementDecrementOp()) { - HandleValue(E->getSubExpr(), false /*AddressOf*/); - return; - } - if (E->getOpcode() == UO_AddrOf) { - if (MemberExpr *ME = dyn_cast(E->getSubExpr())) { - HandleValue(ME->getBase(), true /*AddressOf*/); - return; - } - } + Inherited::VisitCallExpr(E); + } - Inherited::VisitUnaryOperator(E); - } - }; + void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { + Expr *Callee = E->getCallee(); + + if (isa(Callee)) + return Inherited::VisitCXXOperatorCallExpr(E); + + Visit(Callee); + for (auto *Arg : E->arguments()) + HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); + } + + void VisitBinaryOperator(BinaryOperator *E) { + // If a field assignment is detected, remove the field from the + // uninitiailized field set. + if (E->getOpcode() == BO_Assign) + if (MemberExpr *ME = dyn_cast(E->getLHS())) + if (FieldDecl *FD = dyn_cast(ME->getMemberDecl())) + if (!FD->getType()->isReferenceType()) + DeclsToRemove.push_back(FD); - // Diagnose value-uses of fields to initialize themselves, e.g. - // foo(foo) - // where foo is not also a parameter to the constructor. - // Also diagnose across field uninitialized use such as - // x(y), y(x) - // TODO: implement -Wuninitialized and fold this into that framework. - static void DiagnoseUninitializedFields( - Sema &SemaRef, const CXXConstructorDecl *Constructor) { - - if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, - Constructor->getLocation())) { + if (E->isCompoundAssignmentOp()) { + HandleValue(E->getLHS(), false /*AddressOf*/); + Visit(E->getRHS()); return; } - if (Constructor->isInvalidDecl()) + Inherited::VisitBinaryOperator(E); + } + + void VisitUnaryOperator(UnaryOperator *E) { + if (E->isIncrementDecrementOp()) { + HandleValue(E->getSubExpr(), false /*AddressOf*/); return; + } + if (E->getOpcode() == UO_AddrOf) { + if (MemberExpr *ME = dyn_cast(E->getSubExpr())) { + HandleValue(ME->getBase(), true /*AddressOf*/); + return; + } + } - const CXXRecordDecl *RD = Constructor->getParent(); + Inherited::VisitUnaryOperator(E); + } +}; - if (RD->isDependentContext()) - return; +// Diagnose value-uses of fields to initialize themselves, e.g. +// foo(foo) +// where foo is not also a parameter to the constructor. +// Also diagnose across field uninitialized use such as +// x(y), y(x) +// TODO: implement -Wuninitialized and fold this into that framework. +static void DiagnoseUninitializedFields(Sema &SemaRef, + const CXXConstructorDecl *Constructor) { + + if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, + Constructor->getLocation())) { + return; + } - // Holds fields that are uninitialized. - llvm::SmallPtrSet UninitializedFields; + if (Constructor->isInvalidDecl()) + return; - // At the beginning, all fields are uninitialized. - for (auto *I : RD->decls()) { - if (auto *FD = dyn_cast(I)) { - UninitializedFields.insert(FD); - } else if (auto *IFD = dyn_cast(I)) { - UninitializedFields.insert(IFD->getAnonField()); - } + const CXXRecordDecl *RD = Constructor->getParent(); + + if (RD->isDependentContext()) + return; + + // Holds fields that are uninitialized. + llvm::SmallPtrSet UninitializedFields; + + // At the beginning, all fields are uninitialized. + for (auto *I : RD->decls()) { + if (auto *FD = dyn_cast(I)) { + UninitializedFields.insert(FD); + } else if (auto *IFD = dyn_cast(I)) { + UninitializedFields.insert(IFD->getAnonField()); } + } - llvm::SmallPtrSet UninitializedBaseClasses; - for (auto I : RD->bases()) - UninitializedBaseClasses.insert(I.getType().getCanonicalType()); + llvm::SmallPtrSet UninitializedBaseClasses; + for (auto I : RD->bases()) + UninitializedBaseClasses.insert(I.getType().getCanonicalType()); - if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) - return; + if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) + return; - UninitializedFieldVisitor UninitializedChecker(SemaRef, - UninitializedFields, - UninitializedBaseClasses); + UninitializedFieldVisitor UninitializedChecker(SemaRef, UninitializedFields, + UninitializedBaseClasses); - for (const auto *FieldInit : Constructor->inits()) { - if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) - break; + for (const auto *FieldInit : Constructor->inits()) { + if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) + break; - Expr *InitExpr = FieldInit->getInit(); + Expr *InitExpr = FieldInit->getInit(); + if (!InitExpr) + continue; + + if (CXXDefaultInitExpr *Default = dyn_cast(InitExpr)) { + InitExpr = Default->getExpr(); if (!InitExpr) continue; - - if (CXXDefaultInitExpr *Default = - dyn_cast(InitExpr)) { - InitExpr = Default->getExpr(); - if (!InitExpr) - continue; - // In class initializers will point to the constructor. - UninitializedChecker.CheckInitializer(InitExpr, Constructor, - FieldInit->getAnyMember(), - FieldInit->getBaseClass()); - } else { - UninitializedChecker.CheckInitializer(InitExpr, nullptr, - FieldInit->getAnyMember(), - FieldInit->getBaseClass()); - } + // In class initializers will point to the constructor. + UninitializedChecker.CheckInitializer(InitExpr, Constructor, + FieldInit->getAnyMember(), + FieldInit->getBaseClass()); + } else { + UninitializedChecker.CheckInitializer(InitExpr, nullptr, + FieldInit->getAnyMember(), + FieldInit->getBaseClass()); } } +} } // namespace /// Enter a new C++ default initializer scope. After calling this, the @@ -4031,8 +4006,8 @@ auto &FTI = D.getFunctionTypeInfo(); if (!FTI.Params) return; - for (auto &Param : ArrayRef(FTI.Params, - FTI.NumParams)) { + for (auto &Param : + ArrayRef(FTI.Params, FTI.NumParams)) { auto *ParamDecl = cast(Param.Param); if (ParamDecl->getDeclName()) PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); @@ -4121,8 +4096,7 @@ /// Find the direct and/or virtual base specifiers that /// correspond to the given base type, for use in base initialization /// within a constructor. -static bool FindBaseInitializer(Sema &SemaRef, - CXXRecordDecl *ClassDecl, +static bool FindBaseInitializer(Sema &SemaRef, CXXRecordDecl *ClassDecl, QualType BaseType, const CXXBaseSpecifier *&DirectBaseSpec, const CXXBaseSpecifier *&VirtualBaseSpec) { @@ -4163,34 +4137,20 @@ } /// Handle a C++ member initializer using braced-init-list syntax. -MemInitResult -Sema::ActOnMemInitializer(Decl *ConstructorD, - Scope *S, - CXXScopeSpec &SS, - IdentifierInfo *MemberOrBase, - ParsedType TemplateTypeTy, - const DeclSpec &DS, - SourceLocation IdLoc, - Expr *InitList, - SourceLocation EllipsisLoc) { +MemInitResult Sema::ActOnMemInitializer( + Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, + IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, + SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc) { return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, - DS, IdLoc, InitList, - EllipsisLoc); + DS, IdLoc, InitList, EllipsisLoc); } /// Handle a C++ member initializer using parentheses syntax. -MemInitResult -Sema::ActOnMemInitializer(Decl *ConstructorD, - Scope *S, - CXXScopeSpec &SS, - IdentifierInfo *MemberOrBase, - ParsedType TemplateTypeTy, - const DeclSpec &DS, - SourceLocation IdLoc, - SourceLocation LParenLoc, - ArrayRef Args, - SourceLocation RParenLoc, - SourceLocation EllipsisLoc) { +MemInitResult Sema::ActOnMemInitializer( + Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, + IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, + SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef Args, + SourceLocation RParenLoc, SourceLocation EllipsisLoc) { Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, DS, IdLoc, List, EllipsisLoc); @@ -4222,7 +4182,7 @@ CXXRecordDecl *ClassDecl; }; -} +} // namespace ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, @@ -4237,16 +4197,10 @@ } /// Handle a C++ member initializer. -MemInitResult -Sema::BuildMemInitializer(Decl *ConstructorD, - Scope *S, - CXXScopeSpec &SS, - IdentifierInfo *MemberOrBase, - ParsedType TemplateTypeTy, - const DeclSpec &DS, - SourceLocation IdLoc, - Expr *Init, - SourceLocation EllipsisLoc) { +MemInitResult Sema::BuildMemInitializer( + Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, + IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, + SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc) { ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/true); if (!Res.isUsable()) @@ -4258,8 +4212,7 @@ AdjustDeclIfTemplate(ConstructorD); - CXXConstructorDecl *Constructor - = dyn_cast(ConstructorD); + CXXConstructorDecl *Constructor = dyn_cast(ConstructorD); if (!Constructor) { // The user wrote a constructor initializer on a function that is // not a C++ constructor. Ignore the error for now, because we may @@ -4310,7 +4263,8 @@ TypeDecl *TyD = R.getAsSingle(); if (!TyD) { - if (R.isAmbiguous()) return true; + if (R.isAmbiguous()) + return true; // We don't want access-control diagnostics here. R.suppressDiagnostics(); @@ -4375,24 +4329,24 @@ // member. diagnoseTypo(Corr, PDiag(diag::err_mem_init_not_member_or_class_suggest) - << MemberOrBase << true); + << MemberOrBase << true); return BuildMemberInitializer(Member, Init, IdLoc); } else if (TypeDecl *Type = Corr.getCorrectionDeclAs()) { const CXXBaseSpecifier *DirectBaseSpec; const CXXBaseSpecifier *VirtualBaseSpec; if (FindBaseInitializer(*this, ClassDecl, - Context.getTypeDeclType(Type), - DirectBaseSpec, VirtualBaseSpec)) { + Context.getTypeDeclType(Type), DirectBaseSpec, + VirtualBaseSpec)) { // We have found a direct or virtual base class with a // similar name to what was typed; complain and initialize // that base class. diagnoseTypo(Corr, PDiag(diag::err_mem_init_not_member_or_class_suggest) - << MemberOrBase << false, + << MemberOrBase << false, PDiag() /*Suppress note, we provide our own.*/); - const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec - : VirtualBaseSpec; + const CXXBaseSpecifier *BaseSpec = + DirectBaseSpec ? DirectBaseSpec : VirtualBaseSpec; Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) << BaseSpec->getType() << BaseSpec->getSourceRange(); @@ -4403,7 +4357,8 @@ if (!TyD && BaseType.isNull()) { Diag(IdLoc, diag::err_mem_init_not_member_or_class) - << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); + << MemberOrBase + << SourceRange(IdLoc, Init->getSourceRange().getEnd()); return true; } } @@ -4425,9 +4380,8 @@ return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); } -MemInitResult -Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, - SourceLocation IdLoc) { +MemInitResult Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, + SourceLocation IdLoc) { FieldDecl *DirectMember = dyn_cast(Member); IndirectFieldDecl *IndirectMember = dyn_cast(Member); assert((DirectMember || IndirectMember) && @@ -4464,9 +4418,9 @@ // Initialize the member. InitializedEntity MemberEntity = - DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) - : InitializedEntity::InitializeMember(IndirectMember, - nullptr); + DirectMember + ? InitializedEntity::InitializeMember(DirectMember, nullptr) + : InitializedEntity::InitializeMember(IndirectMember, nullptr); InitializationKind Kind = InitList ? InitializationKind::CreateDirectList( IdLoc, Init->getBeginLoc(), Init->getEndLoc()) @@ -4474,8 +4428,8 @@ InitRange.getEnd()); InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); - ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, - nullptr); + ExprResult MemberInit = + InitSeq.Perform(*this, MemberEntity, Kind, Args, nullptr); if (!MemberInit.isInvalid()) { // C++11 [class.base.init]p7: // The initialization of each base and member constitutes a @@ -4498,19 +4452,19 @@ } if (DirectMember) { - return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, - InitRange.getBegin(), Init, - InitRange.getEnd()); + return new (Context) + CXXCtorInitializer(Context, DirectMember, IdLoc, InitRange.getBegin(), + Init, InitRange.getEnd()); } else { - return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, - InitRange.getBegin(), Init, - InitRange.getEnd()); + return new (Context) + CXXCtorInitializer(Context, IndirectMember, IdLoc, InitRange.getBegin(), + Init, InitRange.getEnd()); } } -MemInitResult -Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, - CXXRecordDecl *ClassDecl) { +MemInitResult Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, + Expr *Init, + CXXRecordDecl *ClassDecl) { SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin(); if (!LangOpts.CPlusPlus11) return Diag(NameLoc, diag::err_delegating_ctor) @@ -4527,15 +4481,15 @@ SourceRange InitRange = Init->getSourceRange(); // Initialize the object. InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( - QualType(ClassDecl->getTypeForDecl(), 0)); + QualType(ClassDecl->getTypeForDecl(), 0)); InitializationKind Kind = InitList ? InitializationKind::CreateDirectList( NameLoc, Init->getBeginLoc(), Init->getEndLoc()) : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), InitRange.getEnd()); InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); - ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, - Args, nullptr); + ExprResult DelegationInit = + InitSeq.Perform(*this, DelegationEntity, Kind, Args, nullptr); if (!DelegationInit.isInvalid()) { assert((DelegationInit.get()->containsErrors() || cast(DelegationInit.get())->getConstructor()) && @@ -4566,15 +4520,15 @@ DelegationInit = Init; } - return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), - DelegationInit.getAs(), - InitRange.getEnd()); + return new (Context) + CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), + DelegationInit.getAs(), InitRange.getEnd()); } -MemInitResult -Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, - Expr *Init, CXXRecordDecl *ClassDecl, - SourceLocation EllipsisLoc) { +MemInitResult Sema::BuildBaseInitializer(QualType BaseType, + TypeSourceInfo *BaseTInfo, Expr *Init, + CXXRecordDecl *ClassDecl, + SourceLocation EllipsisLoc) { SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc(); if (!BaseType->isDependentType() && !BaseType->isRecordType()) @@ -4597,9 +4551,9 @@ SourceRange InitRange = Init->getSourceRange(); if (EllipsisLoc.isValid()) { // This is a pack expansion. - if (!BaseType->containsUnexpandedParameterPack()) { + if (!BaseType->containsUnexpandedParameterPack()) { Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) - << SourceRange(BaseLoc, InitRange.getEnd()); + << SourceRange(BaseLoc, InitRange.getEnd()); EllipsisLoc = SourceLocation(); } @@ -4616,7 +4570,7 @@ const CXXBaseSpecifier *DirectBaseSpec = nullptr; const CXXBaseSpecifier *VirtualBaseSpec = nullptr; if (!Dependent) { - if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), + if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(), 0), BaseType)) return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); @@ -4645,10 +4599,10 @@ if (Dependent) { DiscardCleanupsInEvaluationContext(); - return new (Context) CXXCtorInitializer(Context, BaseTInfo, - /*IsVirtual=*/false, - InitRange.getBegin(), Init, - InitRange.getEnd(), EllipsisLoc); + return new (Context) + CXXCtorInitializer(Context, BaseTInfo, + /*IsVirtual=*/false, InitRange.getBegin(), Init, + InitRange.getEnd(), EllipsisLoc); } // C++ [base.class.init]p2: @@ -4657,7 +4611,7 @@ // class, the mem-initializer is ill-formed. if (DirectBaseSpec && VirtualBaseSpec) return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) - << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); + << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; if (!BaseSpec) @@ -4672,7 +4626,7 @@ } InitializedEntity BaseEntity = - InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); + InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); InitializationKind Kind = InitList ? InitializationKind::CreateDirectList(BaseLoc) : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), @@ -4704,11 +4658,9 @@ BaseInit = Init; } - return new (Context) CXXCtorInitializer(Context, BaseTInfo, - BaseSpec->isVirtual(), - InitRange.getBegin(), - BaseInit.getAs(), - InitRange.getEnd(), EllipsisLoc); + return new (Context) CXXCtorInitializer( + Context, BaseTInfo, BaseSpec->isVirtual(), InitRange.getBegin(), + BaseInit.getAs(), InitRange.getEnd(), EllipsisLoc); } // Create a static_cast\(expr). @@ -4717,40 +4669,33 @@ SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName()); SourceLocation ExprLoc = E->getBeginLoc(); - TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( - TargetType, ExprLoc); + TypeSourceInfo *TargetLoc = + SemaRef.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc); - return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, - SourceRange(ExprLoc, ExprLoc), - E->getSourceRange()).get(); + return SemaRef + .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, + SourceRange(ExprLoc, ExprLoc), E->getSourceRange()) + .get(); } /// ImplicitInitializerKind - How an implicit base or member initializer should /// initialize its base or member. -enum ImplicitInitializerKind { - IIK_Default, - IIK_Copy, - IIK_Move, - IIK_Inherit -}; +enum ImplicitInitializerKind { IIK_Default, IIK_Copy, IIK_Move, IIK_Inherit }; -static bool -BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, - ImplicitInitializerKind ImplicitInitKind, - CXXBaseSpecifier *BaseSpec, - bool IsInheritedVirtualBase, - CXXCtorInitializer *&CXXBaseInit) { - InitializedEntity InitEntity - = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, - IsInheritedVirtualBase); +static bool BuildImplicitBaseInitializer( + Sema &SemaRef, CXXConstructorDecl *Constructor, + ImplicitInitializerKind ImplicitInitKind, CXXBaseSpecifier *BaseSpec, + bool IsInheritedVirtualBase, CXXCtorInitializer *&CXXBaseInit) { + InitializedEntity InitEntity = InitializedEntity::InitializeBase( + SemaRef.Context, BaseSpec, IsInheritedVirtualBase); ExprResult BaseInit; switch (ImplicitInitKind) { case IIK_Inherit: case IIK_Default: { - InitializationKind InitKind - = InitializationKind::CreateDefault(Constructor->getLocation()); + InitializationKind InitKind = + InitializationKind::CreateDefault(Constructor->getLocation()); InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt); BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt); break; @@ -4762,18 +4707,15 @@ ParmVarDecl *Param = Constructor->getParamDecl(0); QualType ParamType = Param->getType().getNonReferenceType(); - Expr *CopyCtorArg = - DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), - SourceLocation(), Param, false, - Constructor->getLocation(), ParamType, - VK_LValue, nullptr); + Expr *CopyCtorArg = DeclRefExpr::Create( + SemaRef.Context, NestedNameSpecifierLoc(), SourceLocation(), Param, + false, Constructor->getLocation(), ParamType, VK_LValue, nullptr); SemaRef.MarkDeclRefReferenced(cast(CopyCtorArg)); // Cast to the base class to avoid ambiguities. - QualType ArgTy = - SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), - ParamType.getQualifiers()); + QualType ArgTy = SemaRef.Context.getQualifiedType( + BaseSpec->getType().getUnqualifiedType(), ParamType.getQualifiers()); if (Moving) { CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); @@ -4781,14 +4723,14 @@ CXXCastPath BasePath; BasePath.push_back(BaseSpec); - CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, - CK_UncheckedDerivedToBase, - Moving ? VK_XValue : VK_LValue, - &BasePath).get(); - - InitializationKind InitKind - = InitializationKind::CreateDirect(Constructor->getLocation(), - SourceLocation(), SourceLocation()); + CopyCtorArg = + SemaRef + .ImpCastExprToType(CopyCtorArg, ArgTy, CK_UncheckedDerivedToBase, + Moving ? VK_XValue : VK_LValue, &BasePath) + .get(); + + InitializationKind InitKind = InitializationKind::CreateDirect( + Constructor->getLocation(), SourceLocation(), SourceLocation()); InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); break; @@ -4799,15 +4741,12 @@ if (BaseInit.isInvalid()) return true; - CXXBaseInit = - new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, - SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), - SourceLocation()), - BaseSpec->isVirtual(), - SourceLocation(), - BaseInit.getAs(), - SourceLocation(), - SourceLocation()); + CXXBaseInit = new (SemaRef.Context) CXXCtorInitializer( + SemaRef.Context, + SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), + SourceLocation()), + BaseSpec->isVirtual(), SourceLocation(), BaseInit.getAs(), + SourceLocation(), SourceLocation()); return false; } @@ -4836,10 +4775,9 @@ if (Field->isZeroLengthBitField(SemaRef.Context)) return false; - Expr *MemberExprBase = - DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), - SourceLocation(), Param, false, - Loc, ParamType, VK_LValue, nullptr); + Expr *MemberExprBase = DeclRefExpr::Create( + SemaRef.Context, NestedNameSpecifierLoc(), SourceLocation(), Param, + false, Loc, ParamType, VK_LValue, nullptr); SemaRef.MarkDeclRefReferenced(cast(MemberExprBase)); @@ -4852,18 +4790,16 @@ LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, Sema::LookupMemberName); MemberLookup.addDecl(Indirect ? cast(Indirect) - : cast(Field), AS_public); + : cast(Field), + AS_public); MemberLookup.resolveKind(); - ExprResult CtorArg - = SemaRef.BuildMemberReferenceExpr(MemberExprBase, - ParamType, Loc, - /*IsArrow=*/false, - SS, - /*TemplateKWLoc=*/SourceLocation(), - /*FirstQualifierInScope=*/nullptr, - MemberLookup, - /*TemplateArgs=*/nullptr, - /*S*/nullptr); + ExprResult CtorArg = SemaRef.BuildMemberReferenceExpr( + MemberExprBase, ParamType, Loc, + /*IsArrow=*/false, SS, + /*TemplateKWLoc=*/SourceLocation(), + /*FirstQualifierInScope=*/nullptr, MemberLookup, + /*TemplateArgs=*/nullptr, + /*S*/ nullptr); if (CtorArg.isInvalid()) return true; @@ -4881,8 +4817,8 @@ /*Implicit*/ true); // Direct-initialize to use the copy constructor. - InitializationKind InitKind = - InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); + InitializationKind InitKind = InitializationKind::CreateDirect( + Loc, SourceLocation(), SourceLocation()); Expr *CtorArgE = CtorArg.getAs(); InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); @@ -4905,7 +4841,7 @@ "Unhandled implicit init kind!"); QualType FieldBaseElementType = - SemaRef.Context.getBaseElementType(Field->getType()); + SemaRef.Context.getBaseElementType(Field->getType()); if (FieldBaseElementType->isRecordType()) { InitializedEntity InitEntity = @@ -4913,8 +4849,7 @@ /*Implicit*/ true) : InitializedEntity::InitializeMember(Field, nullptr, /*Implicit*/ true); - InitializationKind InitKind = - InitializationKind::CreateDefault(Loc); + InitializationKind InitKind = InitializationKind::CreateDefault(Loc); InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt); ExprResult MemberInit = @@ -4925,16 +4860,11 @@ return true; if (Indirect) - CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, - Indirect, Loc, - Loc, - MemberInit.get(), - Loc); + CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( + SemaRef.Context, Indirect, Loc, Loc, MemberInit.get(), Loc); else - CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, - Field, Loc, Loc, - MemberInit.get(), - Loc); + CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( + SemaRef.Context, Field, Loc, Loc, MemberInit.get(), Loc); return false; } @@ -4942,9 +4872,9 @@ if (FieldBaseElementType->isReferenceType()) { SemaRef.Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor) - << (int)Constructor->isImplicit() - << SemaRef.Context.getTagDeclType(Constructor->getParent()) - << 0 << Field->getDeclName(); + << (int)Constructor->isImplicit() + << SemaRef.Context.getTagDeclType(Constructor->getParent()) << 0 + << Field->getDeclName(); SemaRef.Diag(Field->getLocation(), diag::note_declared_at); return true; } @@ -4952,9 +4882,9 @@ if (FieldBaseElementType.isConstQualified()) { SemaRef.Diag(Constructor->getLocation(), diag::err_uninitialized_member_in_ctor) - << (int)Constructor->isImplicit() - << SemaRef.Context.getTagDeclType(Constructor->getParent()) - << 1 << Field->getDeclName(); + << (int)Constructor->isImplicit() + << SemaRef.Context.getTagDeclType(Constructor->getParent()) << 1 + << Field->getDeclName(); SemaRef.Diag(Field->getLocation(), diag::note_declared_at); return true; } @@ -4963,11 +4893,9 @@ if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { // ARC and Weak: // Default-initialize Objective-C pointers to NULL. - CXXMemberInit - = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, - Loc, Loc, - new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), - Loc); + CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( + SemaRef.Context, Field, Loc, Loc, + new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), Loc); return false; } @@ -4982,12 +4910,12 @@ CXXConstructorDecl *Ctor; bool AnyErrorsInInits; ImplicitInitializerKind IIK; - llvm::DenseMap AllBaseFields; - SmallVector AllToInit; - llvm::DenseMap ActiveUnionMember; + llvm::DenseMap AllBaseFields; + SmallVector AllToInit; + llvm::DenseMap ActiveUnionMember; BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) - : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { + : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); if (Ctor->getInheritedConstructor()) IIK = IIK_Inherit; @@ -5064,7 +4992,7 @@ return false; } }; -} +} // namespace /// Determine whether the given type is an incomplete or zero-lenfgth /// array type. @@ -5150,14 +5078,12 @@ return Info.addFieldInitializer(Init); } -bool -Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, - CXXCtorInitializer *Initializer) { +bool Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, + CXXCtorInitializer *Initializer) { assert(Initializer->isDelegatingInitializer()); Constructor->setNumCtorInitializers(1); - CXXCtorInitializer **initializer = - new (Context) CXXCtorInitializer*[1]; - memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); + CXXCtorInitializer **initializer = new (Context) CXXCtorInitializer *[1]; + memcpy(initializer, &Initializer, sizeof(CXXCtorInitializer *)); Constructor->setCtorInitializers(initializer); if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { @@ -5180,9 +5106,9 @@ if (!Initializers.empty()) { Constructor->setNumCtorInitializers(Initializers.size()); CXXCtorInitializer **baseOrMemberInitializers = - new (Context) CXXCtorInitializer*[Initializers.size()]; + new (Context) CXXCtorInitializer *[Initializers.size()]; memcpy(baseOrMemberInitializers, Initializers.data(), - Initializers.size() * sizeof(CXXCtorInitializer*)); + Initializers.size() * sizeof(CXXCtorInitializer *)); Constructor->setCtorInitializers(baseOrMemberInitializers); } @@ -5235,8 +5161,8 @@ // Push virtual bases before others. for (auto &VBase : ClassDecl->vbases()) { - if (CXXCtorInitializer *Value - = Info.AllBaseFields.lookup(VBase.getType()->getAs())) { + if (CXXCtorInitializer *Value = + Info.AllBaseFields.lookup(VBase.getType()->getAs())) { // [class.base.init]p7, per DR257: // A mem-initializer where the mem-initializer-id names a virtual base // class is ignored during execution of a constructor of any class that @@ -5245,7 +5171,7 @@ // FIXME: Provide a fixit to remove the base specifier. This requires // tracking the location of the associated comma for a base specifier. Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) - << VBase.getType() << ClassDecl; + << VBase.getType() << ClassDecl; DiagnoseAbstractType(ClassDecl); } @@ -5257,9 +5183,8 @@ // class, then [...] the entity is default-initialized. bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); CXXCtorInitializer *CXXBaseInit; - if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, - &VBase, IsInheritedVirtualBase, - CXXBaseInit)) { + if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, &VBase, + IsInheritedVirtualBase, CXXBaseInit)) { HadError = true; continue; } @@ -5274,13 +5199,13 @@ if (Base.isVirtual()) continue; - if (CXXCtorInitializer *Value - = Info.AllBaseFields.lookup(Base.getType()->getAs())) { + if (CXXCtorInitializer *Value = + Info.AllBaseFields.lookup(Base.getType()->getAs())) { Info.AllToInit.push_back(Value); } else if (!AnyErrors) { CXXCtorInitializer *CXXBaseInit; - if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, - &Base, /*IsInheritedVirtualBase=*/false, + if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, &Base, + /*IsInheritedVirtualBase=*/false, CXXBaseInit)) { HadError = true; continue; @@ -5334,9 +5259,9 @@ if (NumInitializers > 0) { Constructor->setNumCtorInitializers(NumInitializers); CXXCtorInitializer **baseOrMemberInitializers = - new (Context) CXXCtorInitializer*[NumInitializers]; + new (Context) CXXCtorInitializer *[NumInitializers]; memcpy(baseOrMemberInitializers, Info.AllToInit.data(), - NumInitializers * sizeof(CXXCtorInitializer*)); + NumInitializers * sizeof(CXXCtorInitializer *)); Constructor->setCtorInitializers(baseOrMemberInitializers); // Constructors implicitly reference the base and member @@ -5348,7 +5273,8 @@ return HadError; } -static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl &IdealInits) { +static void PopulateKeysForFields(FieldDecl *Field, + SmallVectorImpl &IdealInits) { if (const RecordType *RT = Field->getType()->getAs()) { const RecordDecl *RD = RT->getDecl(); if (RD->isAnonymousStructOrUnion()) { @@ -5386,9 +5312,10 @@ Diag << 1 << Current->getTypeSourceInfo()->getType(); } -static void DiagnoseBaseOrMemInitializerOrder( - Sema &SemaRef, const CXXConstructorDecl *Constructor, - ArrayRef Inits) { +static void +DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef, + const CXXConstructorDecl *Constructor, + ArrayRef Inits) { if (Constructor->getDeclContext()->isDependentContext()) return; @@ -5409,7 +5336,7 @@ // Build the list of bases and members in the order that they'll // actually be initialized. The explicit initializers should be in // this same order but may be missing things. - SmallVector IdealInitKeys; + SmallVector IdealInitKeys; const CXXRecordDecl *ClassDecl = Constructor->getParent(); @@ -5516,8 +5443,7 @@ } namespace { -bool CheckRedundantInit(Sema &S, - CXXCtorInitializer *Init, +bool CheckRedundantInit(Sema &S, CXXCtorInitializer *Init, CXXCtorInitializer *&PrevInit) { if (!PrevInit) { PrevInit = Init; @@ -5525,29 +5451,24 @@ } if (FieldDecl *Field = Init->getAnyMember()) - S.Diag(Init->getSourceLocation(), - diag::err_multiple_mem_initialization) - << Field->getDeclName() - << Init->getSourceRange(); + S.Diag(Init->getSourceLocation(), diag::err_multiple_mem_initialization) + << Field->getDeclName() << Init->getSourceRange(); else { const Type *BaseClass = Init->getBaseClass(); assert(BaseClass && "neither field nor base"); - S.Diag(Init->getSourceLocation(), - diag::err_multiple_base_initialization) - << QualType(BaseClass, 0) - << Init->getSourceRange(); + S.Diag(Init->getSourceLocation(), diag::err_multiple_base_initialization) + << QualType(BaseClass, 0) << Init->getSourceRange(); } S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) - << 0 << PrevInit->getSourceRange(); + << 0 << PrevInit->getSourceRange(); return true; } typedef std::pair UnionEntry; -typedef llvm::DenseMap RedundantUnionMap; +typedef llvm::DenseMap RedundantUnionMap; -bool CheckRedundantUnionInit(Sema &S, - CXXCtorInitializer *Init, +bool CheckRedundantUnionInit(Sema &S, CXXCtorInitializer *Init, RedundantUnionMap &Unions) { FieldDecl *Field = Init->getAnyMember(); RecordDecl *Parent = Field->getParent(); @@ -5559,10 +5480,9 @@ if (En.first && En.first != Child) { S.Diag(Init->getSourceLocation(), diag::err_multiple_mem_union_initialization) - << Field->getDeclName() - << Init->getSourceRange(); + << Field->getDeclName() << Init->getSourceRange(); S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) - << 0 << En.second->getSourceRange(); + << 0 << En.second->getSourceRange(); return true; } if (!En.first) { @@ -5582,17 +5502,16 @@ } // namespace /// ActOnMemInitializers - Handle the member initializers for a constructor. -void Sema::ActOnMemInitializers(Decl *ConstructorDecl, - SourceLocation ColonLoc, - ArrayRef MemInits, +void Sema::ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, + ArrayRef MemInits, bool AnyErrors) { if (!ConstructorDecl) return; AdjustDeclIfTemplate(ConstructorDecl); - CXXConstructorDecl *Constructor - = dyn_cast(ConstructorDecl); + CXXConstructorDecl *Constructor = + dyn_cast(ConstructorDecl); if (!Constructor) { Diag(ColonLoc, diag::err_only_constructors_take_base_inits); @@ -5627,9 +5546,8 @@ assert(Init->isDelegatingInitializer()); // This must be the only initializer if (MemInits.size() != 1) { - Diag(Init->getSourceLocation(), - diag::err_delegating_initializer_alone) - << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); + Diag(Init->getSourceLocation(), diag::err_delegating_initializer_alone) + << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); // We will treat this as being the only initializer. } SetDelegatingInitializer(Constructor, MemInits[i]); @@ -5648,9 +5566,8 @@ DiagnoseUninitializedFields(*this, Constructor); } -void -Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, - CXXRecordDecl *ClassDecl) { +void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, + CXXRecordDecl *ClassDecl) { // Ignore dependent contexts. Also ignore unions, since their members never // have destructors implicitly called. if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) @@ -5672,7 +5589,7 @@ QualType FieldType = Context.getBaseElementType(Field->getType()); - const RecordType* RT = FieldType->getAs(); + const RecordType *RT = FieldType->getAs(); if (!RT) continue; @@ -5691,8 +5608,7 @@ continue; CheckDestructorAccess(Field->getLocation(), Dtor, PDiag(diag::err_access_dtor_field) - << Field->getDeclName() - << FieldType); + << Field->getDeclName() << FieldType); MarkFunctionReferenced(Location, Dtor); DiagnoseUseOfDecl(Dtor, Location); @@ -5780,12 +5696,11 @@ ClassDecl->getLocation(), Dtor, PDiag(diag::err_access_dtor_vbase) << Context.getTypeDeclType(ClassDecl) << VBase.getType(), - Context.getTypeDeclType(ClassDecl)) == - AR_accessible) { - CheckDerivedToBaseConversion( - Context.getTypeDeclType(ClassDecl), VBase.getType(), - diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), - SourceRange(), DeclarationName(), nullptr); + Context.getTypeDeclType(ClassDecl)) == AR_accessible) { + CheckDerivedToBaseConversion(Context.getTypeDeclType(ClassDecl), + VBase.getType(), diag::err_access_dtor_vbase, + 0, ClassDecl->getLocation(), SourceRange(), + DeclarationName(), nullptr); } MarkFunctionReferenced(Location, Dtor); @@ -5797,8 +5712,8 @@ if (!CDtorDecl) return; - if (CXXConstructorDecl *Constructor - = dyn_cast(CDtorDecl)) { + if (CXXConstructorDecl *Constructor = + dyn_cast(CDtorDecl)) { SetCtorInitializers(Constructor, /*AnyErrors=*/false); DiagnoseUninitializedFields(*this, Constructor); } @@ -5856,11 +5771,10 @@ llvm::SmallPtrSet SeenPureMethods; for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), - MEnd = FinalOverriders.end(); - M != MEnd; - ++M) { + MEnd = FinalOverriders.end(); + M != MEnd; ++M) { for (OverridingMethods::iterator SO = M->second.begin(), - SOEnd = M->second.end(); + SOEnd = M->second.end(); SO != SOEnd; ++SO) { // C++ [class.abstract]p4: // A class is abstract if it contains or inherits at least one @@ -5879,7 +5793,7 @@ Diag(SO->second.front().Method->getLocation(), diag::note_pure_virtual_function) - << SO->second.front().Method->getDeclName() << RD->getDeclName(); + << SO->second.front().Method->getDeclName() << RD->getDeclName(); } } @@ -5896,13 +5810,13 @@ bool Invalid; AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) - : S(S), Record(Record), - AbstractType(S.Context.getCanonicalType( - S.Context.getTypeDeclType(Record))), - Invalid(false) {} + : S(S), Record(Record), AbstractType(S.Context.getCanonicalType( + S.Context.getTypeDeclType(Record))), + Invalid(false) {} void DiagnoseAbstractType() { - if (Invalid) return; + if (Invalid) + return; S.DiagnoseAbstractType(Record); Invalid = true; } @@ -5915,13 +5829,15 @@ const NamedDecl *Ctx; CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) - : Info(Info), Ctx(Ctx) {} + : Info(Info), Ctx(Ctx) {} void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { switch (TL.getTypeLocClass()) { #define ABSTRACT_TYPELOC(CLASS, PARENT) -#define TYPELOC(CLASS, PARENT) \ - case TypeLoc::CLASS: Check(TL.castAs(), Sel); break; +#define TYPELOC(CLASS, PARENT) \ + case TypeLoc::CLASS: \ + Check(TL.castAs(), Sel); \ + break; #include "clang/AST/TypeLocNodes.def" } } @@ -5933,7 +5849,8 @@ continue; TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); - if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); + if (TSI) + Visit(TSI->getTypeLoc(), Sema::AbstractParamType); } } @@ -5953,19 +5870,17 @@ } // Visit pointee types from a permissive context. -#define CheckPolymorphic(Type) \ - void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ - Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ - } - CheckPolymorphic(PointerTypeLoc) - CheckPolymorphic(ReferenceTypeLoc) - CheckPolymorphic(MemberPointerTypeLoc) - CheckPolymorphic(BlockPointerTypeLoc) - CheckPolymorphic(AtomicTypeLoc) - - /// Handle all the types we haven't given a more specific - /// implementation for above. - void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { +#define CheckPolymorphic(Type) \ + void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ + Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ + } + CheckPolymorphic(PointerTypeLoc) CheckPolymorphic(ReferenceTypeLoc) + CheckPolymorphic(MemberPointerTypeLoc) + CheckPolymorphic(BlockPointerTypeLoc) CheckPolymorphic(AtomicTypeLoc) + + /// Handle all the types we haven't given a more specific + /// implementation for above. + void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { // Every other kind of type that we haven't called out already // that has an inner type is either (1) sugar or (2) contains that // inner type in some way as a subobject. @@ -5974,7 +5889,8 @@ // If there's no inner type and we're in a permissive context, // don't diagnose. - if (Sel == Sema::AbstractNone) return; + if (Sel == Sema::AbstractNone) + return; // Check whether the type matches the abstract type. QualType T = TL.getType(); @@ -5983,16 +5899,17 @@ T = Info.S.Context.getBaseElementType(T); } CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); - if (CT != Info.AbstractType) return; + if (CT != Info.AbstractType) + return; // It matched; do some magic. // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. if (Sel == Sema::AbstractArrayType) { Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) - << T << TL.getSourceRange(); + << T << TL.getSourceRange(); } else { Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) - << Sel << T << TL.getSourceRange(); + << Sel << T << TL.getSourceRange(); } Info.DiagnoseAbstractType(); } @@ -6003,11 +5920,10 @@ CheckAbstractUsage(*this, D).Visit(TL, Sel); } -} +} // namespace /// Check for invalid uses of an abstract type in a function declaration. -static void CheckAbstractClassUsage(AbstractUsageInfo &Info, - FunctionDecl *FD) { +static void CheckAbstractClassUsage(AbstractUsageInfo &Info, FunctionDecl *FD) { // No need to do the check on definitions, which require that // the return/param types be complete. if (FD->doesThisDeclarationHaveABody()) @@ -6021,8 +5937,7 @@ } /// Check for invalid uses of an abstract type in a variable0 declaration. -static void CheckAbstractClassUsage(AbstractUsageInfo &Info, - VarDecl *VD) { +static void CheckAbstractClassUsage(AbstractUsageInfo &Info, VarDecl *VD) { // No need to do the check on definitions, which require that // the type is complete. if (VD->isThisDeclarationADefinition()) @@ -6036,12 +5951,14 @@ static void CheckAbstractClassUsage(AbstractUsageInfo &Info, CXXRecordDecl *RD) { for (auto *D : RD->decls()) { - if (D->isImplicit()) continue; + if (D->isImplicit()) + continue; // Step through friends to the befriended declaration. if (auto *FD = dyn_cast(D)) { D = FD->getFriendDecl(); - if (!D) continue; + if (!D) + continue; } // Functions and function templates. @@ -6050,7 +5967,7 @@ } else if (auto *FTD = dyn_cast(D)) { CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); - // Fields and static variables. + // Fields and static variables. } else if (auto *FD = dyn_cast(D)) { if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); @@ -6059,7 +5976,7 @@ } else if (auto *VTD = dyn_cast(D)) { CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); - // Nested classes and class templates. + // Nested classes and class templates. } else if (auto *RD = dyn_cast(D)) { CheckAbstractClassUsage(Info, RD); } else if (auto *CTD = dyn_cast(D)) { @@ -6094,9 +6011,7 @@ Ctx.Entity = Class; S.pushCodeSynthesisContext(Ctx); } - ~MarkingClassDllexported() { - S.popCodeSynthesisContext(); - } + ~MarkingClassDllexported() { S.popCodeSynthesisContext(); } } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) @@ -6147,8 +6062,7 @@ // definition again later, so pass it to the consumer now. S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); } - } else if (!MD->isTrivial() || - MD->isCopyAssignmentOperator() || + } else if (!MD->isTrivial() || MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) { // Synthesize and instantiate non-trivial implicit methods, and the copy // and move assignment operators. The latter are exported even if they @@ -6323,7 +6237,8 @@ for (auto *Method : Class->methods()) { if (Method->isUserProvided()) continue; - if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) + if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction( + Method, /*IsDefinition=*/true)) Method->addAttr(A); } } @@ -6364,7 +6279,7 @@ continue; Diag(MemberAttr->getLocation(), - diag::err_attribute_dll_member_of_dll_class) + diag::err_attribute_dll_member_of_dll_class) << MemberAttr << ClassAttr; Diag(ClassAttr->getLocation(), diag::note_previous_attribute); Member->setInvalidDecl(); @@ -6542,11 +6457,11 @@ Diag(ClassAttr->getLocation(), diag::note_attribute); if (BaseTemplateSpec->isExplicitSpecialization()) { Diag(BaseTemplateSpec->getLocation(), - diag::note_template_class_explicit_specialization_was_here) + diag::note_template_class_explicit_specialization_was_here) << BaseTemplateSpec; } else { Diag(BaseTemplateSpec->getPointOfInstantiation(), - diag::note_template_class_instantiation_was_here) + diag::note_template_class_instantiation_was_here) << BaseTemplateSpec; } } @@ -6810,13 +6725,12 @@ (F->getType().isConstQualified() && F->getType()->isScalarType())) { if (!Complained) { Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) - << Record->getTagKind() << Record; + << Record->getTagKind() << Record; Complained = true; } Diag(F->getLocation(), diag::note_refconst_member_not_initialized) - << F->getType()->isReferenceType() - << F->getDeclName(); + << F->getType()->isReferenceType() << F->getDeclName(); } } } @@ -6831,14 +6745,13 @@ // In addition, if class T has a user-declared constructor (12.1), every // non-static data member of class T shall have a name different from T. DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); - 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) { NamedDecl *D = (*I)->getUnderlyingDecl(); if (((isa(D) || isa(D)) && Record->hasUserDeclaredConstructor()) || isa(D)) { Diag((*I)->getLocation(), diag::err_member_name_of_class) - << D->getDeclName(); + << D->getDeclName(); break; } } @@ -6850,13 +6763,14 @@ if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && !Record->hasAttr()) Diag(dtor ? dtor->getLocation() : Record->getLocation(), - diag::warn_non_virtual_dtor) << Context.getRecordType(Record); + diag::warn_non_virtual_dtor) + << Context.getRecordType(Record); } if (Record->isAbstract()) { if (FinalAttr *FA = Record->getAttr()) { Diag(Record->getLocation(), diag::warn_abstract_final_class) - << FA->isSpelledAsSealed(); + << FA->isSpelledAsSealed(); DiagnoseAbstractType(Record); } } @@ -6891,7 +6805,7 @@ // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). // We check these last because they can depend on the properties of the // primary comparison functions (==, <=>). - llvm::SmallVector DefaultedSecondaryComparisons; + llvm::SmallVector DefaultedSecondaryComparisons; // Perform checks that can't be done until we know all the properties of a // member function (whether it's defaulted, deleted, virtual, overriding, @@ -6974,7 +6888,8 @@ // Set triviality for the purpose of calls if this is a user-provided // copy/move constructor or destructor. if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || - CSM == CXXDestructor) && M->isUserProvided()) { + CSM == CXXDestructor) && + M->isUserProvided()) { M->setTrivialForCall(HasTrivialABI); Record->setTrivialForCallFlags(M); } @@ -7118,9 +7033,10 @@ /// \param ConstRHS True if this is a copy operation with a const object /// on its RHS, that is, if the argument to the outer special member /// function is 'const' and this is not a field marked 'mutable'. -static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( - Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, - unsigned FieldQuals, bool ConstRHS) { +static Sema::SpecialMemberOverloadResult +lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class, + Sema::CXXSpecialMember CSM, unsigned FieldQuals, + bool ConstRHS) { unsigned LHSQuals = 0; if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) LHSQuals = FieldQuals; @@ -7131,12 +7047,9 @@ else if (ConstRHS) RHSQuals |= Qualifiers::Const; - return S.LookupSpecialMember(Class, CSM, - RHSQuals & Qualifiers::Const, - RHSQuals & Qualifiers::Volatile, - false, - LHSQuals & Qualifiers::Const, - LHSQuals & Qualifiers::Volatile); + return S.LookupSpecialMember( + Class, CSM, RHSQuals & Qualifiers::Const, RHSQuals & Qualifiers::Volatile, + false, LHSQuals & Qualifiers::Const, LHSQuals & Qualifiers::Volatile); } class Sema::InheritedConstructorInfo { @@ -7222,12 +7135,10 @@ /// Is the special member function which would be selected to perform the /// specified operation on the specified class type a constexpr constructor? -static bool -specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, - Sema::CXXSpecialMember CSM, unsigned Quals, - bool ConstRHS, - CXXConstructorDecl *InheritedCtor = nullptr, - Sema::InheritedConstructorInfo *Inherited = nullptr) { +static bool specialMemberIsConstexpr( + Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, + unsigned Quals, bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr, + Sema::InheritedConstructorInfo *Inherited = nullptr) { // Suppress duplicate constraint checking here, in case a constraint check // caused us to decide to do this. Any truely recursive checks will get // caught during these checks anyway. @@ -7371,24 +7282,22 @@ struct ComputingExceptionSpec { Sema &S; - ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) - : S(S) { + ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) : S(S) { Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; Ctx.PointOfInstantiation = Loc; Ctx.Entity = FD; S.pushCodeSynthesisContext(Ctx); } - ~ComputingExceptionSpec() { - S.popCodeSynthesisContext(); - } + ~ComputingExceptionSpec() { S.popCodeSynthesisContext(); } }; -} +} // namespace static Sema::ImplicitExceptionSpecification -ComputeDefaultedSpecialMemberExceptionSpec( - Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, - Sema::InheritedConstructorInfo *ICI); +ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc, + CXXMethodDecl *MD, + Sema::CXXSpecialMember CSM, + Sema::InheritedConstructorInfo *ICI); static Sema::ImplicitExceptionSpecification ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, @@ -7501,14 +7410,14 @@ // default argument is classified as a default constructor, and assignment // operations and destructors can't have default arguments. Diag(MD->getLocation(), diag::err_defaulted_special_member_params) - << CSM << MD->getSourceRange(); + << CSM << MD->getSourceRange(); HadError = true; } else if (MD->isVariadic()) { if (DeleteOnTypeMismatch) ShouldDeleteForTypeMismatch = true; else { Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) - << CSM << MD->getSourceRange(); + << CSM << MD->getSourceRange(); HadError = true; } } @@ -7528,22 +7437,24 @@ QualType DeclType = Context.getTypeDeclType(RD); DeclType = Context.getElaboratedType(ETK_None, nullptr, DeclType, nullptr); - DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); + DeclType = Context.getAddrSpaceQualType( + DeclType, MD->getMethodQualifiers().getAddressSpace()); QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) - << (CSM == CXXMoveAssignment) << ExpectedReturnType; + << (CSM == CXXMoveAssignment) << ExpectedReturnType; HadError = true; } // A defaulted special member cannot have cv-qualifiers. - if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { + if (Type->getMethodQuals().hasConst() || + Type->getMethodQuals().hasVolatile()) { if (DeleteOnTypeMismatch) ShouldDeleteForTypeMismatch = true; else { Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) - << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; + << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; HadError = true; } } @@ -7562,7 +7473,8 @@ ShouldDeleteForTypeMismatch = true; else { Diag(MD->getLocation(), - diag::err_defaulted_special_member_volatile_param) << CSM; + diag::err_defaulted_special_member_volatile_param) + << CSM; HadError = true; } } @@ -7573,13 +7485,13 @@ else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { Diag(MD->getLocation(), diag::err_defaulted_special_member_copy_const_param) - << (CSM == CXXCopyAssignment); + << (CSM == CXXCopyAssignment); // FIXME: Explain why this special member can't be const. HadError = true; } else { Diag(MD->getLocation(), diag::err_defaulted_special_member_move_const_param) - << (CSM == CXXMoveAssignment); + << (CSM == CXXMoveAssignment); HadError = true; } } @@ -7600,8 +7512,8 @@ // destructors in C++14 and C++17), this is checked elsewhere. // // FIXME: This should not apply if the member is deleted. - bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, - HasConstParam); + bool Constexpr = + defaultedSpecialMemberIsConstexpr(*this, RD, CSM, HasConstParam); // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358): // If the instantiated template specialization of a constexpr function @@ -7665,7 +7577,8 @@ } if (ShouldDeleteForTypeMismatch && !HadError) { Diag(MD->getLocation(), - diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; + diag::warn_cxx17_compat_defaulted_method_type_mismatch) + << CSM; } } else { // C++11 [dcl.fct.def.default]p4: @@ -7673,7 +7586,7 @@ // function is implicitly defined as deleted, the program is ill-formed. Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); - ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); + ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/ true); HadError = true; } } @@ -7694,8 +7607,8 @@ /// /// This is accomplished by performing two visitation steps over the eventual /// body of the function. -template +template class DefaultedComparisonVisitor { public: using DefaultedComparisonKind = Sema::DefaultedComparisonKind; @@ -7737,7 +7650,7 @@ } protected: - Derived &getDerived() { return static_cast(*this); } + Derived &getDerived() { return static_cast(*this); } /// Visit the expanded list of subobjects of the given type, as specified in /// C++2a [class.compare.default]. @@ -7833,10 +7746,9 @@ /// A visitor over the notional body of a defaulted comparison that determines /// whether that body would be deleted or constexpr. class DefaultedComparisonAnalyzer - : public DefaultedComparisonVisitor { + : public DefaultedComparisonVisitor< + DefaultedComparisonAnalyzer, DefaultedComparisonInfo, + DefaultedComparisonInfo, DefaultedComparisonSubobject> { public: enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; @@ -7864,7 +7776,7 @@ // deleted if [...] C has variant members. if (Diagnose == ExplainDeleted) { S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) - << FD << RD->isUnion() << RD; + << FD << RD->isUnion() << RD; } return Result::deleted(); } @@ -8001,7 +7913,7 @@ if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { if (Subobj.Kind != Subobject::CompleteObject) S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) - << Subobj.Kind << Subobj.Decl; + << Subobj.Kind << Subobj.Decl; S.Diag(BestFD->getLocation(), diag::note_defaulted_comparison_not_constexpr_here); // Bail out after explaining; we don't want any more notes. @@ -8093,8 +8005,7 @@ diag::note_defaulted_comparison_not_rewritten_callee) << FD; } else { - S.Diag(Subobj.Loc, - diag::note_defaulted_comparison_calls_deleted) + S.Diag(Subobj.Loc, diag::note_defaulted_comparison_calls_deleted) << FD << Subobj.Kind << Subobj.Decl; S.NoteDeletedFunction(Best->Function); } @@ -8147,7 +8058,7 @@ /// A list of statements. struct StmtListResult { bool IsInvalid = false; - llvm::SmallVector Stmts; + llvm::SmallVector Stmts; bool add(const StmtResult &S) { IsInvalid |= S.isInvalid(); @@ -8527,7 +8438,7 @@ SourceRange(Loc, Loc), SourceRange(Loc, Loc)); } }; -} +} // namespace /// Perform the unqualified lookups that might be needed to form a defaulted /// comparison function for the given operator. @@ -8959,8 +8870,7 @@ namespace { /// CRTP base class for visiting operations performed by a special member /// function (or inherited constructor). -template -struct SpecialMemberVisitor { +template struct SpecialMemberVisitor { Sema &S; CXXMethodDecl *MD; Sema::CXXSpecialMember CSM; @@ -8995,7 +8905,7 @@ } } - Derived &getDerived() { return static_cast(*this); } + Derived &getDerived() { return static_cast(*this); } /// Is this a "move" special member? bool isMove() const { @@ -9015,24 +8925,25 @@ if (!ICI) return {}; assert(CSM == Sema::CXXDefaultConstructor); - auto *BaseCtor = - cast(MD)->getInheritedConstructor().getConstructor(); + auto *BaseCtor = cast(MD) + ->getInheritedConstructor() + .getConstructor(); if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) return MD; return {}; } /// A base or member subobject. - typedef llvm::PointerUnion Subobject; + typedef llvm::PointerUnion Subobject; /// Get the location to use for a subobject in diagnostics. static SourceLocation getSubobjectLoc(Subobject Subobj) { // FIXME: For an indirect virtual base, the direct base leading to // the indirect virtual base would be a more useful choice. - if (auto *B = Subobj.dyn_cast()) + if (auto *B = Subobj.dyn_cast()) return B->getBaseTypeLoc(); else - return Subobj.get()->getLocation(); + return Subobj.get()->getLocation(); } enum BasesToVisit { @@ -9072,7 +8983,7 @@ return false; } }; -} +} // namespace namespace { struct SpecialMemberDeletionInfo @@ -9112,7 +9023,7 @@ bool isAccessible(Subobject Subobj, CXXMethodDecl *D); }; -} +} // namespace /// Is the given special member inaccessible when used on the given /// sub-object. @@ -9122,11 +9033,11 @@ /// type of this special member. QualType objectTy; AccessSpecifier access = target->getAccess(); - if (CXXBaseSpecifier *base = Subobj.dyn_cast()) { + if (CXXBaseSpecifier *base = Subobj.dyn_cast()) { objectTy = S.Context.getTypeDeclType(MD->getParent()); access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); - // If we're operating on a field, the object type is the type of the field. + // If we're operating on a field, the object type is the type of the field. } else { objectTy = S.Context.getTypeDeclType(target->getParent()); } @@ -9141,7 +9052,7 @@ Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, bool IsDtorCallInCtor) { CXXMethodDecl *Decl = SMOR.getMethod(); - FieldDecl *Field = Subobj.dyn_cast(); + FieldDecl *Field = Subobj.dyn_cast(); int DiagKind = -1; @@ -9179,15 +9090,15 @@ if (Field) { S.Diag(Field->getLocation(), diag::note_deleted_special_member_class_subobject) - << getEffectiveCSM() << MD->getParent() << /*IsField*/true - << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; + << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field + << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false; } else { - CXXBaseSpecifier *Base = Subobj.get(); + CXXBaseSpecifier *Base = Subobj.get(); S.Diag(Base->getBeginLoc(), diag::note_deleted_special_member_class_subobject) << getEffectiveCSM() << MD->getParent() << /*IsField*/ false << Base->getType() << DiagKind << IsDtorCallInCtor - << /*IsObjCPtr*/false; + << /*IsObjCPtr*/ false; } if (DiagKind == 1) @@ -9202,7 +9113,7 @@ /// direct or virtual base class or non-static data member of class type M. bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { - FieldDecl *Field = Subobj.dyn_cast(); + FieldDecl *Field = Subobj.dyn_cast(); bool IsMutable = Field && Field->isMutable(); // C++11 [class.ctor]p5: @@ -9219,8 +9130,8 @@ // C++11 [class.dtor]p5: // -- any direct or virtual base class [...] has a type with a destructor // that is deleted or inaccessible - if (!(CSM == Sema::CXXDefaultConstructor && - Field && Field->hasInClassInitializer()) && + if (!(CSM == Sema::CXXDefaultConstructor && Field && + Field->hasInClassInitializer()) && shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), false)) return true; @@ -9229,9 +9140,8 @@ // -- any direct or virtual base class or non-static data member has a // type with a destructor that is deleted or inaccessible if (IsConstructor) { - Sema::SpecialMemberOverloadResult SMOR = - S.LookupSpecialMember(Class, Sema::CXXDestructor, - false, false, false, false, false); + Sema::SpecialMemberOverloadResult SMOR = S.LookupSpecialMember( + Class, Sema::CXXDestructor, false, false, false, false, false); if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) return true; } @@ -9254,10 +9164,9 @@ if (Diagnose) { auto *ParentClass = cast(FD->getParent()); - S.Diag(FD->getLocation(), - diag::note_deleted_special_member_class_subobject) - << getEffectiveCSM() << ParentClass << /*IsField*/true - << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; + S.Diag(FD->getLocation(), diag::note_deleted_special_member_class_subobject) + << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4 + << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true; } return true; @@ -9284,7 +9193,7 @@ diag::note_deleted_special_member_class_subobject) << getEffectiveCSM() << MD->getParent() << /*IsField*/ false << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false - << /*IsObjCPtr*/false; + << /*IsObjCPtr*/ false; S.NoteDeletedFunction(BaseCtor); } return BaseCtor->isDeleted(); @@ -9307,7 +9216,7 @@ if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { if (Diagnose) S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) - << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; + << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/ 0; return true; } // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static @@ -9318,7 +9227,7 @@ (!FieldRecord || !FieldRecord->allowConstDefaultInit())) { if (Diagnose) S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) - << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; + << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/ 1; return true; } @@ -9330,7 +9239,7 @@ if (FieldType->isRValueReferenceType()) { if (Diagnose) S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) - << MD->getParent() << FD << FieldType; + << MD->getParent() << FD << FieldType; return true; } } else if (IsAssignment) { @@ -9338,7 +9247,8 @@ if (FieldType->isReferenceType()) { if (Diagnose) S.Diag(FD->getLocation(), diag::note_deleted_assign_field) - << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; + << isMove() << MD->getParent() << FD << FieldType + << /*Reference*/ 0; return true; } if (!FieldRecord && FieldType.isConstQualified()) { @@ -9346,7 +9256,8 @@ // -- a non-static data member of const non-class type (or array thereof) if (Diagnose) S.Diag(FD->getLocation(), diag::note_deleted_assign_field) - << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; + << isMove() << MD->getParent() << FD << FD->getType() + << /*Const*/ 1; return true; } } @@ -9380,7 +9291,7 @@ if (Diagnose) S.Diag(FieldRecord->getLocation(), diag::note_deleted_default_ctor_all_const) - << !!ICI << MD->getParent() << /*anonymous union*/1; + << !!ICI << MD->getParent() << /*anonymous union*/ 1; return true; } @@ -9414,7 +9325,7 @@ if (Diagnose) S.Diag(MD->getParent()->getLocation(), diag::note_deleted_default_ctor_all_const) - << !!ICI << MD->getParent() << /*not anonymous union*/0; + << !!ICI << MD->getParent() << /*not anonymous union*/ 0; return true; } return false; @@ -9469,7 +9380,8 @@ if (RD->hasUserDeclaredMoveConstructor() && (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { - if (!Diagnose) return true; + if (!Diagnose) + return true; // Find any user-declared move constructor. for (auto *I : RD->ctors()) { @@ -9481,7 +9393,8 @@ assert(UserDeclaredMove); } else if (RD->hasUserDeclaredMoveAssignment() && (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { - if (!Diagnose) return true; + if (!Diagnose) + return true; // Find any user-declared move assignment operator. for (auto *I : RD->methods()) { @@ -9496,8 +9409,8 @@ if (UserDeclaredMove) { Diag(UserDeclaredMove->getLocation(), diag::note_deleted_copy_user_declared_move) - << (CSM == CXXCopyAssignment) << RD - << UserDeclaredMove->isMoveAssignmentOperator(); + << (CSM == CXXCopyAssignment) << RD + << UserDeclaredMove->isMoveAssignmentOperator(); return true; } } @@ -9511,9 +9424,9 @@ if (CSM == CXXDestructor && MD->isVirtual()) { FunctionDecl *OperatorDelete = nullptr; DeclarationName Name = - Context.DeclarationNames.getCXXOperatorName(OO_Delete); + Context.DeclarationNames.getCXXOperatorName(OO_Delete); if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, - OperatorDelete, /*Diagnose*/false)) { + OperatorDelete, /*Diagnose*/ false)) { if (Diagnose) Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); return true; @@ -9626,9 +9539,8 @@ // C++11 [class.dtor]p5: // A destructor is trivial if: // - all the direct [subobjects] have trivial destructors - if (RD->hasTrivialDestructor() || - (TAH == Sema::TAH_ConsiderTrivialABI && - RD->hasTrivialDestructorForCall())) + if (RD->hasTrivialDestructor() || (TAH == Sema::TAH_ConsiderTrivialABI && + RD->hasTrivialDestructorForCall())) return true; if (Selected) { @@ -9717,7 +9629,7 @@ typedef CXXRecordDecl::specific_decl_iterator tmpl_iter; for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { if (CXXConstructorDecl *CD = - dyn_cast(TI->getTemplatedDecl())) + dyn_cast(TI->getTemplatedDecl())) return CD; } @@ -9740,7 +9652,8 @@ QualType SubType, bool ConstRHS, Sema::CXXSpecialMember CSM, TrivialSubobjectKind Kind, - Sema::TrivialABIHandling TAH, bool Diagnose) { + Sema::TrivialABIHandling TAH, + bool Diagnose) { CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); if (!SubRD) return true; @@ -9756,25 +9669,25 @@ if (!Selected && CSM == Sema::CXXDefaultConstructor) { S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) - << Kind << SubType.getUnqualifiedType(); + << Kind << SubType.getUnqualifiedType(); if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) S.Diag(CD->getLocation(), diag::note_user_declared_ctor); } else if (!Selected) S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) - << Kind << SubType.getUnqualifiedType() << CSM << SubType; + << Kind << SubType.getUnqualifiedType() << CSM << SubType; else if (Selected->isUserProvided()) { if (Kind == TSK_CompleteObject) S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) - << Kind << SubType.getUnqualifiedType() << CSM; + << Kind << SubType.getUnqualifiedType() << CSM; else { S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) - << Kind << SubType.getUnqualifiedType() << CSM; + << Kind << SubType.getUnqualifiedType() << CSM; S.Diag(Selected->getLocation(), diag::note_declared_at); } } else { if (Kind != TSK_CompleteObject) S.Diag(SubobjLoc, diag::note_nontrivial_subobject) - << Kind << SubType.getUnqualifiedType() << CSM; + << Kind << SubType.getUnqualifiedType() << CSM; // Explain why the defaulted or deleted special member isn't trivial. S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, @@ -9788,8 +9701,7 @@ /// Check whether the members of a class type allow a special member to be /// trivial. static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, - Sema::CXXSpecialMember CSM, - bool ConstArg, + Sema::CXXSpecialMember CSM, bool ConstArg, Sema::TrivialABIHandling TAH, bool Diagnose) { for (const auto *FI : RD->fields()) { @@ -9800,8 +9712,8 @@ // Pretend anonymous struct or union members are members of this class. if (FI->isAnonymousStructOrUnion()) { - if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), - CSM, ConstArg, TAH, Diagnose)) + if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), CSM, + ConstArg, TAH, Diagnose)) return false; continue; } @@ -9824,7 +9736,7 @@ if (FieldType.hasNonTrivialObjCLifetime()) { if (Diagnose) S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) - << RD << FieldType.getObjCLifetime(); + << RD << FieldType.getObjCLifetime(); return false; } @@ -9845,7 +9757,7 @@ bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, TSK_CompleteObject, TAH_IgnoreTrivialABI, - /*Diagnose*/true); + /*Diagnose*/ true); } /// Determine whether a defaulted or deleted special member function is trivial, @@ -9888,9 +9800,9 @@ ClangABICompat14)) { if (Diagnose) Diag(Param0->getLocation(), diag::note_nontrivial_param_type) - << Param0->getSourceRange() << Param0->getType() - << Context.getLValueReferenceType( - Context.getRecordType(RD).withConst()); + << Param0->getSourceRange() << Param0->getType() + << Context.getLValueReferenceType( + Context.getRecordType(RD).withConst()); return false; } @@ -9903,12 +9815,12 @@ // Trivial move operations always have non-cv-qualified parameters. const ParmVarDecl *Param0 = MD->getParamDecl(0); const RValueReferenceType *RT = - Param0->getType()->getAs(); + Param0->getType()->getAs(); if (!RT || RT->getPointeeType().getCVRQualifiers()) { if (Diagnose) Diag(Param0->getLocation(), diag::note_nontrivial_param_type) - << Param0->getSourceRange() << Param0->getType() - << Context.getRValueReferenceType(Context.getRecordType(RD)); + << Param0->getSourceRange() << Param0->getType() + << Context.getRValueReferenceType(Context.getRecordType(RD)); return false; } break; @@ -9922,7 +9834,7 @@ if (Diagnose) Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), diag::note_nontrivial_default_arg) - << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); + << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); return false; } if (MD->isVariadic()) { @@ -10070,8 +9982,9 @@ } // end anonymous namespace /// Add the most overridden methods from MD to Methods -static void AddMostOverridenMethods(const CXXMethodDecl *MD, - llvm::SmallPtrSetImpl& Methods) { +static void +AddMostOverridenMethods(const CXXMethodDecl *MD, + llvm::SmallPtrSetImpl &Methods) { if (MD->size_overridden_methods() == 0) Methods.insert(MD->getCanonicalDecl()); else @@ -10081,8 +9994,8 @@ /// Check if a method overloads virtual methods in a base class without /// overriding any. -void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, - SmallVectorImpl &OverloadedMethods) { +void Sema::FindHiddenVirtualMethods( + CXXMethodDecl *MD, SmallVectorImpl &OverloadedMethods) { if (!MD->getDeclName().isIdentifier()) return; @@ -10109,12 +10022,13 @@ OverloadedMethods = FHVM.OverloadedMethods; } -void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, - SmallVectorImpl &OverloadedMethods) { +void Sema::NoteHiddenVirtualMethods( + CXXMethodDecl *MD, SmallVectorImpl &OverloadedMethods) { for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { CXXMethodDecl *overloadedMD = OverloadedMethods[i]; - PartialDiagnostic PD = PDiag( - diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; + PartialDiagnostic PD = + PDiag(diag::note_hidden_overloaded_virtual_declared_here) + << overloadedMD; HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); Diag(overloadedMD->getLocation(), PD); } @@ -10133,7 +10047,7 @@ FindHiddenVirtualMethods(MD, OverloadedMethods); if (!OverloadedMethods.empty()) { Diag(MD->getLocation(), diag::warn_overloaded_virtual) - << MD << (OverloadedMethods.size() > 1); + << MD << (OverloadedMethods.size() > 1); NoteHiddenVirtualMethods(MD, OverloadedMethods); } @@ -10144,9 +10058,11 @@ // No diagnostics if this is a template instantiation. if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { Diag(RD.getAttr()->getLocation(), - diag::ext_cannot_use_trivial_abi) << &RD; + diag::ext_cannot_use_trivial_abi) + << &RD; Diag(RD.getAttr()->getLocation(), - diag::note_cannot_use_trivial_abi_reason) << &RD << N; + diag::note_cannot_use_trivial_abi_reason) + << &RD << N; } RD.dropAttr(); }; @@ -10251,7 +10167,8 @@ // Traverse friends looking for an '==' or a '<=>'. for (FriendDecl *Friend : RD->friends()) { FunctionDecl *FD = dyn_cast_or_null(Friend->getFriendDecl()); - if (!FD) continue; + if (!FD) + continue; if (FD->getOverloadedOperator() == OO_EqualEqual) { // Friend operator== explicitly declared: no implicit operator==s. @@ -10446,14 +10363,16 @@ } void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { - if (!RecordD) return; + if (!RecordD) + return; AdjustDeclIfTemplate(RecordD); CXXRecordDecl *Record = cast(RecordD); PushDeclContext(S, Record); } void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { - if (!RecordD) return; + if (!RecordD) + return; PopDeclContext(); } @@ -10477,8 +10396,7 @@ /// Method declaration as if we had just parsed the qualified method /// name. However, it should not bring the parameters into scope; /// that will be performed by ActOnDelayedCXXMethodParameter. -void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { -} +void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {} /// ActOnDelayedCXXMethodParameter - We've already started a delayed /// C++ method declaration. We're (re-)introducing the given @@ -10561,15 +10479,15 @@ if (isVirtual) { if (!D.isInvalidType()) Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) - << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) - << SourceRange(D.getIdentifierLoc()); + << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) + << SourceRange(D.getIdentifierLoc()); D.setInvalidType(); } if (SC == SC_Static) { if (!D.isInvalidType()) Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) - << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) - << SourceRange(D.getIdentifierLoc()); + << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) + << SourceRange(D.getIdentifierLoc()); D.setInvalidType(); SC = SC_None; } @@ -10590,8 +10508,8 @@ DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); if (FTI.hasRefQualifier()) { Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) - << FTI.RefQualifierIsLValueRef - << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); + << FTI.RefQualifierIsLValueRef + << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); D.setInvalidType(); } @@ -10613,8 +10531,8 @@ /// well-formedness, issuing any diagnostics required. Returns true if /// the constructor declarator is invalid. void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { - CXXRecordDecl *ClassDecl - = dyn_cast(Constructor->getDeclContext()); + CXXRecordDecl *ClassDecl = + dyn_cast(Constructor->getDeclContext()); if (!ClassDecl) return Constructor->setInvalidDecl(); @@ -10631,11 +10549,11 @@ QualType ClassTy = Context.getTagDeclType(ClassDecl); if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); - const char *ConstRef - = Constructor->getParamDecl(0)->getIdentifier() ? "const &" - : " const &"; + const char *ConstRef = Constructor->getParamDecl(0)->getIdentifier() + ? "const &" + : " const &"; Diag(ParamLoc, diag::err_constructor_byvalue_arg) - << FixItHint::CreateInsertion(ParamLoc, ConstRef); + << FixItHint::CreateInsertion(ParamLoc, ConstRef); // FIXME: Rather that making the constructor invalid, we should endeavor // to fix the type. @@ -10703,7 +10621,7 @@ /// will be updated to reflect a well-formed type for the destructor and /// returned. QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, - StorageClass& SC) { + StorageClass &SC) { // C++ [class.dtor]p1: // [...] A typedef-name that names a class is a class-name // (7.1.3); however, a typedef-name that names a class shall not @@ -10712,12 +10630,12 @@ QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); if (const TypedefType *TT = DeclaratorType->getAs()) Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) - << DeclaratorType << isa(TT->getDecl()); + << DeclaratorType << isa(TT->getDecl()); else if (const TemplateSpecializationType *TST = - DeclaratorType->getAs()) + DeclaratorType->getAs()) if (TST->isTypeAlias()) Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) - << DeclaratorType << 1; + << DeclaratorType << 1; // C++ [class.dtor]p2: // A destructor is used to destroy objects of its class type. A @@ -10730,9 +10648,9 @@ if (SC == SC_Static) { if (!D.isInvalidType()) Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) - << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) - << SourceRange(D.getIdentifierLoc()) - << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); + << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) + << SourceRange(D.getIdentifierLoc()) + << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); SC = SC_None; } @@ -10747,8 +10665,8 @@ // The return type will be eliminated later. if (D.getDeclSpec().hasTypeSpecifier()) Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) - << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) - << SourceRange(D.getIdentifierLoc()); + << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) + << SourceRange(D.getIdentifierLoc()); else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, SourceLocation(), @@ -10767,8 +10685,8 @@ DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); if (FTI.hasRefQualifier()) { Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) - << FTI.RefQualifierIsLValueRef - << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); + << FTI.RefQualifierIsLValueRef + << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); D.setInvalidType(); } @@ -10825,7 +10743,7 @@ /// false. Either way, the type @p R will be updated to reflect a /// well-formed type for the conversion operator. void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, - StorageClass& SC) { + StorageClass &SC) { // C++ [class.conv.fct]p1: // Neither parameter types nor return type can be specified. The // type of a conversion function (8.3.5) is "function taking no @@ -10833,8 +10751,8 @@ if (SC == SC_Static) { if (!D.isInvalidType()) Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) - << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) - << D.getName().getSourceRange(); + << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) + << D.getName().getSourceRange(); D.setInvalidType(); SC = SC_None; } @@ -10854,8 +10772,8 @@ // // The return type will be changed later anyway. Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) - << SourceRange(DS.getTypeSpecTypeLoc()) - << SourceRange(D.getIdentifierLoc()); + << SourceRange(DS.getTypeSpecTypeLoc()) + << SourceRange(D.getIdentifierLoc()); D.setInvalidType(); } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { // It's also plausible that the user writes type qualifiers in the wrong @@ -10897,7 +10815,8 @@ if (Chunk.Fun.HasTrailingReturnType) { TypeSourceInfo *TRT = nullptr; GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); - if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); + if (TRT) + extendRight(After, TRT->getTypeLoc().getSourceRange()); } PastFunctionChunk = true; break; @@ -10923,14 +10842,14 @@ } } - SourceLocation Loc = Before.isValid() ? Before.getBegin() : - After.isValid() ? After.getBegin() : - D.getIdentifierLoc(); + SourceLocation Loc = Before.isValid() ? Before.getBegin() + : After.isValid() ? After.getBegin() + : D.getIdentifierLoc(); auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); DB << Before << After; if (!NeedsTypedef) { - DB << /*don't need a typedef*/0; + DB << /*don't need a typedef*/ 0; // If we can provide a correct fix-it hint, do so. if (After.isInvalid() && ConvTSI) { @@ -10942,11 +10861,11 @@ << FixItHint::CreateRemoval(Before); } } else if (!Proto->getReturnType()->isDependentType()) { - DB << /*typedef*/1 << Proto->getReturnType(); + DB << /*typedef*/ 1 << Proto->getReturnType(); } else if (getLangOpts().CPlusPlus11) { - DB << /*alias template*/2 << Proto->getReturnType(); + DB << /*alias template*/ 2 << Proto->getReturnType(); } else { - DB << /*might not be fixable*/3; + DB << /*might not be fixable*/ 3; } // Recover by incorporating the other type chunks into the result type. @@ -11004,8 +10923,8 @@ // same object type (or a reference to it), to a (possibly // cv-qualified) base class of that type (or a reference to it), // or to (possibly cv-qualified) void. - QualType ClassType - = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); + QualType ClassType = + Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); if (const ReferenceType *ConvTypeRef = ConvType->getAs()) ConvType = ConvTypeRef->getPointeeType(); if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && @@ -11017,17 +10936,17 @@ ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); if (ConvType == ClassType) Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) - << ClassType; + << ClassType; else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) - << ClassType << ConvType; + << ClassType << ConvType; } else if (ConvType->isVoidType()) { Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) - << ClassType << ConvType; + << ClassType << ConvType; } - if (FunctionTemplateDecl *ConversionTemplate - = Conversion->getDescribedFunctionTemplate()) + if (FunctionTemplateDecl *ConversionTemplate = + Conversion->getDescribedFunctionTemplate()) return ConversionTemplate; return Conversion; @@ -11039,11 +10958,9 @@ struct BadSpecifierDiagnoser { BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} - ~BadSpecifierDiagnoser() { - Diagnostic << Specifiers; - } + ~BadSpecifierDiagnoser() { Diagnostic << Specifiers; } - template void check(SourceLocation SpecLoc, T Spec) { + template void check(SourceLocation SpecLoc, T Spec) { return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); } void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { @@ -11051,9 +10968,11 @@ DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); } void check(SourceLocation SpecLoc, const char *Spec) { - if (SpecLoc.isInvalid()) return; + if (SpecLoc.isInvalid()) + return; Diagnostic << SourceRange(SpecLoc, SpecLoc); - if (!Specifiers.empty()) Specifiers += " "; + if (!Specifiers.empty()) + Specifiers += " "; Specifiers += Spec; } @@ -11061,7 +10980,7 @@ Sema::SemaDiagnosticBuilder Diagnostic; std::string Specifiers; }; -} +} // namespace /// Check the validity of a declarator that we parsed for a deduction-guide. /// These aren't actually declarators in the grammar, so we need to check that @@ -11079,7 +10998,7 @@ if (!CurContext->getRedeclContext()->Equals( GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) - << GuidedTemplateDecl; + << GuidedTemplateDecl; Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); } @@ -11162,8 +11081,8 @@ // This could still instantiate to the right type, unless we know it // names the wrong class template. auto *TD = SpecifiedName.getAsTemplateDecl(); - MightInstantiateToSpecialization = !(TD && isa(TD) && - !TemplateMatches); + MightInstantiateToSpecialization = + !(TD && isa(TD) && !TemplateMatches); } } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { MightInstantiateToSpecialization = true; @@ -11207,7 +11126,7 @@ // The user probably just forgot the 'inline', so suggest that it // be added back. S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) - << FixItHint::CreateInsertion(KeywordLoc, "inline "); + << FixItHint::CreateInsertion(KeywordLoc, "inline "); else S.Diag(Loc, diag::err_inline_namespace_mismatch); @@ -11256,12 +11175,11 @@ if (PrevNS) { // This is an extended namespace definition. if (IsInline != PrevNS->isInline()) - DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, - &IsInline, PrevNS); + DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, &IsInline, + PrevNS); } else if (PrevDecl) { // This is an invalid name redefinition. - Diag(Loc, diag::err_redefinition_different_kind) - << II; + Diag(Loc, diag::err_redefinition_different_kind) << II; Diag(PrevDecl->getLocation(), diag::note_previous_definition); IsInvalid = true; // Continue on to push Namespc as current DeclContext and return it. @@ -11340,13 +11258,13 @@ // namespace internal linkage. if (!PrevNS) { - UD = UsingDirectiveDecl::Create(Context, Parent, - /* 'using' */ LBrace, - /* 'namespace' */ SourceLocation(), - /* qualifier */ NestedNameSpecifierLoc(), - /* identifier */ SourceLocation(), - Namespc, - /* Ancestor */ Parent); + UD = + UsingDirectiveDecl::Create(Context, Parent, + /* 'using' */ LBrace, + /* 'namespace' */ SourceLocation(), + /* qualifier */ NestedNameSpecifierLoc(), + /* identifier */ SourceLocation(), Namespc, + /* Ancestor */ Parent); UD->setImplicit(); Parent->addDecl(UD); } @@ -11387,7 +11305,7 @@ CXXRecordDecl *Sema::getStdBadAlloc() const { return cast_or_null( - StdBadAlloc.get(Context.getExternalSource())); + StdBadAlloc.get(Context.getExternalSource())); } EnumDecl *Sema::getStdAlignValT() const { @@ -11396,7 +11314,7 @@ NamespaceDecl *Sema::getStdNamespace() const { return cast_or_null( - StdNamespace.get(Context.getExternalSource())); + StdNamespace.get(Context.getExternalSource())); } namespace { @@ -11611,7 +11529,8 @@ return true; } -static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ +static ClassTemplateDecl *LookupStdInitializerList(Sema &S, + SourceLocation Loc) { NamespaceDecl *Std = S.getStdNamespace(); if (!Std) { S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); @@ -11653,9 +11572,9 @@ } TemplateArgumentListInfo Args(Loc, Loc); - Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), - Context.getTrivialTypeSourceInfo(Element, - Loc))); + Args.addArgument( + TemplateArgumentLoc(TemplateArgument(Element), + Context.getTrivialTypeSourceInfo(Element, Loc))); return Context.getElaboratedType( ElaboratedTypeKeyword::ETK_None, NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()), @@ -11682,12 +11601,12 @@ /// apply in all contexts. static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { switch (CurContext->getDeclKind()) { - case Decl::TranslationUnit: - return true; - case Decl::LinkageSpec: - return IsUsingDirectiveInToplevelContext(CurContext->getParent()); - default: - return false; + case Decl::TranslationUnit: + return true; + case Decl::LinkageSpec: + return IsUsingDirectiveInToplevelContext(CurContext->getParent()); + default: + return false; } } @@ -11707,7 +11626,7 @@ } }; -} +} // namespace static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, CXXScopeSpec &SS, @@ -11724,7 +11643,7 @@ Ident->getName().equals(CorrectedStr); S.diagnoseTypo(Corrected, S.PDiag(diag::err_using_directive_member_suggest) - << Ident << DC << DroppedSpecifier << SS.getRange(), + << Ident << DC << DroppedSpecifier << SS.getRange(), S.PDiag(diag::note_namespace_defined_here)); } else { S.diagnoseTypo(Corrected, @@ -11773,7 +11692,8 @@ R.resolveKind(); } // Otherwise, attempt typo correction. - else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); + else + TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); } if (!R.empty()) { @@ -11801,8 +11721,8 @@ CommonAncestor = CommonAncestor->getParent(); UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, - SS.getWithLocInContext(Context), - IdentLoc, Named, CommonAncestor); + SS.getWithLocInContext(Context), IdentLoc, + Named, CommonAncestor); if (IsUsingDirectiveInToplevelContext(CurContext) && !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { @@ -11863,7 +11783,8 @@ : diag::err_using_decl_constructor) << SS.getRange(); - if (getLangOpts().CPlusPlus11) break; + if (getLangOpts().CPlusPlus11) + break; return nullptr; @@ -11901,16 +11822,16 @@ if (!SS.getScopeRep()->containsUnexpandedParameterPack() && !TargetNameInfo.containsUnexpandedParameterPack()) { Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) - << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); + << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); EllipsisLoc = SourceLocation(); } } - NamedDecl *UD = - BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, - SS, TargetNameInfo, EllipsisLoc, AttrList, - /*IsInstantiation*/ false, - AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); + NamedDecl *UD = BuildUsingDeclaration( + S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, SS, TargetNameInfo, + EllipsisLoc, AttrList, + /*IsInstantiation*/ false, + AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); if (UD) PushOnScopeChains(UD, S, /*AddToContext*/ false); @@ -11963,8 +11884,8 @@ /// Determine whether a using declaration considers the given /// declarations as "equivalent", e.g., if they are redeclarations of /// the same entity or are both typedefs of the same type. -static bool -IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { +static bool IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, + NamedDecl *D2) { if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) return true; @@ -11982,7 +11903,6 @@ return false; } - /// Determines whether to create a using shadow decl for a particular /// decl, given the set of decls existing prior to this using lookup. bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, @@ -12038,7 +11958,8 @@ } } - if (Previous.empty()) return false; + if (Previous.empty()) + return false; NamedDecl *Target = Orig; if (isa(Target)) @@ -12051,8 +11972,8 @@ // should redeclare it. NamedDecl *NonTag = nullptr, *Tag = nullptr; bool FoundEquivalentDecl = false; - for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); - I != E; ++I) { + for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); I != E; + ++I) { NamedDecl *D = (*I)->getUnderlyingDecl(); // We can have UsingDecls in our Previous results because we use the same // LookupResult for checking whether the UsingDecl itself is a valid @@ -12138,7 +12059,8 @@ if (isa(Target)) { // No conflict between a tag and a non-tag. - if (!Tag) return false; + if (!Tag) + return false; Diag(BUD->getLocation(), diag::err_using_decl_conflict); Diag(Target->getLocation(), diag::note_using_decl_target); @@ -12148,7 +12070,8 @@ } // No conflict between a tag and a non-tag. - if (!NonTag) return false; + if (!NonTag) + return false; Diag(BUD->getLocation(), diag::err_using_decl_conflict); Diag(Target->getLocation(), diag::note_using_decl_target); @@ -12207,7 +12130,6 @@ else CurContext->addDecl(Shadow); - return Shadow; } @@ -12240,7 +12162,7 @@ /// (2) avoids this but is very fiddly and phase-dependent. void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { if (Shadow->getDeclName().getNameKind() == - DeclarationName::CXXConversionFunctionName) + DeclarationName::CXXConversionFunctionName) cast(Shadow->getDeclContext())->removeConversion(Shadow); // Remove it from the DeclContext... @@ -12264,8 +12186,8 @@ QualType DesiredBase, bool &AnyDependentBases) { // Check whether the named type is a direct base class. - CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() - .getUnqualifiedType(); + CanQualType CanonicalDesiredBase = + DesiredBase->getCanonicalTypeUnqualified().getUnqualifiedType(); for (auto &Base : Derived->bases()) { CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); if (CanonicalDesiredBase == BaseType) @@ -12438,8 +12360,8 @@ } // Check for invalid redeclarations. - if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, - SS, IdentLoc, Previous)) + if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, SS, IdentLoc, + Previous)) return nullptr; // 'using_if_exists' doesn't make sense on an inherited constructor. @@ -12460,11 +12382,9 @@ if (HasTypenameKeyword) { // FIXME: not all declaration name kinds are legal here - D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, - UsingLoc, TypenameLoc, - QualifierLoc, - IdentLoc, NameInfo.getName(), - EllipsisLoc); + D = UnresolvedUsingTypenameDecl::Create( + Context, CurContext, UsingLoc, TypenameLoc, QualifierLoc, IdentLoc, + NameInfo.getName(), EllipsisLoc); } else { D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo, EllipsisLoc); @@ -12485,8 +12405,8 @@ UD->setInvalidDecl(Invalid); return UD; }; - auto BuildInvalid = [&]{ return Build(true); }; - auto BuildValid = [&]{ return Build(false); }; + auto BuildInvalid = [&] { return Build(true); }; + auto BuildValid = [&] { return Build(false); }; if (RequireCompleteDeclContext(SS, LookupContext)) return BuildInvalid(); @@ -12505,7 +12425,7 @@ // equal to that of the current context. if (CurContext->isRecord()) { R.setBaseObjectType( - Context.getTypeDeclType(cast(CurContext))); + Context.getTypeDeclType(cast(CurContext))); } LookupQualifiedName(R, LookupContext); @@ -12543,8 +12463,8 @@ // We reject candidates where DroppedSpecifier == true, hence the // literal '0' below. diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) - << NameInfo.getName() << LookupContext << 0 - << SS.getRange()); + << NameInfo.getName() << LookupContext << 0 + << SS.getRange()); // If we picked a correction with no attached Decl we can't do anything // useful with it, bail out. @@ -12583,7 +12503,7 @@ } } else { Diag(IdentLoc, diag::err_no_member) - << NameInfo.getName() << LookupContext << SS.getRange(); + << NameInfo.getName() << LookupContext << SS.getRange(); return BuildInvalid(); } } @@ -12616,7 +12536,7 @@ // A using-declaration shall not name a namespace. if (R.getAsSingle()) { Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) - << SS.getRange(); + << SS.getRange(); return BuildInvalid(); } @@ -12624,7 +12544,7 @@ // Some additional rules apply to inheriting constructors. if (UsingName.getName().getNameKind() == - DeclarationName::CXXConstructorName) { + DeclarationName::CXXConstructorName) { // Suppress access diagnostics; the access check is instead performed at the // point of use for an inheriting constructor. R.suppressDiagnostics(); @@ -12724,10 +12644,9 @@ auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), AnyDependentBases); if (!Base && !AnyDependentBases) { - Diag(UD->getUsingLoc(), - diag::err_using_decl_constructor_not_in_direct_base) - << UD->getNameInfo().getSourceRange() - << QualType(SourceType, 0) << TargetClass; + Diag(UD->getUsingLoc(), diag::err_using_decl_constructor_not_in_direct_base) + << UD->getNameInfo().getSourceRange() << QualType(SourceType, 0) + << TargetClass; UD->setInvalidDecl(); return true; } @@ -12766,9 +12685,9 @@ if (!isa(D) && !isa(D) && !isa(D)) { bool OldCouldBeEnumerator = isa(D) || isa(D); - Diag(NameLoc, - OldCouldBeEnumerator ? diag::err_redefinition - : diag::err_redefinition_different_kind) + Diag(NameLoc, OldCouldBeEnumerator + ? diag::err_redefinition + : diag::err_redefinition_different_kind) << Prev.getLookupName(); Diag(D->getLocation(), diag::note_previous_definition); return true; @@ -12788,19 +12707,21 @@ if (UsingDecl *UD = dyn_cast(D)) { DTypename = UD->hasTypename(); DQual = UD->getQualifier(); - } else if (UnresolvedUsingValueDecl *UD - = dyn_cast(D)) { + } else if (UnresolvedUsingValueDecl *UD = + dyn_cast(D)) { DTypename = false; DQual = UD->getQualifier(); - } else if (UnresolvedUsingTypenameDecl *UD - = dyn_cast(D)) { + } else if (UnresolvedUsingTypenameDecl *UD = + dyn_cast(D)) { DTypename = true; DQual = UD->getQualifier(); - } else continue; + } else + continue; // using decls differ if one says 'typename' and the other doesn't. // FIXME: non-dependent using decls? - if (HasTypenameKeyword != DTypename) continue; + if (HasTypenameKeyword != DTypename) + continue; // using decls differ if they name different scopes (but note that // template instantiation can cause this check to trigger when it @@ -12896,18 +12817,18 @@ if (getLangOpts().CPlusPlus11) { // Convert 'using X::Y;' to 'using Y = X::Y;'. Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) - << 0 // alias declaration - << FixItHint::CreateInsertion(SS.getBeginLoc(), - NameInfo.getName().getAsString() + - " = "); + << 0 // alias declaration + << FixItHint::CreateInsertion(SS.getBeginLoc(), + NameInfo.getName().getAsString() + + " = "); } else { // Convert 'using X::Y;' to 'typedef X::Y Y;'. SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); Diag(InsertLoc, diag::note_using_decl_class_member_workaround) - << 1 // typedef declaration - << FixItHint::CreateReplacement(UsingLoc, "typedef") - << FixItHint::CreateInsertion( - InsertLoc, " " + NameInfo.getName().getAsString()); + << 1 // typedef declaration + << FixItHint::CreateReplacement(UsingLoc, "typedef") + << FixItHint::CreateInsertion( + InsertLoc, " " + NameInfo.getName().getAsString()); } } else if (R->getAsSingle()) { // Don't provide a fixit outside C++11 mode; we don't want to suggest @@ -12920,8 +12841,8 @@ } Diag(UsingLoc, diag::note_using_decl_class_member_workaround) - << 2 // reference declaration - << FixIt; + << 2 // reference declaration + << FixIt; } else if (R->getAsSingle()) { // Don't provide a fixit outside C++11 mode; we don't want to suggest // repeating the type of the enumeration here, and we can't do so if @@ -12935,8 +12856,8 @@ } Diag(UsingLoc, diag::note_using_decl_class_member_workaround) - << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable - << FixIt; + << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable + << FixIt; } } @@ -12971,7 +12892,7 @@ } if (!NamedContext->isDependentContext() && - RequireCompleteDeclContext(const_cast(SS), NamedContext)) + RequireCompleteDeclContext(const_cast(SS), NamedContext)) return true; if (getLangOpts().CPlusPlus11) { @@ -12980,8 +12901,8 @@ // nested-name-specifier shall name a base class of the class // being defined. - if (cast(CurContext)->isProvablyNotDerivedFrom( - cast(NamedContext))) { + if (cast(CurContext) + ->isProvablyNotDerivedFrom(cast(NamedContext))) { if (Cxx20Enumerator) { Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) @@ -13045,9 +12966,7 @@ Diag(SS.getRange().getBegin(), diag::err_using_decl_nested_name_specifier_is_not_base_class) - << SS.getScopeRep() - << cast(CurContext) - << SS.getRange(); + << SS.getScopeRep() << cast(CurContext) << SS.getRange(); return true; } @@ -13090,15 +13009,16 @@ // Warn about shadowing the name of a template parameter. if (Previous.isSingleResult() && Previous.getFoundDecl()->isTemplateParameter()) { - DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); + DiagnoseTemplateParameterShadow(Name.StartLocation, + Previous.getFoundDecl()); Previous.clear(); } assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier && "name in alias declaration must be an identifier"); - TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, - Name.StartLocation, - Name.Identifier, TInfo); + TypeAliasDecl *NewTD = + TypeAliasDecl::Create(Context, CurContext, UsingLoc, Name.StartLocation, + Name.Identifier, TInfo); NewTD->setAccess(AS); @@ -13119,9 +13039,9 @@ TemplateParameterList *OldTemplateParams = nullptr; if (TemplateParamLists.size() != 1) { - Diag(UsingLoc, diag::err_alias_template_extra_headers) - << SourceRange(TemplateParamLists[1]->getTemplateLoc(), - TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); + Diag(UsingLoc, diag::err_alias_template_extra_headers) << SourceRange( + TemplateParamLists[1]->getTemplateLoc(), + TemplateParamLists[TemplateParamLists.size() - 1]->getRAngleLoc()); } TemplateParameterList *TemplateParams = TemplateParamLists[0]; @@ -13130,15 +13050,15 @@ return nullptr; // Only consider previous declarations in the same scope. - FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, - /*ExplicitInstantiationOrSpecialization*/false); + FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/ false, + /*ExplicitInstantiationOrSpecialization*/ false); if (!Previous.empty()) { Redeclaration = true; OldDecl = Previous.getAsSingle(); if (!OldDecl && !Invalid) { Diag(UsingLoc, diag::err_redefinition_different_kind) - << Name.Identifier; + << Name.Identifier; NamedDecl *OldD = Previous.getRepresentativeDecl(); if (OldD->getLocation().isValid()) @@ -13148,23 +13068,21 @@ } if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { - if (TemplateParameterListsAreEqual(TemplateParams, - OldDecl->getTemplateParameters(), - /*Complain=*/true, - TPL_TemplateMatch)) + if (TemplateParameterListsAreEqual( + TemplateParams, OldDecl->getTemplateParameters(), + /*Complain=*/true, TPL_TemplateMatch)) OldTemplateParams = OldDecl->getMostRecentDecl()->getTemplateParameters(); else Invalid = true; TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); - if (!Invalid && - !Context.hasSameType(OldTD->getUnderlyingType(), - NewTD->getUnderlyingType())) { + if (!Invalid && !Context.hasSameType(OldTD->getUnderlyingType(), + NewTD->getUnderlyingType())) { // FIXME: The C++0x standard does not clearly say this is ill-formed, // but we can't reasonably accept it. Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) - << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); + << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); if (OldTD->getLocation().isValid()) Diag(OldTD->getLocation(), diag::note_previous_definition); Invalid = true; @@ -13178,10 +13096,8 @@ TPC_TypeAliasTemplate)) return nullptr; - TypeAliasTemplateDecl *NewDecl = - TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, - Name.Identifier, TemplateParams, - NewTD); + TypeAliasTemplateDecl *NewDecl = TypeAliasTemplateDecl::Create( + Context, CurContext, UsingLoc, Name.Identifier, TemplateParams, NewTD); NewTD->setDescribedAliasTemplate(NewDecl); NewDecl->setAccess(AS); @@ -13242,8 +13158,8 @@ } // Filter out any other lookup result from an enclosing scope. - FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, - /*AllowInlineNamespace*/false); + FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/ false, + /*AllowInlineNamespace*/ false); // Find the previous declaration and check that we can redeclare it. NamespaceAliasDecl *Prev = nullptr; @@ -13256,9 +13172,9 @@ Prev = AD; } else if (isVisible(PrevDecl)) { Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) - << Alias; + << Alias; Diag(AD->getLocation(), diag::note_previous_namespace_alias) - << AD->getNamespace(); + << AD->getNamespace(); return nullptr; } } else if (isVisible(PrevDecl)) { @@ -13274,10 +13190,9 @@ // The use of a nested name specifier may trigger deprecation warnings. DiagnoseUseOfDecl(ND, IdentLoc); - NamespaceAliasDecl *AliasDecl = - NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, - Alias, SS.getWithLocInContext(Context), - IdentLoc, ND); + NamespaceAliasDecl *AliasDecl = NamespaceAliasDecl::Create( + Context, CurContext, NamespaceLoc, AliasLoc, Alias, + SS.getWithLocInContext(Context), IdentLoc, ND); if (Prev) AliasDecl->setPreviousDecl(Prev); @@ -13306,7 +13221,7 @@ void visitSubobjectCall(Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR); }; -} +} // namespace bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { auto *RT = Base->getType()->getAs(); @@ -13347,7 +13262,7 @@ void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { - FieldDecl *Field = Subobj.dyn_cast(); + FieldDecl *Field = Subobj.dyn_cast(); bool IsMutable = Field && Field->isMutable(); visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); } @@ -13466,11 +13381,9 @@ } /// Are we already trying to declare this special member? - bool isAlreadyBeingDeclared() const { - return WasAlreadyBeingDeclared; - } + bool isAlreadyBeingDeclared() const { return WasAlreadyBeingDeclared; } }; -} +} // namespace void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { // Look up any existing declarations, but don't trigger declaration of all @@ -13513,8 +13426,8 @@ } } -CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( - CXXRecordDecl *ClassDecl) { +CXXConstructorDecl * +Sema::DeclareImplicitDefaultConstructor(CXXRecordDecl *ClassDecl) { // C++ [class.ctor]p5: // A default constructor for a class X is a constructor of class X // that can be called without an argument. If there is no @@ -13528,16 +13441,15 @@ if (DSM.isAlreadyBeingDeclared()) return nullptr; - bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, - CXXDefaultConstructor, - false); + bool Constexpr = defaultedSpecialMemberIsConstexpr( + *this, ClassDecl, CXXDefaultConstructor, false); // Create the actual constructor declaration. - CanQualType ClassType - = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); + CanQualType ClassType = + Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); SourceLocation ClassLoc = ClassDecl->getLocation(); - DeclarationName Name - = Context.DeclarationNames.getCXXConstructorName(ClassType); + DeclarationName Name = + Context.DeclarationNames.getCXXConstructorName(ClassType); DeclarationNameInfo NameInfo(Name, ClassLoc); CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), @@ -13579,10 +13491,11 @@ void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor) { - assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && - !Constructor->doesThisDeclarationHaveABody() && - !Constructor->isDeleted()) && - "DefineImplicitDefaultConstructor - call it for implicit default ctor"); + assert( + (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && + !Constructor->doesThisDeclarationHaveABody() && + !Constructor->isDeleted()) && + "DefineImplicitDefaultConstructor - call it for implicit default ctor"); if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) return; @@ -13677,8 +13590,8 @@ FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); EPI.ExceptionSpec.Type = EST_Unevaluated; EPI.ExceptionSpec.SourceDecl = DerivedCtor; - DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), - FPT->getParamTypes(), EPI)); + DerivedCtor->setType( + Context.getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI)); // Build the parameter declarations. SmallVector ParamDecls; @@ -13713,7 +13626,7 @@ InheritedConstructorInfo ICI(*this, Ctor->getLocation(), Ctor->getInheritedConstructor().getShadowDecl()); ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, - /*Diagnose*/true); + /*Diagnose*/ true); } void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, @@ -13754,7 +13667,7 @@ // Build explicit initializers for all base classes from which the // constructor was inherited. - SmallVector Inits; + SmallVector Inits; for (bool VBase : {false, true}) { for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { if (B.isVirtual() != VBase) @@ -13782,7 +13695,7 @@ // We now proceed as if for a defaulted default constructor, with the relevant // initializers replaced. - if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { + if (SetCtorInitializers(Constructor, /*AnyErrors*/ false, Inits)) { Constructor->setInvalidDecl(); return; } @@ -13808,16 +13721,15 @@ if (DSM.isAlreadyBeingDeclared()) return nullptr; - bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, - CXXDestructor, - false); + bool Constexpr = + defaultedSpecialMemberIsConstexpr(*this, ClassDecl, CXXDestructor, false); // Create the actual destructor declaration. - CanQualType ClassType - = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); + CanQualType ClassType = + Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); SourceLocation ClassLoc = ClassDecl->getLocation(); - DeclarationName Name - = Context.DeclarationNames.getCXXDestructorName(ClassType); + DeclarationName Name = + Context.DeclarationNames.getCXXDestructorName(ClassType); DeclarationNameInfo NameInfo(Name, ClassLoc); CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, @@ -13943,7 +13855,7 @@ referenceDLLExportedClassMethods(); if (!DelayedDllExportMemberFunctions.empty()) { - SmallVector WorkList; + SmallVector WorkList; std::swap(DelayedDllExportMemberFunctions, WorkList); for (CXXMethodDecl *M : WorkList) { DefineDefaultedFunction(*this, M, M->getLocation()); @@ -14005,8 +13917,8 @@ // copy/move operators. These classes serve as factory functions and help us // avoid using the same Expr* in the AST twice. class ExprBuilder { - ExprBuilder(const ExprBuilder&) = delete; - ExprBuilder &operator=(const ExprBuilder&) = delete; + ExprBuilder(const ExprBuilder &) = delete; + ExprBuilder &operator=(const ExprBuilder &) = delete; protected: static Expr *assertNotNull(Expr *E) { @@ -14021,7 +13933,7 @@ virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; }; -class RefBuilder: public ExprBuilder { +class RefBuilder : public ExprBuilder { VarDecl *Var; QualType VarType; @@ -14030,18 +13942,17 @@ return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); } - RefBuilder(VarDecl *Var, QualType VarType) - : Var(Var), VarType(VarType) {} + RefBuilder(VarDecl *Var, QualType VarType) : Var(Var), VarType(VarType) {} }; -class ThisBuilder: public ExprBuilder { +class ThisBuilder : public ExprBuilder { public: Expr *build(Sema &S, SourceLocation Loc) const override { return assertNotNull(S.ActOnCXXThis(Loc).getAs()); } }; -class CastBuilder: public ExprBuilder { +class CastBuilder : public ExprBuilder { const ExprBuilder &Builder; QualType Type; ExprValueKind Kind; @@ -14051,7 +13962,8 @@ Expr *build(Sema &S, SourceLocation Loc) const override { return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, CK_UncheckedDerivedToBase, Kind, - &Path).get()); + &Path) + .get()); } CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, @@ -14059,7 +13971,7 @@ : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} }; -class DerefBuilder: public ExprBuilder { +class DerefBuilder : public ExprBuilder { const ExprBuilder &Builder; public: @@ -14071,7 +13983,7 @@ DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} }; -class MemberBuilder: public ExprBuilder { +class MemberBuilder : public ExprBuilder { const ExprBuilder &Builder; QualType Type; CXXScopeSpec SS; @@ -14080,9 +13992,11 @@ public: Expr *build(Sema &S, SourceLocation Loc) const override { - return assertNotNull(S.BuildMemberReferenceExpr( - Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), - nullptr, MemberLookup, nullptr, nullptr).get()); + return assertNotNull( + S.BuildMemberReferenceExpr(Builder.build(S, Loc), Type, Loc, IsArrow, + SS, SourceLocation(), nullptr, MemberLookup, + nullptr, nullptr) + .get()); } MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, @@ -14091,7 +14005,7 @@ MemberLookup(MemberLookup) {} }; -class MoveCastBuilder: public ExprBuilder { +class MoveCastBuilder : public ExprBuilder { const ExprBuilder &Builder; public: @@ -14102,7 +14016,7 @@ MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} }; -class LvalueConvBuilder: public ExprBuilder { +class LvalueConvBuilder : public ExprBuilder { const ExprBuilder &Builder; public: @@ -14114,14 +14028,15 @@ LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} }; -class SubscriptBuilder: public ExprBuilder { +class SubscriptBuilder : public ExprBuilder { const ExprBuilder &Base; const ExprBuilder &Index; public: Expr *build(Sema &S, SourceLocation Loc) const override { return assertNotNull(S.CreateBuiltinArraySubscriptExpr( - Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); + Base.build(S, Loc), Loc, Index.build(S, Loc), Loc) + .get()); } SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) @@ -14134,9 +14049,9 @@ /// should be copied with __builtin_memcpy rather than via explicit assignments, /// do so. This optimization only applies for arrays of scalars, and for arrays /// of class type where the selected copy/move-assignment operator is trivial. -static StmtResult -buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, - const ExprBuilder &ToB, const ExprBuilder &FromB) { +static StmtResult buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, + QualType T, const ExprBuilder &ToB, + const ExprBuilder &FromB) { // Compute the size of the memory buffer to be copied. QualType SizeType = S.Context.getSizeType(); llvm::APInt Size(S.Context.getTypeSize(SizeType), @@ -14160,9 +14075,9 @@ E->castAs()->getDecl()->hasObjectMember(); // Create a reference to the __builtin_objc_memmove_collectable function - StringRef MemCpyName = NeedsCollectableMemCpy ? - "__builtin_objc_memmove_collectable" : - "__builtin_memcpy"; + StringRef MemCpyName = NeedsCollectableMemCpy + ? "__builtin_objc_memmove_collectable" + : "__builtin_memcpy"; LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, Sema::LookupOrdinaryName); S.LookupName(R, S.TUScope, true); @@ -14177,11 +14092,10 @@ VK_PRValue, Loc, nullptr); assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); - Expr *CallArgs[] = { - To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) - }; - ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), - Loc, CallArgs, Loc); + Expr *CallArgs[] = {To, From, + IntegerLiteral::Create(S.Context, Size, SizeType, Loc)}; + ExprResult Call = + S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), Loc, CallArgs, Loc); assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); return Call.getAs(); @@ -14237,8 +14151,8 @@ CXXRecordDecl *ClassDecl = cast(RecordTy->getDecl()); // Look for operator=. - DeclarationName Name - = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); + DeclarationName Name = + S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); S.LookupQualifiedName(OpLookup, ClassDecl, false); @@ -14282,18 +14196,17 @@ // call mechanism. CXXScopeSpec SS; const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); - SS.MakeTrivial(S.Context, - NestedNameSpecifier::Create(S.Context, nullptr, false, - CanonicalT), - Loc); + SS.MakeTrivial( + S.Context, + NestedNameSpecifier::Create(S.Context, nullptr, false, CanonicalT), + Loc); // Create the reference to operator=. - ExprResult OpEqualRef - = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, + ExprResult OpEqualRef = + S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, SS, /*TemplateKWLoc=*/SourceLocation(), - /*FirstQualifierInScope=*/nullptr, - OpLookup, - /*TemplateArgs=*/nullptr, /*S*/nullptr, + /*FirstQualifierInScope=*/nullptr, OpLookup, + /*TemplateArgs=*/nullptr, /*S*/ nullptr, /*SuppressQualifierCheck=*/true); if (OpEqualRef.isInvalid()) return StmtError(); @@ -14301,9 +14214,8 @@ // Build the call to the assignment operator. Expr *FromInst = From.build(S, Loc); - ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, - OpEqualRef.getAs(), - Loc, FromInst, Loc); + ExprResult Call = S.BuildCallToMemberFunction( + /*Scope=*/nullptr, OpEqualRef.getAs(), Loc, FromInst, Loc); if (Call.isInvalid()) return StmtError(); @@ -14311,7 +14223,7 @@ // bail out. We'll replace the whole shebang with a memcpy. CXXMemberCallExpr *CE = dyn_cast(Call.get()); if (CE && CE->getMethodDecl()->isTrivial() && Depth) - return StmtResult((Stmt*)nullptr); + return StmtResult((Stmt *)nullptr); // Convert to an expression-statement, and clean up any produced // temporaries. @@ -14347,10 +14259,9 @@ OS << "__i" << Depth; IterationVarName = &S.Context.Idents.get(OS.str()); } - VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, - IterationVarName, SizeType, - S.Context.getTrivialTypeSourceInfo(SizeType, Loc), - SC_None); + VarDecl *IterationVar = VarDecl::Create( + S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, + S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); // Initialize the iteration variable to zero. llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); @@ -14361,7 +14272,8 @@ LvalueConvBuilder IterationVarRefRVal(IterationVarRef); // Create the DeclStmt that holds the iteration variable. - Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); + Stmt *InitStmt = + new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); // Subscript the "from" and "to" expressions with the iteration variable. SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); @@ -14375,17 +14287,16 @@ SubscriptBuilder ToIndex(To, IterationVarRefRVal); // Build the copy/move for an individual element of the array. - StmtResult Copy = - buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), - ToIndex, *FromIndex, CopyingBaseSubobject, - Copying, Depth + 1); + StmtResult Copy = buildSingleCopyAssignRecursively( + S, Loc, ArrayTy->getElementType(), ToIndex, *FromIndex, + CopyingBaseSubobject, Copying, Depth + 1); // Bail out if copying fails or if we determined that we should use memcpy. if (Copy.isInvalid() || !Copy.get()) return Copy; // Create the comparison against the array bound. - llvm::APInt Upper - = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); + llvm::APInt Upper = + ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); Expr *Comparison = BinaryOperator::Create( S.Context, IterationVarRefRVal.build(S, Loc), IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, @@ -14406,18 +14317,18 @@ S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); } -static StmtResult -buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, - const ExprBuilder &To, const ExprBuilder &From, - bool CopyingBaseSubobject, bool Copying) { +static StmtResult buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, + const ExprBuilder &To, + const ExprBuilder &From, + bool CopyingBaseSubobject, + bool Copying) { // Maybe we should use a memcpy? if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && T.isTriviallyCopyableType(S.Context)) return buildMemcpyForAssignmentOp(S, Loc, T, To, From); - StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, - CopyingBaseSubobject, - Copying, 0)); + StmtResult Result(buildSingleCopyAssignRecursively( + S, Loc, T, To, From, CopyingBaseSubobject, Copying, 0)); // If we ended up picking a trivial assignment operator for an array of a // non-trivially-copyable class type, just emit a memcpy. @@ -14451,8 +14362,7 @@ ArgType = Context.getLValueReferenceType(ArgType); bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, - CXXCopyAssignment, - Const); + CXXCopyAssignment, Const); // An implicitly-declared copy assignment operator is an inline public // member of its class. @@ -14479,17 +14389,16 @@ /* Diagnose */ false); // Add the parameter to the operator. - ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, - ClassLoc, ClassLoc, - /*Id=*/nullptr, ArgType, - /*TInfo=*/nullptr, SC_None, - nullptr); + ParmVarDecl *FromParam = + ParmVarDecl::Create(Context, CopyAssignment, ClassLoc, ClassLoc, + /*Id=*/nullptr, ArgType, + /*TInfo=*/nullptr, SC_None, nullptr); CopyAssignment->setParams(FromParam); CopyAssignment->setTrivial( - ClassDecl->needsOverloadResolutionForCopyAssignment() - ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) - : ClassDecl->hasTrivialCopyAssignment()); + ClassDecl->needsOverloadResolutionForCopyAssignment() + ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) + : ClassDecl->hasTrivialCopyAssignment()); // Note that we have added this copy-assignment operator. ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; @@ -14546,14 +14455,13 @@ bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); bool UDOIsDestructor = isa(UserDeclaredOperation); bool IsCopyAssignment = !isa(CopyOp); - unsigned DiagID = - (UDOIsUserProvided && UDOIsDestructor) - ? diag::warn_deprecated_copy_with_user_provided_dtor - : (UDOIsUserProvided && !UDOIsDestructor) - ? diag::warn_deprecated_copy_with_user_provided_copy - : (!UDOIsUserProvided && UDOIsDestructor) - ? diag::warn_deprecated_copy_with_dtor - : diag::warn_deprecated_copy; + unsigned DiagID = (UDOIsUserProvided && UDOIsDestructor) + ? diag::warn_deprecated_copy_with_user_provided_dtor + : (UDOIsUserProvided && !UDOIsDestructor) + ? diag::warn_deprecated_copy_with_user_provided_copy + : (!UDOIsUserProvided && UDOIsDestructor) + ? diag::warn_deprecated_copy_with_dtor + : diag::warn_deprecated_copy; S.Diag(UserDeclaredOperation->getLocation(), DiagID) << RD << IsCopyAssignment; } @@ -14580,8 +14488,9 @@ // The exception specification is needed because we are defining the // function. - ResolveExceptionSpec(CurrentLocation, - CopyAssignOperator->getType()->castAs()); + ResolveExceptionSpec( + CurrentLocation, + CopyAssignOperator->getType()->castAs()); // Add a context note for diagnostics produced after this point. Scope.addContextNote(CurrentLocation); @@ -14602,14 +14511,14 @@ // which they were declared in the class definition. // The statements that form the synthesized function body. - SmallVector Statements; + SmallVector Statements; // The parameter for the "other" object, which we are copying from. ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); Qualifiers OtherQuals = Other->getType().getQualifiers(); QualType OtherRefType = Other->getType(); - if (const LValueReferenceType *OtherRef - = OtherRefType->getAs()) { + if (const LValueReferenceType *OtherRef = + OtherRefType->getAs()) { OtherRefType = OtherRef->getPointeeType(); OtherQuals = OtherRefType.getQualifiers(); } @@ -14652,8 +14561,7 @@ VK_LValue, BasePath); // Build the copy. - StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, - To, From, + StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, To, From, /*CopyingBaseSubobject=*/true, /*Copying=*/true); if (Copy.isInvalid()) { @@ -14680,7 +14588,7 @@ // Check for members of reference type; we can't copy those. if (Field->getType()->isReferenceType()) { Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) - << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); + << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); Diag(Field->getLocation(), diag::note_declared_at); Invalid = true; continue; @@ -14690,7 +14598,7 @@ QualType BaseType = Context.getBaseElementType(Field->getType()); if (!BaseType->getAs() && BaseType.isConstQualified()) { Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) - << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); + << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); Diag(Field->getLocation(), diag::note_declared_at); Invalid = true; continue; @@ -14720,8 +14628,7 @@ MemberLookup); // Build the copy of this field. - StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, - To, From, + StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, To, From, /*CopyingBaseSubobject=*/false, /*Copying=*/true); if (Copy.isInvalid()) { @@ -14790,8 +14697,7 @@ ArgType = Context.getRValueReferenceType(ArgType); bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, - CXXMoveAssignment, - false); + CXXMoveAssignment, false); // An implicitly-declared move assignment operator is an inline public // member of its class. @@ -14818,17 +14724,16 @@ /* Diagnose */ false); // Add the parameter to the operator. - ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, - ClassLoc, ClassLoc, - /*Id=*/nullptr, ArgType, - /*TInfo=*/nullptr, SC_None, - nullptr); + ParmVarDecl *FromParam = + ParmVarDecl::Create(Context, MoveAssignment, ClassLoc, ClassLoc, + /*Id=*/nullptr, ArgType, + /*TInfo=*/nullptr, SC_None, nullptr); MoveAssignment->setParams(FromParam); MoveAssignment->setTrivial( - ClassDecl->needsOverloadResolutionForMoveAssignment() - ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) - : ClassDecl->hasTrivialMoveAssignment()); + ClassDecl->needsOverloadResolutionForMoveAssignment() + ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) + : ClassDecl->hasTrivialMoveAssignment()); // Note that we have added this copy-assignment operator. ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; @@ -14864,7 +14769,7 @@ return; llvm::SmallVector Worklist; - typedef llvm::DenseMap VBaseMap; + typedef llvm::DenseMap VBaseMap; VBaseMap VBases; for (auto &BI : Class->bases()) { @@ -14885,10 +14790,10 @@ // If we're not actually going to call a move assignment for this base, // or the selected move assignment is trivial, skip it. Sema::SpecialMemberOverloadResult SMOR = - S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, - /*ConstArg*/false, /*VolatileArg*/false, - /*RValueThis*/true, /*ConstThis*/false, - /*VolatileThis*/false); + S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, + /*ConstArg*/ false, /*VolatileArg*/ false, + /*RValueThis*/ true, /*ConstThis*/ false, + /*VolatileThis*/ false); if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || !SMOR.getMethod()->isMoveAssignmentOperator()) continue; @@ -14904,7 +14809,7 @@ .first->second; if (Existing && Existing != &BI) { S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) - << Class << Base; + << Class << Base; S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) << (Base->getCanonicalDecl() == Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) @@ -14964,14 +14869,15 @@ // The exception specification is needed because we are defining the // function. - ResolveExceptionSpec(CurrentLocation, - MoveAssignOperator->getType()->castAs()); + ResolveExceptionSpec( + CurrentLocation, + MoveAssignOperator->getType()->castAs()); // Add a context note for diagnostics produced after this point. Scope.addContextNote(CurrentLocation); // The statements that form the synthesized function body. - SmallVector Statements; + SmallVector Statements; // The parameter for the "other" object, which we are move from. ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); @@ -15027,8 +14933,7 @@ VK_LValue, BasePath); // Build the move. - StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, - To, From, + StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, To, From, /*CopyingBaseSubobject=*/true, /*Copying=*/false); if (Move.isInvalid()) { @@ -15055,7 +14960,7 @@ // Check for members of reference type; we can't move those. if (Field->getType()->isReferenceType()) { Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) - << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); + << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); Diag(Field->getLocation(), diag::note_declared_at); Invalid = true; continue; @@ -15065,7 +14970,7 @@ QualType BaseType = Context.getBaseElementType(Field->getType()); if (!BaseType->getAs() && BaseType.isConstQualified()) { Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) - << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); + << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); Diag(Field->getLocation(), diag::note_declared_at); Invalid = true; continue; @@ -15092,13 +14997,13 @@ MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); - assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue + assert( + !From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue "Member reference with rvalue base must be rvalue except for reference " "members, which aren't allowed for move assignment."); // Build the move of this field. - StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, - To, From, + StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, To, From, /*CopyingBaseSubobject=*/false, /*Copying=*/false); if (Move.isInvalid()) { @@ -15142,8 +15047,8 @@ } } -CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( - CXXRecordDecl *ClassDecl) { +CXXConstructorDecl * +Sema::DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl) { // C++ [class.copy]p4: // If the class definition does not explicitly declare a copy // constructor, one is declared implicitly. @@ -15167,12 +15072,10 @@ ArgType = Context.getLValueReferenceType(ArgType); bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, - CXXCopyConstructor, - Const); + CXXCopyConstructor, Const); - DeclarationName Name - = Context.DeclarationNames.getCXXConstructorName( - Context.getCanonicalType(ClassType)); + DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( + Context.getCanonicalType(ClassType)); SourceLocation ClassLoc = ClassDecl->getLocation(); DeclarationNameInfo NameInfo(Name, ClassLoc); @@ -15219,7 +15122,7 @@ ClassDecl->hasAttr() || (ClassDecl->needsOverloadResolutionForCopyConstructor() ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, - TAH_ConsiderTrivialABI) + TAH_ConsiderTrivialABI) : ClassDecl->hasTrivialCopyConstructorForCall())); // Note that we have declared this constructor. @@ -15273,7 +15176,7 @@ if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { CopyConstructor->setInvalidDecl(); - } else { + } else { SourceLocation Loc = CopyConstructor->getEndLoc().isValid() ? CopyConstructor->getEndLoc() : CopyConstructor->getLocation(); @@ -15289,8 +15192,8 @@ } } -CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( - CXXRecordDecl *ClassDecl) { +CXXConstructorDecl * +Sema::DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl) { assert(ClassDecl->needsImplicitMoveConstructor()); DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); @@ -15307,12 +15210,10 @@ ArgType = Context.getRValueReferenceType(ArgType); bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, - CXXMoveConstructor, - false); + CXXMoveConstructor, false); - DeclarationName Name - = Context.DeclarationNames.getCXXConstructorName( - Context.getCanonicalType(ClassType)); + DeclarationName Name = Context.DeclarationNames.getCXXConstructorName( + Context.getCanonicalType(ClassType)); SourceLocation ClassLoc = ClassDecl->getLocation(); DeclarationNameInfo NameInfo(Name, ClassLoc); @@ -15338,11 +15239,9 @@ /* Diagnose */ false); // Add the parameter to the constructor. - ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, - ClassLoc, ClassLoc, - /*IdentifierInfo=*/nullptr, - ArgType, /*TInfo=*/nullptr, - SC_None, nullptr); + ParmVarDecl *FromParam = ParmVarDecl::Create( + Context, MoveConstructor, ClassLoc, ClassLoc, + /*IdentifierInfo=*/nullptr, ArgType, /*TInfo=*/nullptr, SC_None, nullptr); MoveConstructor->setParams(FromParam); MoveConstructor->setTrivial( @@ -15422,8 +15321,7 @@ } void Sema::DefineImplicitLambdaToFunctionPointerConversion( - SourceLocation CurrentLocation, - CXXConversionDecl *Conv) { + SourceLocation CurrentLocation, CXXConversionDecl *Conv) { SynthesizedFunctionScope Scope(*this, Conv); assert(!Conv->getReturnType()->isUndeducedType()); @@ -15496,11 +15394,10 @@ // Copy-initialize the lambda object as needed to capture it. Expr *This = ActOnCXXThis(CurrentLocation).get(); - Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); + Expr *DerefThis = CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); - ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, - Conv->getLocation(), - Conv, DerefThis); + ExprResult BuildBlock = BuildBlockForLambdaConversion( + CurrentLocation, Conv->getLocation(), Conv, DerefThis); // If we're not under ARC, make sure we still get the _Block_copy/autorelease // behavior. Note that only the general conversion function does this @@ -15557,17 +15454,12 @@ return false; } -ExprResult -Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, - NamedDecl *FoundDecl, - CXXConstructorDecl *Constructor, - MultiExprArg ExprArgs, - bool HadMultipleCandidates, - bool IsListInitialization, - bool IsStdInitListInitialization, - bool RequiresZeroInit, - unsigned ConstructKind, - SourceRange ParenRange) { +ExprResult Sema::BuildCXXConstructExpr( + SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, + CXXConstructorDecl *Constructor, MultiExprArg ExprArgs, + bool HadMultipleCandidates, bool IsListInitialization, + bool IsStdInitListInitialization, bool RequiresZeroInit, + unsigned ConstructKind, SourceRange ParenRange) { bool Elidable = false; // C++0x [class.copy]p34: @@ -15596,26 +15488,18 @@ Context, cast(FoundDecl->getDeclContext())); } - return BuildCXXConstructExpr(ConstructLoc, DeclInitType, - FoundDecl, Constructor, - Elidable, ExprArgs, HadMultipleCandidates, - IsListInitialization, - IsStdInitListInitialization, RequiresZeroInit, - ConstructKind, ParenRange); -} - -ExprResult -Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, - NamedDecl *FoundDecl, - CXXConstructorDecl *Constructor, - bool Elidable, - MultiExprArg ExprArgs, - bool HadMultipleCandidates, - bool IsListInitialization, - bool IsStdInitListInitialization, - bool RequiresZeroInit, - unsigned ConstructKind, - SourceRange ParenRange) { + return BuildCXXConstructExpr( + ConstructLoc, DeclInitType, FoundDecl, Constructor, Elidable, ExprArgs, + HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, + RequiresZeroInit, ConstructKind, ParenRange); +} + +ExprResult Sema::BuildCXXConstructExpr( + SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, + CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs, + bool HadMultipleCandidates, bool IsListInitialization, + bool IsStdInitListInitialization, bool RequiresZeroInit, + unsigned ConstructKind, SourceRange ParenRange) { if (auto *Shadow = dyn_cast(FoundDecl)) { Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); // The only way to get here is if we did overlaod resolution to find the @@ -15633,17 +15517,12 @@ /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. -ExprResult -Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, - CXXConstructorDecl *Constructor, - bool Elidable, - MultiExprArg ExprArgs, - bool HadMultipleCandidates, - bool IsListInitialization, - bool IsStdInitListInitialization, - bool RequiresZeroInit, - unsigned ConstructKind, - SourceRange ParenRange) { +ExprResult Sema::BuildCXXConstructExpr( + SourceLocation ConstructLoc, QualType DeclInitType, + CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs, + bool HadMultipleCandidates, bool IsListInitialization, + bool IsStdInitListInitialization, bool RequiresZeroInit, + unsigned ConstructKind, SourceRange ParenRange) { assert(declaresSameEntity( Constructor->getParent(), DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && @@ -15666,16 +15545,20 @@ } void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { - if (VD->isInvalidDecl()) return; + if (VD->isInvalidDecl()) + return; // If initializing the variable failed, don't also diagnose problems with // the destructor, they're likely related. if (VD->getInit() && VD->getInit()->containsErrors()) return; CXXRecordDecl *ClassDecl = cast(Record->getDecl()); - if (ClassDecl->isInvalidDecl()) return; - if (ClassDecl->hasIrrelevantDestructor()) return; - if (ClassDecl->isDependentContext()) return; + if (ClassDecl->isInvalidDecl()) + return; + if (ClassDecl->hasIrrelevantDestructor()) + return; + if (ClassDecl->isDependentContext()) + return; if (VD->isNoDestroy(getASTContext())) return; @@ -15693,7 +15576,8 @@ DiagnoseUseOfDecl(Destructor, VD->getLocation()); } - if (Destructor->isTrivial()) return; + if (Destructor->isTrivial()) + return; // If the destructor is constexpr, check whether the variable has constant // destruction now. @@ -15705,13 +15589,15 @@ if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && HasConstantInit) { Diag(VD->getLocation(), - diag::err_constexpr_var_requires_const_destruction) << VD; + diag::err_constexpr_var_requires_const_destruction) + << VD; for (unsigned I = 0, N = Notes.size(); I != N; ++I) Diag(Notes[I].first, Notes[I].second); } } - if (!VD->hasGlobalStorage()) return; + if (!VD->hasGlobalStorage()) + return; // Emit warning for non-trivial dtor in global scope (a real global, // class-static, function-static). @@ -15747,7 +15633,7 @@ ConvertedArgs.reserve(NumArgs); VariadicCallType CallType = - Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; + Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; SmallVector AllArgs; bool Invalid = GatherArgumentsForCall( Loc, Constructor, Proto, 0, llvm::ArrayRef(Args, NumArgs), AllArgs, @@ -15770,14 +15656,13 @@ if (isa(DC)) { return SemaRef.Diag(FnDecl->getLocation(), diag::err_operator_new_delete_declared_in_namespace) - << FnDecl->getDeclName(); + << FnDecl->getDeclName(); } - if (isa(DC) && - FnDecl->getStorageClass() == SC_Static) { + if (isa(DC) && FnDecl->getStorageClass() == SC_Static) { return SemaRef.Diag(FnDecl->getLocation(), diag::err_operator_new_delete_declared_static) - << FnDecl->getDeclName(); + << FnDecl->getDeclName(); } return false; @@ -15792,12 +15677,10 @@ PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); } -static inline bool -CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, - CanQualType ExpectedResultType, - CanQualType ExpectedFirstParamType, - unsigned DependentParamTypeDiag, - unsigned InvalidParamTypeDiag) { +static inline bool CheckOperatorNewDeleteTypes( + Sema &SemaRef, const FunctionDecl *FnDecl, CanQualType ExpectedResultType, + CanQualType ExpectedFirstParamType, unsigned DependentParamTypeDiag, + unsigned InvalidParamTypeDiag) { QualType ResultType = FnDecl->getType()->castAs()->getReturnType(); @@ -15825,15 +15708,16 @@ // A function template must have at least 2 parameters. if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) - return SemaRef.Diag(FnDecl->getLocation(), - diag::err_operator_new_delete_template_too_few_parameters) - << FnDecl->getDeclName(); + return SemaRef.Diag( + FnDecl->getLocation(), + diag::err_operator_new_delete_template_too_few_parameters) + << FnDecl->getDeclName(); // The function decl must have at least 1 parameter. if (FnDecl->getNumParams() == 0) return SemaRef.Diag(FnDecl->getLocation(), diag::err_operator_new_delete_too_few_parameters) - << FnDecl->getDeclName(); + << FnDecl->getDeclName(); QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); if (SemaRef.getLangOpts().OpenCLCPlusPlus) { @@ -15863,8 +15747,8 @@ return false; } -static bool -CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { +static bool CheckOperatorNewDeclaration(Sema &SemaRef, + const FunctionDecl *FnDecl) { // C++ [basic.stc.dynamic.allocation]p1: // A program is ill-formed if an allocation function is declared in a // namespace scope other than global scope or declared static in global @@ -15873,7 +15757,7 @@ return true; CanQualType SizeTy = - SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); + SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); // C++ [basic.stc.dynamic.allocation]p1: // The return type shall be void*. The first parameter shall have type @@ -15889,13 +15773,14 @@ if (FnDecl->getParamDecl(0)->hasDefaultArg()) return SemaRef.Diag(FnDecl->getLocation(), diag::err_operator_new_default_arg) - << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); + << FnDecl->getDeclName() + << FnDecl->getParamDecl(0)->getDefaultArgRange(); return false; } -static bool -CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { +static bool CheckOperatorDeleteDeclaration(Sema &SemaRef, + FunctionDecl *FnDecl) { // C++ [basic.stc.dynamic.deallocation]p1: // A program is ill-formed if deallocation functions are declared in a // namespace scope other than global scope or declared static in global @@ -15990,7 +15875,7 @@ if (!ClassOrEnumParam) return Diag(FnDecl->getLocation(), diag::err_operator_overload_needs_class_or_enum) - << FnDecl->getDeclName(); + << FnDecl->getDeclName(); } // C++ [over.oper]p8: @@ -16024,9 +15909,9 @@ } static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { - { false, false, false } -#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ - , { Unary, Binary, MemberOnly } + {false, false, false} +#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ + , { Unary, Binary, MemberOnly } #include "clang/Basic/OperatorKinds.def" }; @@ -16038,8 +15923,8 @@ // [...] Operator functions cannot have more or fewer parameters // than the number required for the corresponding operator, as // described in the rest of this subclause. - unsigned NumParams = FnDecl->getNumParams() - + (isa(FnDecl)? 1 : 0); + unsigned NumParams = + FnDecl->getNumParams() + (isa(FnDecl) ? 1 : 0); if (Op != OO_Call && Op != OO_Subscript && ((NumParams == 1 && !CanBeUnaryOperator) || (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) || @@ -16047,16 +15932,16 @@ // We have the wrong number of parameters. unsigned ErrorKind; if (CanBeUnaryOperator && CanBeBinaryOperator) { - ErrorKind = 2; // 2 -> unary or binary. + ErrorKind = 2; // 2 -> unary or binary. } else if (CanBeUnaryOperator) { - ErrorKind = 0; // 0 -> unary + ErrorKind = 0; // 0 -> unary } else { assert(CanBeBinaryOperator && "All non-call overloaded operators are unary or binary!"); - ErrorKind = 1; // 1 -> binary + ErrorKind = 1; // 1 -> binary } return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) - << FnDecl->getDeclName() << NumParams << ErrorKind; + << FnDecl->getDeclName() << NumParams << ErrorKind; } if (Op == OO_Subscript && NumParams != 2) { @@ -16078,7 +15963,7 @@ if (MustBeMemberOperator && !isa(FnDecl)) { return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be_member) - << FnDecl->getDeclName(); + << FnDecl->getDeclName(); } // C++ [over.inc]p1: @@ -16099,7 +15984,7 @@ !ParamType->isDependentType()) return Diag(LastParam->getLocation(), diag::err_operator_overload_post_incdec_must_be_int) - << LastParam->getType() << (Op == OO_MinusMinus); + << LastParam->getType() << (Op == OO_MinusMinus); } return false; @@ -16166,7 +16051,7 @@ bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { if (isa(FnDecl)) { Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) - << FnDecl->getDeclName(); + << FnDecl->getDeclName(); return true; } @@ -16311,20 +16196,20 @@ if (Param->hasDefaultArg()) { Diag(Param->getDefaultArgRange().getBegin(), diag::err_literal_operator_default_argument) - << Param->getDefaultArgRange(); + << Param->getDefaultArgRange(); break; } } - StringRef LiteralName - = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); + StringRef LiteralName = + FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); if (LiteralName[0] != '_' && !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { // C++11 [usrlit.suffix]p1: // Literal suffix identifiers that do not start with an underscore // are reserved for future standardization. Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) - << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); + << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); } return false; @@ -16342,7 +16227,7 @@ StringLiteral *Lit = cast(LangStr); if (!Lit->isOrdinary()) { Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) - << LangStr->getSourceRange(); + << LangStr->getSourceRange(); return nullptr; } @@ -16354,7 +16239,7 @@ Language = LinkageSpecDecl::lang_cxx; else { Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) - << LangStr->getSourceRange(); + << LangStr->getSourceRange(); return nullptr; } @@ -16388,11 +16273,10 @@ /// the C++ linkage specification LinkageSpec. If RBraceLoc is /// valid, it's the position of the closing '}' brace in a linkage /// specification that uses braces. -Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, - Decl *LinkageSpec, +Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc) { if (RBraceLoc.isValid()) { - LinkageSpecDecl* LSDecl = cast(LinkageSpec); + LinkageSpecDecl *LSDecl = cast(LinkageSpec); LSDecl->setRBraceLoc(RBraceLoc); } @@ -16423,8 +16307,7 @@ /// Perform semantic analysis for the variable declaration that /// occurs within a C++ catch clause, returning the newly-created /// variable. -VarDecl *Sema::BuildExceptionDeclaration(Scope *S, - TypeSourceInfo *TInfo, +VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation Loc, IdentifierInfo *Name) { @@ -16474,8 +16357,7 @@ } if (!Invalid && !ExDeclType->isDependentType() && - RequireNonAbstractType(Loc, ExDeclType, - diag::err_abstract_type_in_decl, + RequireNonAbstractType(Loc, ExDeclType, diag::err_abstract_type_in_decl, AbstractVariableType)) Invalid = true; @@ -16521,15 +16403,15 @@ // it can be destroyed later. QualType initType = Context.getExceptionObjectType(ExDeclType); - InitializedEntity entity = - InitializedEntity::InitializeVariable(ExDecl); + InitializedEntity entity = InitializedEntity::InitializeVariable(ExDecl); InitializationKind initKind = - InitializationKind::CreateCopy(Loc, SourceLocation()); + InitializationKind::CreateCopy(Loc, SourceLocation()); Expr *opaqueValue = - new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); + new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); InitializationSequence sequence(*this, entity, initKind, opaqueValue); - ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); + ExprResult result = + sequence.Perform(*this, entity, initKind, opaqueValue); if (result.isInvalid()) Invalid = true; else { @@ -16562,22 +16444,21 @@ // Check for unexpanded parameter packs. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, UPPC_ExceptionType)) { - TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, - D.getIdentifierLoc()); + TInfo = + Context.getTrivialTypeSourceInfo(Context.IntTy, D.getIdentifierLoc()); Invalid = true; } IdentifierInfo *II = D.getIdentifier(); - if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), - LookupOrdinaryName, - ForVisibleRedeclaration)) { + if (NamedDecl *PrevDecl = + LookupSingleName(S, II, D.getIdentifierLoc(), LookupOrdinaryName, + ForVisibleRedeclaration)) { // The scope should be freshly made just for us. There is just no way // it contains any previous declaration, except for function parameters in // a function-try-block's catch statement. assert(!S->isDeclScope(PrevDecl)); if (isDeclInScope(PrevDecl, CurContext, S)) { - Diag(D.getIdentifierLoc(), diag::err_redefinition) - << D.getIdentifier(); + Diag(D.getIdentifierLoc(), diag::err_redefinition) << D.getIdentifier(); Diag(PrevDecl->getLocation(), diag::note_previous_definition); Invalid = true; } else if (PrevDecl->isTemplateParameter()) @@ -16587,7 +16468,7 @@ if (D.getCXXScopeSpec().isSet() && !Invalid) { Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) - << D.getCXXScopeSpec().getRange(); + << D.getCXXScopeSpec().getRange(); Invalid = true; } @@ -16715,7 +16596,8 @@ /// Try to print more useful information about a failed static_assert /// with expression \E void Sema::DiagnoseStaticAssertDetails(const Expr *E) { - if (const auto *Op = dyn_cast(E)) { + if (const auto *Op = dyn_cast(E); + Op && Op->getOpcode() != BO_LOr) { const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts(); const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts(); @@ -16785,10 +16667,11 @@ FoldKind = AllowFold; } - if (!Failed && VerifyIntegerConstantExpression( - BaseExpr, &Cond, - diag::err_static_assert_expression_is_not_constant, - FoldKind).isInvalid()) + if (!Failed && + VerifyIntegerConstantExpression( + BaseExpr, &Cond, diag::err_static_assert_expression_is_not_constant, + FoldKind) + .isInvalid()) Failed = true; // CWG2518 @@ -16812,20 +16695,20 @@ Expr *InnerCond = nullptr; std::string InnerCondDescription; std::tie(InnerCond, InnerCondDescription) = - findFailedBooleanCondition(Converted.get()); + findFailedBooleanCondition(Converted.get()); if (InnerCond && isa(InnerCond)) { // Drill down into concept specialization expressions to see why they // weren't satisfied. Diag(StaticAssertLoc, diag::err_static_assert_failed) - << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); + << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); ConstraintSatisfaction Satisfaction; if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) DiagnoseUnsatisfiedConstraint(Satisfaction); - } else if (InnerCond && !isa(InnerCond) - && !isa(InnerCond)) { + } else if (InnerCond && !isa(InnerCond) && + !isa(InnerCond)) { Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) - << InnerCondDescription << !AssertMessage - << Msg.str() << InnerCond->getSourceRange(); + << InnerCondDescription << !AssertMessage << Msg.str() + << InnerCond->getSourceRange(); DiagnoseStaticAssertDetails(InnerCond); } else { Diag(StaticAssertLoc, diag::err_static_assert_failed) @@ -16836,17 +16719,17 @@ } } else { ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, - /*DiscardedValue*/false, - /*IsConstexpr*/true); + /*DiscardedValue*/ false, + /*IsConstexpr*/ true); if (FullAssertExpr.isInvalid()) Failed = true; else AssertExpr = FullAssertExpr.get(); } - Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, - AssertExpr, AssertMessage, RParenLoc, - Failed); + Decl *Decl = + StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, AssertExpr, + AssertMessage, RParenLoc, Failed); CurContext->addDecl(Decl); return Decl; @@ -16883,28 +16766,23 @@ InsertionText += RD->getKindName(); Diag(TypeRange.getBegin(), - getLangOpts().CPlusPlus11 ? - diag::warn_cxx98_compat_unelaborated_friend_type : - diag::ext_unelaborated_friend_type) - << (unsigned) RD->getTagKind() - << T - << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), - InsertionText); + getLangOpts().CPlusPlus11 + ? diag::warn_cxx98_compat_unelaborated_friend_type + : diag::ext_unelaborated_friend_type) + << (unsigned)RD->getTagKind() << T + << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), + InsertionText); } else { - Diag(FriendLoc, - getLangOpts().CPlusPlus11 ? - diag::warn_cxx98_compat_nonclass_type_friend : - diag::ext_nonclass_type_friend) - << T - << TypeRange; + Diag(FriendLoc, getLangOpts().CPlusPlus11 + ? diag::warn_cxx98_compat_nonclass_type_friend + : diag::ext_nonclass_type_friend) + << T << TypeRange; } } else if (T->getAs()) { - Diag(FriendLoc, - getLangOpts().CPlusPlus11 ? - diag::warn_cxx98_compat_enum_friend : - diag::ext_enum_friend) - << T - << TypeRange; + Diag(FriendLoc, getLangOpts().CPlusPlus11 + ? diag::warn_cxx98_compat_enum_friend + : diag::ext_enum_friend) + << T << TypeRange; } // C++11 [class.friend]p3: @@ -16949,19 +16827,21 @@ NameLoc, Attr, TemplateParams, AS_public, /*ModulePrivateLoc=*/SourceLocation(), FriendLoc, TempParamLists.size() - 1, - TempParamLists.data()).get(); + TempParamLists.data()) + .get(); } else { // The "template<>" header is extraneous. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) - << TypeWithKeyword::getTagTypeKindName(Kind) << Name; + << TypeWithKeyword::getTagTypeKindName(Kind) << Name; IsMemberSpecialization = true; } } - if (Invalid) return true; + if (Invalid) + return true; bool isAllExplicitSpecializations = true; - for (unsigned I = TempParamLists.size(); I-- > 0; ) { + for (unsigned I = TempParamLists.size(); I-- > 0;) { if (TempParamLists[I]->size()) { isAllExplicitSpecializations = false; break; @@ -16989,10 +16869,10 @@ } NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); - ElaboratedTypeKeyword Keyword - = TypeWithKeyword::getKeywordForTagTypeKind(Kind); - QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, - *Name, NameLoc); + ElaboratedTypeKeyword Keyword = + TypeWithKeyword::getKeywordForTagTypeKind(Kind); + QualType T = + CheckTypenameType(Keyword, TagLoc, QualifierLoc, *Name, NameLoc); if (T.isNull()) return true; @@ -17010,8 +16890,8 @@ TL.getNamedTypeLoc().castAs().setNameLoc(NameLoc); } - FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, - TSI, FriendLoc, TempParamLists); + FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, TSI, + FriendLoc, TempParamLists); Friend->setAccess(AS_public); CurContext->addDecl(Friend); return Friend; @@ -17019,13 +16899,11 @@ assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); - - // Handle the case of a templated-scope friend class. e.g. // template class A::B; // FIXME: we don't support these right now. Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) - << SS.getScopeRep() << SS.getRange() << cast(CurContext); + << SS.getScopeRep() << SS.getRange() << cast(CurContext); ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); @@ -17034,8 +16912,8 @@ TL.setQualifierLoc(SS.getWithLocInContext(Context)); TL.setNameLoc(NameLoc); - FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, - TSI, FriendLoc, TempParamLists); + FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, TSI, + FriendLoc, TempParamLists); Friend->setAccess(AS_public); Friend->setUnsupportedFriend(true); CurContext->addDecl(Friend); @@ -17086,7 +16964,8 @@ if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) - Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; + Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) + << "__unaligned"; } // Try to convert the decl specifier to a type. This works for @@ -17117,8 +16996,7 @@ // FIXME: handle "template <> friend class A;", which // is possibly well-formed? Who even knows? if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { - Diag(Loc, diag::err_tagless_friend_type_template) - << DS.getSourceRange(); + Diag(Loc, diag::err_tagless_friend_type_template) << DS.getSourceRange(); return nullptr; } @@ -17135,9 +17013,7 @@ Decl *D; if (!TempParams.empty()) - D = FriendTemplateDecl::Create(Context, CurContext, Loc, - TempParams, - TSI, + D = FriendTemplateDecl::Create(Context, CurContext, Loc, TempParams, TSI, DS.getFriendSpecLoc()); else D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); @@ -17151,8 +17027,9 @@ return D; } -NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, - MultiTemplateParamsArg TemplateParams) { +NamedDecl * +Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, + MultiTemplateParamsArg TemplateParams) { const DeclSpec &DS = D.getDeclSpec(); assert(DS.isFriendSpecified()); @@ -17234,7 +17111,7 @@ // Look up the function name in the scope. Previous.clear(LookupLocalFriendName); - LookupName(Previous, S, /*AllowBuiltinCreation*/false); + LookupName(Previous, S, /*AllowBuiltinCreation*/ false); if (!Previous.empty()) { // All possible previous declarations must have the same context: @@ -17256,9 +17133,9 @@ Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); } - // - There's no scope specifier, in which case we just go to the - // appropriate scope and look for a function or function template - // there as appropriate. + // - There's no scope specifier, in which case we just go to the + // appropriate scope and look for a function or function template + // there as appropriate. } else if (SS.isInvalid() || !SS.isSet()) { // C++11 [namespace.memdef]p3: // If the name in a friend declaration is neither qualified nor @@ -17292,33 +17169,36 @@ } if (isTemplateId) { - if (isa(LookupDC)) break; + if (isa(LookupDC)) + break; } else { - if (LookupDC->isFileContext()) break; + if (LookupDC->isFileContext()) + break; } LookupDC = LookupDC->getParent(); } DCScope = getScopeForDeclContext(S, DC); - // - There's a non-dependent scope specifier, in which case we - // compute it and do a previous lookup there for a function - // or function template. + // - There's a non-dependent scope specifier, in which case we + // compute it and do a previous lookup there for a function + // or function template. } else if (!SS.getScopeRep()->isDependent()) { DC = computeDeclContext(SS); - if (!DC) return nullptr; + if (!DC) + return nullptr; - if (RequireCompleteDeclContext(SS, DC)) return nullptr; + if (RequireCompleteDeclContext(SS, DC)) + return nullptr; LookupQualifiedName(Previous, DC); // C++ [class.friend]p1: A friend of a class is a function or // class that is not a member of the class . . . if (DC->Equals(CurContext)) - Diag(DS.getFriendSpecLoc(), - getLangOpts().CPlusPlus11 ? - diag::warn_cxx98_compat_friend_is_member : - diag::err_friend_is_member); + Diag(DS.getFriendSpecLoc(), getLangOpts().CPlusPlus11 + ? diag::warn_cxx98_compat_friend_is_member + : diag::err_friend_is_member); if (D.isFunctionDefinition()) { // C++ [class.friend]p6: @@ -17329,8 +17209,8 @@ // FIXME: We should only do this if the scope specifier names the // innermost enclosing namespace; otherwise the fixit changes the // meaning of the code. - SemaDiagnosticBuilder DB - = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); + SemaDiagnosticBuilder DB = + Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); DB << SS.getScopeRep(); if (DC->isFileContext()) @@ -17338,11 +17218,11 @@ SS.clear(); } - // - There's a scope specifier that does not match any template - // parameter lists, in which case we use some arbitrary context, - // create a method or method template, and wait for instantiation. - // - There's a scope specifier that does match some template - // parameter lists, which we don't handle right now. + // - There's a scope specifier that does not match any template + // parameter lists, in which case we use some arbitrary context, + // create a method or method template, and wait for instantiation. + // - There's a scope specifier that does match some template + // parameter lists, which we don't handle right now. } else { if (D.isFunctionDefinition()) { // C++ [class.friend]p6: @@ -17350,7 +17230,7 @@ // only if the class is a non-local class (9.8), the function name is // unqualified, and the function has namespace scope. Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) - << SS.getScopeRep(); + << SS.getScopeRep(); } DC = CurContext; @@ -17399,7 +17279,8 @@ bool AddToScope = true; NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, TemplateParams, AddToScope); - if (!ND) return nullptr; + if (!ND) + return nullptr; assert(ND->getLexicalDeclContext() == CurContext); @@ -17417,19 +17298,19 @@ DC = DC->getRedeclContext(); DC->makeDeclVisibleInContext(ND); if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) - PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); + PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/false); } - FriendDecl *FrD = FriendDecl::Create(Context, CurContext, - D.getIdentifierLoc(), ND, - DS.getFriendSpecLoc()); + FriendDecl *FrD = FriendDecl::Create( + Context, CurContext, D.getIdentifierLoc(), ND, DS.getFriendSpecLoc()); FrD->setAccess(AS_public); CurContext->addDecl(FrD); if (ND->isInvalidDecl()) { FrD->setInvalidDecl(); } else { - if (DC->isRecord()) CheckFriendAccess(ND); + if (DC->isRecord()) + CheckFriendAccess(ND); FunctionDecl *FD; if (FunctionTemplateDecl *FTD = dyn_cast(ND)) @@ -17456,8 +17337,8 @@ // Mark templated-scope function declarations as unsupported. if (FD->getNumTemplateParameterLists() && SS.isValid()) { Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) - << SS.getScopeRep() << SS.getRange() - << cast(CurContext); + << SS.getScopeRep() << SS.getRange() + << cast(CurContext); FrD->setUnsupportedFriend(true); } } @@ -17685,9 +17566,8 @@ if (New->getStorageClass() == SC_Static) return false; - Diag(New->getLocation(), - diag::err_conflicting_overriding_cc_attributes) - << New->getDeclName() << New->getType() << Old->getType(); + Diag(New->getLocation(), diag::err_conflicting_overriding_cc_attributes) + << New->getDeclName() << New->getType() << Old->getType(); Diag(Old->getLocation(), diag::note_overridden_virtual_function); return true; } @@ -17697,8 +17577,8 @@ QualType NewTy = New->getType()->castAs()->getReturnType(); QualType OldTy = Old->getType()->castAs()->getReturnType(); - if (Context.hasSameType(NewTy, OldTy) || - NewTy->isDependentType() || OldTy->isDependentType()) + if (Context.hasSameType(NewTy, OldTy) || NewTy->isDependentType() || + OldTy->isDependentType()) return false; // Check if the return types are covariant @@ -17783,7 +17663,6 @@ return true; } - // The new class type must have the same or less qualifiers as the old type. if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { Diag(New->getLocation(), @@ -17815,7 +17694,7 @@ if (!Method->isInvalidDecl()) Diag(Method->getLocation(), diag::err_non_virtual_pure) - << Method->getDeclName() << InitRange; + << Method->getDeclName() << InitRange; return true; } @@ -17894,7 +17773,7 @@ if (isa(Dcl)) { // The declarator shall not specify a function. Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) - << D.getSourceRange(); + << D.getSourceRange(); return true; } @@ -17909,8 +17788,8 @@ ExternalSource->ReadUsedVTables(VTables); SmallVector NewUses; for (unsigned I = 0, N = VTables.size(); I != N; ++I) { - llvm::DenseMap::iterator Pos - = VTablesUsed.find(VTables[I].Record); + llvm::DenseMap::iterator Pos = + VTablesUsed.find(VTables[I].Record); // Even if a definition wasn't required before, it may be required now. if (Pos != VTablesUsed.end()) { if (!Pos->second && VTables[I].DefinitionRequired) @@ -17945,8 +17824,8 @@ // Try to insert this class into the map. LoadExternalVTableUses(); Class = Class->getCanonicalDecl(); - std::pair::iterator, bool> - Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); + std::pair::iterator, bool> Pos = + VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); if (!Pos.second) { // If we already had an entry, check to see if we are promoting this vtable // to require a definition. If so, we need to reappend to the VTableUses @@ -18029,8 +17908,8 @@ bool IsExplicitInstantiationDeclaration = ClassTSK == TSK_ExplicitInstantiationDeclaration; for (auto *R : Class->redecls()) { - TemplateSpecializationKind TSK - = cast(R)->getTemplateSpecializationKind(); + TemplateSpecializationKind TSK = + cast(R)->getTemplateSpecializationKind(); if (TSK == TSK_ExplicitInstantiationDeclaration) IsExplicitInstantiationDeclaration = true; else if (TSK == TSK_ExplicitInstantiationDefinition) { @@ -18067,8 +17946,8 @@ Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && ClassTSK != TSK_ExplicitInstantiationDefinition) { const FunctionDecl *KeyFunctionDef = nullptr; - if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && - KeyFunctionDef->isInlined())) + if (!KeyFunction || + (KeyFunction->hasBody(KeyFunctionDef) && KeyFunctionDef->isInlined())) Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; } } @@ -18125,11 +18004,11 @@ if (!getLangOpts().CPlusPlus) return; if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { - SmallVector ivars; + SmallVector ivars; CollectIvarsToConstructOrDestruct(OID, ivars); if (ivars.empty()) return; - SmallVector AllToInit; + SmallVector AllToInit; for (unsigned i = 0; i < ivars.size(); i++) { FieldDecl *Field = ivars[i]; if (Field->isInvalidDecl()) @@ -18138,7 +18017,7 @@ CXXCtorInitializer *Member; InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); InitializationKind InitKind = - InitializationKind::CreateDefault(ObjCImplementation->getLocation()); + InitializationKind::CreateDefault(ObjCImplementation->getLocation()); InitializationSequence InitSeq(*this, InitEntity, InitKind, std::nullopt); ExprResult MemberInit = @@ -18149,11 +18028,9 @@ if (!MemberInit.get() || MemberInit.isInvalid()) continue; - Member = - new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), - SourceLocation(), - MemberInit.getAs(), - SourceLocation()); + Member = new (Context) + CXXCtorInitializer(Context, Field, SourceLocation(), SourceLocation(), + MemberInit.getAs(), SourceLocation()); AllToInit.push_back(Member); // Be sure that the destructor is accessible and is marked as referenced. @@ -18163,23 +18040,22 @@ CXXRecordDecl *RD = cast(RecordTy->getDecl()); if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { MarkFunctionReferenced(Field->getLocation(), Destructor); - CheckDestructorAccess(Field->getLocation(), Destructor, - PDiag(diag::err_access_dtor_ivar) - << Context.getBaseElementType(Field->getType())); + CheckDestructorAccess( + Field->getLocation(), Destructor, + PDiag(diag::err_access_dtor_ivar) + << Context.getBaseElementType(Field->getType())); } } } - ObjCImplementation->setIvarInitializers(Context, - AllToInit.data(), AllToInit.size()); + ObjCImplementation->setIvarInitializers(Context, AllToInit.data(), + AllToInit.size()); } } -static -void DelegatingCycleHelper(CXXConstructorDecl* Ctor, - llvm::SmallPtrSet &Valid, - llvm::SmallPtrSet &Invalid, - llvm::SmallPtrSet &Current, - Sema &S) { +static void DelegatingCycleHelper( + CXXConstructorDecl *Ctor, llvm::SmallPtrSet &Valid, + llvm::SmallPtrSet &Invalid, + llvm::SmallPtrSet &Current, Sema &S) { if (Ctor->isInvalidDecl()) return; @@ -18190,13 +18066,13 @@ if (Target) { const FunctionDecl *FNTarget = nullptr; (void)Target->hasBody(FNTarget); - Target = const_cast( - cast_or_null(FNTarget)); + Target = const_cast( + cast_or_null(FNTarget)); } CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), // Avoid dereferencing a null pointer here. - *TCanonical = Target? Target->getCanonicalDecl() : nullptr; + *TCanonical = Target ? Target->getCanonicalDecl() : nullptr; if (!Current.insert(Canonical).second) return; @@ -18206,14 +18082,14 @@ Target->isInvalidDecl() || Valid.count(TCanonical)) { Valid.insert(Current.begin(), Current.end()); Current.clear(); - // We've hit a cycle. + // We've hit a cycle. } else if (TCanonical == Canonical || Invalid.count(TCanonical) || Current.count(TCanonical)) { // If we haven't diagnosed this cycle yet, do so now. if (!Invalid.count(TCanonical)) { S.Diag((*Ctor->init_begin())->getSourceLocation(), diag::warn_delegating_ctor_cycle) - << Ctor; + << Ctor; // Don't add a note for a function delegating directly to itself. if (TCanonical != Canonical) @@ -18225,8 +18101,8 @@ (void)C->getTargetConstructor()->hasBody(FNTarget); assert(FNTarget && "Ctor cycle through bodiless function"); - C = const_cast( - cast(FNTarget)); + C = const_cast( + cast(FNTarget)); S.Diag(C->getLocation(), diag::note_which_delegates_to); } } @@ -18238,9 +18114,8 @@ } } - void Sema::CheckDelegatingCtorCycles() { - llvm::SmallPtrSet Valid, Invalid, Current; + llvm::SmallPtrSet Valid, Invalid, Current; for (DelegatingCtorDeclsType::iterator I = DelegatingCtorDecls.begin(ExternalSource.get()), @@ -18253,20 +18128,20 @@ } namespace { - /// AST visitor that finds references to the 'this' expression. - class FindCXXThisExpr : public RecursiveASTVisitor { - Sema &S; +/// AST visitor that finds references to the 'this' expression. +class FindCXXThisExpr : public RecursiveASTVisitor { + Sema &S; - public: - explicit FindCXXThisExpr(Sema &S) : S(S) { } +public: + explicit FindCXXThisExpr(Sema &S) : S(S) {} - bool VisitCXXThisExpr(CXXThisExpr *E) { - S.Diag(E->getLocation(), diag::err_this_static_member_func) + bool VisitCXXThisExpr(CXXThisExpr *E) { + S.Diag(E->getLocation(), diag::err_this_static_member_func) << E->isImplicit(); - return false; - } - }; -} + return false; + } +}; +} // namespace bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); @@ -18431,7 +18306,7 @@ if (isComputedNoexcept(EST)) { assert((NoexceptExpr->isTypeDependent() || NoexceptExpr->getType()->getCanonicalTypeUnqualified() == - Context.BoolTy) && + Context.BoolTy) && "Parser should have made sure that the expression is boolean"); if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { ESI.Type = EST_BasicNoexcept; @@ -18443,12 +18318,10 @@ } } -void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, - ExceptionSpecificationType EST, - SourceRange SpecificationRange, - ArrayRef DynamicExceptions, - ArrayRef DynamicExceptionRanges, - Expr *NoexceptExpr) { +void Sema::actOnDelayedExceptionSpecification( + Decl *MethodD, ExceptionSpecificationType EST, + SourceRange SpecificationRange, ArrayRef DynamicExceptions, + ArrayRef DynamicExceptionRanges, Expr *NoexceptExpr) { if (!MethodD) return; @@ -18463,12 +18336,12 @@ // Check the exception specification. llvm::SmallVector Exceptions; FunctionProtoType::ExceptionSpecInfo ESI; - checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, + checkExceptionSpecification(/*IsTopLevel*/ true, EST, DynamicExceptions, DynamicExceptionRanges, NoexceptExpr, Exceptions, ESI); // Update the exception specification on the function type. - Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); + Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/ true); if (Method->isStatic()) checkThisInStaticMemberFunctionExceptionSpec(Method); @@ -18516,7 +18389,7 @@ if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), diag::err_invalid_thread) - << DeclSpec::getSpecifierName(TSCS); + << DeclSpec::getSpecifierName(TSCS); // Check to see if this name was declared as a member previously NamedDecl *PrevDecl = nullptr; @@ -18584,8 +18457,8 @@ bool IsMemberSpecialization, IsInvalid; ExplicitParams = MatchTemplateParametersToScopeSpecifier( Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), - Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, - ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, + Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, ExplicitLists, + /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, /*SuppressDiagnostic=*/true); } if (ExplicitParams) { @@ -18604,17 +18477,14 @@ if (FSI.NumExplicitTemplateParams != 0) { TemplateParameterList *ExplicitParams = Declarator.getTemplateParameterLists().back(); - Declarator.setInventedTemplateParameterList( - TemplateParameterList::Create( - Context, ExplicitParams->getTemplateLoc(), - ExplicitParams->getLAngleLoc(), FSI.TemplateParams, - ExplicitParams->getRAngleLoc(), - ExplicitParams->getRequiresClause())); + Declarator.setInventedTemplateParameterList(TemplateParameterList::Create( + Context, ExplicitParams->getTemplateLoc(), + ExplicitParams->getLAngleLoc(), FSI.TemplateParams, + ExplicitParams->getRAngleLoc(), ExplicitParams->getRequiresClause())); } else { - Declarator.setInventedTemplateParameterList( - TemplateParameterList::Create( - Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, - SourceLocation(), /*RequiresClause=*/nullptr)); + Declarator.setInventedTemplateParameterList(TemplateParameterList::Create( + Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, + SourceLocation(), /*RequiresClause=*/nullptr)); } } InventedParameterInfos.pop_back(); diff --git a/clang/test/SemaCXX/static-assert.cpp b/clang/test/SemaCXX/static-assert.cpp --- a/clang/test/SemaCXX/static-assert.cpp +++ b/clang/test/SemaCXX/static-assert.cpp @@ -258,8 +258,14 @@ constexpr bool invert(bool b) { return !b; } + + static_assert(invert(true) || invert(true), ""); // expected-error {{failed}} static_assert(invert(true) == invert(false), ""); // expected-error {{failed}} \ // expected-note {{evaluates to 'false == true'}} + static_assert(true && false, ""); // expected-error {{failed}} + static_assert(invert(true) || invert(true) || false, ""); // expected-error {{failed}} + static_assert((true && invert(true)) || false, ""); // expected-error {{failed}} + static_assert(true && invert(false) && invert(true), ""); // expected-error {{failed}} /// No notes here since we compare a bool expression with a bool literal. static_assert(invert(true) == true, ""); // expected-error {{failed}}