Home | History | Annotate | Line # | Download | only in Sema
SemaDeclCXX.cpp revision 1.1.1.1
      1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 //  This file implements semantic analysis for C++ declarations.
     10 //
     11 //===----------------------------------------------------------------------===//
     12 
     13 #include "clang/AST/ASTConsumer.h"
     14 #include "clang/AST/ASTContext.h"
     15 #include "clang/AST/ASTLambda.h"
     16 #include "clang/AST/ASTMutationListener.h"
     17 #include "clang/AST/CXXInheritance.h"
     18 #include "clang/AST/CharUnits.h"
     19 #include "clang/AST/ComparisonCategories.h"
     20 #include "clang/AST/EvaluatedExprVisitor.h"
     21 #include "clang/AST/ExprCXX.h"
     22 #include "clang/AST/RecordLayout.h"
     23 #include "clang/AST/RecursiveASTVisitor.h"
     24 #include "clang/AST/StmtVisitor.h"
     25 #include "clang/AST/TypeLoc.h"
     26 #include "clang/AST/TypeOrdering.h"
     27 #include "clang/Basic/AttributeCommonInfo.h"
     28 #include "clang/Basic/PartialDiagnostic.h"
     29 #include "clang/Basic/TargetInfo.h"
     30 #include "clang/Lex/LiteralSupport.h"
     31 #include "clang/Lex/Preprocessor.h"
     32 #include "clang/Sema/CXXFieldCollector.h"
     33 #include "clang/Sema/DeclSpec.h"
     34 #include "clang/Sema/Initialization.h"
     35 #include "clang/Sema/Lookup.h"
     36 #include "clang/Sema/ParsedTemplate.h"
     37 #include "clang/Sema/Scope.h"
     38 #include "clang/Sema/ScopeInfo.h"
     39 #include "clang/Sema/SemaInternal.h"
     40 #include "clang/Sema/Template.h"
     41 #include "llvm/ADT/STLExtras.h"
     42 #include "llvm/ADT/SmallString.h"
     43 #include "llvm/ADT/StringExtras.h"
     44 #include <map>
     45 #include <set>
     46 
     47 using namespace clang;
     48 
     49 //===----------------------------------------------------------------------===//
     50 // CheckDefaultArgumentVisitor
     51 //===----------------------------------------------------------------------===//
     52 
     53 namespace {
     54   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
     55   /// the default argument of a parameter to determine whether it
     56   /// contains any ill-formed subexpressions. For example, this will
     57   /// diagnose the use of local variables or parameters within the
     58   /// default argument expression.
     59   class CheckDefaultArgumentVisitor
     60     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
     61     Expr *DefaultArg;
     62     Sema *S;
     63 
     64   public:
     65     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
     66         : DefaultArg(defarg), S(s) {}
     67 
     68     bool VisitExpr(Expr *Node);
     69     bool VisitDeclRefExpr(DeclRefExpr *DRE);
     70     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
     71     bool VisitLambdaExpr(LambdaExpr *Lambda);
     72     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
     73   };
     74 
     75   /// VisitExpr - Visit all of the children of this expression.
     76   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
     77     bool IsInvalid = false;
     78     for (Stmt *SubStmt : Node->children())
     79       IsInvalid |= Visit(SubStmt);
     80     return IsInvalid;
     81   }
     82 
     83   /// VisitDeclRefExpr - Visit a reference to a declaration, to
     84   /// determine whether this declaration can be used in the default
     85   /// argument expression.
     86   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
     87     NamedDecl *Decl = DRE->getDecl();
     88     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
     89       // C++ [dcl.fct.default]p9
     90       //   Default arguments are evaluated each time the function is
     91       //   called. The order of evaluation of function arguments is
     92       //   unspecified. Consequently, parameters of a function shall not
     93       //   be used in default argument expressions, even if they are not
     94       //   evaluated. Parameters of a function declared before a default
     95       //   argument expression are in scope and can hide namespace and
     96       //   class member names.
     97       return S->Diag(DRE->getBeginLoc(),
     98                      diag::err_param_default_argument_references_param)
     99              << Param->getDeclName() << DefaultArg->getSourceRange();
    100     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
    101       // C++ [dcl.fct.default]p7
    102       //   Local variables shall not be used in default argument
    103       //   expressions.
    104       if (VDecl->isLocalVarDecl())
    105         return S->Diag(DRE->getBeginLoc(),
    106                        diag::err_param_default_argument_references_local)
    107                << VDecl->getDeclName() << DefaultArg->getSourceRange();
    108     }
    109 
    110     return false;
    111   }
    112 
    113   /// VisitCXXThisExpr - Visit a C++ "this" expression.
    114   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
    115     // C++ [dcl.fct.default]p8:
    116     //   The keyword this shall not be used in a default argument of a
    117     //   member function.
    118     return S->Diag(ThisE->getBeginLoc(),
    119                    diag::err_param_default_argument_references_this)
    120            << ThisE->getSourceRange();
    121   }
    122 
    123   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
    124     bool Invalid = false;
    125     for (PseudoObjectExpr::semantics_iterator
    126            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
    127       Expr *E = *i;
    128 
    129       // Look through bindings.
    130       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
    131         E = OVE->getSourceExpr();
    132         assert(E && "pseudo-object binding without source expression?");
    133       }
    134 
    135       Invalid |= Visit(E);
    136     }
    137     return Invalid;
    138   }
    139 
    140   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
    141     // C++11 [expr.lambda.prim]p13:
    142     //   A lambda-expression appearing in a default argument shall not
    143     //   implicitly or explicitly capture any entity.
    144     if (Lambda->capture_begin() == Lambda->capture_end())
    145       return false;
    146 
    147     return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
    148   }
    149 }
    150 
    151 void
    152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
    153                                                  const CXXMethodDecl *Method) {
    154   // If we have an MSAny spec already, don't bother.
    155   if (!Method || ComputedEST == EST_MSAny)
    156     return;
    157 
    158   const FunctionProtoType *Proto
    159     = Method->getType()->getAs<FunctionProtoType>();
    160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
    161   if (!Proto)
    162     return;
    163 
    164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
    165 
    166   // If we have a throw-all spec at this point, ignore the function.
    167   if (ComputedEST == EST_None)
    168     return;
    169 
    170   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
    171     EST = EST_BasicNoexcept;
    172 
    173   switch (EST) {
    174   case EST_Unparsed:
    175   case EST_Uninstantiated:
    176   case EST_Unevaluated:
    177     llvm_unreachable("should not see unresolved exception specs here");
    178 
    179   // If this function can throw any exceptions, make a note of that.
    180   case EST_MSAny:
    181   case EST_None:
    182     // FIXME: Whichever we see last of MSAny and None determines our result.
    183     // We should make a consistent, order-independent choice here.
    184     ClearExceptions();
    185     ComputedEST = EST;
    186     return;
    187   case EST_NoexceptFalse:
    188     ClearExceptions();
    189     ComputedEST = EST_None;
    190     return;
    191   // FIXME: If the call to this decl is using any of its default arguments, we
    192   // need to search them for potentially-throwing calls.
    193   // If this function has a basic noexcept, it doesn't affect the outcome.
    194   case EST_BasicNoexcept:
    195   case EST_NoexceptTrue:
    196   case EST_NoThrow:
    197     return;
    198   // If we're still at noexcept(true) and there's a throw() callee,
    199   // change to that specification.
    200   case EST_DynamicNone:
    201     if (ComputedEST == EST_BasicNoexcept)
    202       ComputedEST = EST_DynamicNone;
    203     return;
    204   case EST_DependentNoexcept:
    205     llvm_unreachable(
    206         "should not generate implicit declarations for dependent cases");
    207   case EST_Dynamic:
    208     break;
    209   }
    210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
    211   assert(ComputedEST != EST_None &&
    212          "Shouldn't collect exceptions when throw-all is guaranteed.");
    213   ComputedEST = EST_Dynamic;
    214   // Record the exceptions in this function's exception specification.
    215   for (const auto &E : Proto->exceptions())
    216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
    217       Exceptions.push_back(E);
    218 }
    219 
    220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
    221   if (!E || ComputedEST == EST_MSAny)
    222     return;
    223 
    224   // FIXME:
    225   //
    226   // C++0x [except.spec]p14:
    227   //   [An] implicit exception-specification specifies the type-id T if and
    228   // only if T is allowed by the exception-specification of a function directly
    229   // invoked by f's implicit definition; f shall allow all exceptions if any
    230   // function it directly invokes allows all exceptions, and f shall allow no
    231   // exceptions if every function it directly invokes allows no exceptions.
    232   //
    233   // Note in particular that if an implicit exception-specification is generated
    234   // for a function containing a throw-expression, that specification can still
    235   // be noexcept(true).
    236   //
    237   // Note also that 'directly invoked' is not defined in the standard, and there
    238   // is no indication that we should only consider potentially-evaluated calls.
    239   //
    240   // Ultimately we should implement the intent of the standard: the exception
    241   // specification should be the set of exceptions which can be thrown by the
    242   // implicit definition. For now, we assume that any non-nothrow expression can
    243   // throw any exception.
    244 
    245   if (Self->canThrow(E))
    246     ComputedEST = EST_None;
    247 }
    248 
    249 bool
    250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
    251                               SourceLocation EqualLoc) {
    252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
    253                           diag::err_typecheck_decl_incomplete_type)) {
    254     Param->setInvalidDecl();
    255     return true;
    256   }
    257 
    258   // C++ [dcl.fct.default]p5
    259   //   A default argument expression is implicitly converted (clause
    260   //   4) to the parameter type. The default argument expression has
    261   //   the same semantic constraints as the initializer expression in
    262   //   a declaration of a variable of the parameter type, using the
    263   //   copy-initialization semantics (8.5).
    264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
    265                                                                     Param);
    266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
    267                                                            EqualLoc);
    268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
    269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
    270   if (Result.isInvalid())
    271     return true;
    272   Arg = Result.getAs<Expr>();
    273 
    274   CheckCompletedExpr(Arg, EqualLoc);
    275   Arg = MaybeCreateExprWithCleanups(Arg);
    276 
    277   // Okay: add the default argument to the parameter
    278   Param->setDefaultArg(Arg);
    279 
    280   // We have already instantiated this parameter; provide each of the
    281   // instantiations with the uninstantiated default argument.
    282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
    283     = UnparsedDefaultArgInstantiations.find(Param);
    284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
    285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
    286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
    287 
    288     // We're done tracking this parameter's instantiations.
    289     UnparsedDefaultArgInstantiations.erase(InstPos);
    290   }
    291 
    292   return false;
    293 }
    294 
    295 /// ActOnParamDefaultArgument - Check whether the default argument
    296 /// provided for a function parameter is well-formed. If so, attach it
    297 /// to the parameter declaration.
    298 void
    299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
    300                                 Expr *DefaultArg) {
    301   if (!param || !DefaultArg)
    302     return;
    303 
    304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
    305   UnparsedDefaultArgLocs.erase(Param);
    306 
    307   // Default arguments are only permitted in C++
    308   if (!getLangOpts().CPlusPlus) {
    309     Diag(EqualLoc, diag::err_param_default_argument)
    310       << DefaultArg->getSourceRange();
    311     Param->setInvalidDecl();
    312     return;
    313   }
    314 
    315   // Check for unexpanded parameter packs.
    316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
    317     Param->setInvalidDecl();
    318     return;
    319   }
    320 
    321   // C++11 [dcl.fct.default]p3
    322   //   A default argument expression [...] shall not be specified for a
    323   //   parameter pack.
    324   if (Param->isParameterPack()) {
    325     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
    326         << DefaultArg->getSourceRange();
    327     return;
    328   }
    329 
    330   // Check that the default argument is well-formed
    331   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
    332   if (DefaultArgChecker.Visit(DefaultArg)) {
    333     Param->setInvalidDecl();
    334     return;
    335   }
    336 
    337   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
    338 }
    339 
    340 /// ActOnParamUnparsedDefaultArgument - We've seen a default
    341 /// argument for a function parameter, but we can't parse it yet
    342 /// because we're inside a class definition. Note that this default
    343 /// argument will be parsed later.
    344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
    345                                              SourceLocation EqualLoc,
    346                                              SourceLocation ArgLoc) {
    347   if (!param)
    348     return;
    349 
    350   ParmVarDecl *Param = cast<ParmVarDecl>(param);
    351   Param->setUnparsedDefaultArg();
    352   UnparsedDefaultArgLocs[Param] = ArgLoc;
    353 }
    354 
    355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
    356 /// the default argument for the parameter param failed.
    357 void Sema::ActOnParamDefaultArgumentError(Decl *param,
    358                                           SourceLocation EqualLoc) {
    359   if (!param)
    360     return;
    361 
    362   ParmVarDecl *Param = cast<ParmVarDecl>(param);
    363   Param->setInvalidDecl();
    364   UnparsedDefaultArgLocs.erase(Param);
    365   Param->setDefaultArg(new(Context)
    366                        OpaqueValueExpr(EqualLoc,
    367                                        Param->getType().getNonReferenceType(),
    368                                        VK_RValue));
    369 }
    370 
    371 /// CheckExtraCXXDefaultArguments - Check for any extra default
    372 /// arguments in the declarator, which is not a function declaration
    373 /// or definition and therefore is not permitted to have default
    374 /// arguments. This routine should be invoked for every declarator
    375 /// that is not a function declaration or definition.
    376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
    377   // C++ [dcl.fct.default]p3
    378   //   A default argument expression shall be specified only in the
    379   //   parameter-declaration-clause of a function declaration or in a
    380   //   template-parameter (14.1). It shall not be specified for a
    381   //   parameter pack. If it is specified in a
    382   //   parameter-declaration-clause, it shall not occur within a
    383   //   declarator or abstract-declarator of a parameter-declaration.
    384   bool MightBeFunction = D.isFunctionDeclarationContext();
    385   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
    386     DeclaratorChunk &chunk = D.getTypeObject(i);
    387     if (chunk.Kind == DeclaratorChunk::Function) {
    388       if (MightBeFunction) {
    389         // This is a function declaration. It can have default arguments, but
    390         // keep looking in case its return type is a function type with default
    391         // arguments.
    392         MightBeFunction = false;
    393         continue;
    394       }
    395       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
    396            ++argIdx) {
    397         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
    398         if (Param->hasUnparsedDefaultArg()) {
    399           std::unique_ptr<CachedTokens> Toks =
    400               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
    401           SourceRange SR;
    402           if (Toks->size() > 1)
    403             SR = SourceRange((*Toks)[1].getLocation(),
    404                              Toks->back().getLocation());
    405           else
    406             SR = UnparsedDefaultArgLocs[Param];
    407           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
    408             << SR;
    409         } else if (Param->getDefaultArg()) {
    410           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
    411             << Param->getDefaultArg()->getSourceRange();
    412           Param->setDefaultArg(nullptr);
    413         }
    414       }
    415     } else if (chunk.Kind != DeclaratorChunk::Paren) {
    416       MightBeFunction = false;
    417     }
    418   }
    419 }
    420 
    421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
    422   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
    423     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
    424     if (!PVD->hasDefaultArg())
    425       return false;
    426     if (!PVD->hasInheritedDefaultArg())
    427       return true;
    428   }
    429   return false;
    430 }
    431 
    432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
    433 /// function, once we already know that they have the same
    434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
    435 /// error, false otherwise.
    436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
    437                                 Scope *S) {
    438   bool Invalid = false;
    439 
    440   // The declaration context corresponding to the scope is the semantic
    441   // parent, unless this is a local function declaration, in which case
    442   // it is that surrounding function.
    443   DeclContext *ScopeDC = New->isLocalExternDecl()
    444                              ? New->getLexicalDeclContext()
    445                              : New->getDeclContext();
    446 
    447   // Find the previous declaration for the purpose of default arguments.
    448   FunctionDecl *PrevForDefaultArgs = Old;
    449   for (/**/; PrevForDefaultArgs;
    450        // Don't bother looking back past the latest decl if this is a local
    451        // extern declaration; nothing else could work.
    452        PrevForDefaultArgs = New->isLocalExternDecl()
    453                                 ? nullptr
    454                                 : PrevForDefaultArgs->getPreviousDecl()) {
    455     // Ignore hidden declarations.
    456     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
    457       continue;
    458 
    459     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
    460         !New->isCXXClassMember()) {
    461       // Ignore default arguments of old decl if they are not in
    462       // the same scope and this is not an out-of-line definition of
    463       // a member function.
    464       continue;
    465     }
    466 
    467     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
    468       // If only one of these is a local function declaration, then they are
    469       // declared in different scopes, even though isDeclInScope may think
    470       // they're in the same scope. (If both are local, the scope check is
    471       // sufficient, and if neither is local, then they are in the same scope.)
    472       continue;
    473     }
    474 
    475     // We found the right previous declaration.
    476     break;
    477   }
    478 
    479   // C++ [dcl.fct.default]p4:
    480   //   For non-template functions, default arguments can be added in
    481   //   later declarations of a function in the same
    482   //   scope. Declarations in different scopes have completely
    483   //   distinct sets of default arguments. That is, declarations in
    484   //   inner scopes do not acquire default arguments from
    485   //   declarations in outer scopes, and vice versa. In a given
    486   //   function declaration, all parameters subsequent to a
    487   //   parameter with a default argument shall have default
    488   //   arguments supplied in this or previous declarations. A
    489   //   default argument shall not be redefined by a later
    490   //   declaration (not even to the same value).
    491   //
    492   // C++ [dcl.fct.default]p6:
    493   //   Except for member functions of class templates, the default arguments
    494   //   in a member function definition that appears outside of the class
    495   //   definition are added to the set of default arguments provided by the
    496   //   member function declaration in the class definition.
    497   for (unsigned p = 0, NumParams = PrevForDefaultArgs
    498                                        ? PrevForDefaultArgs->getNumParams()
    499                                        : 0;
    500        p < NumParams; ++p) {
    501     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
    502     ParmVarDecl *NewParam = New->getParamDecl(p);
    503 
    504     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
    505     bool NewParamHasDfl = NewParam->hasDefaultArg();
    506 
    507     if (OldParamHasDfl && NewParamHasDfl) {
    508       unsigned DiagDefaultParamID =
    509         diag::err_param_default_argument_redefinition;
    510 
    511       // MSVC accepts that default parameters be redefined for member functions
    512       // of template class. The new default parameter's value is ignored.
    513       Invalid = true;
    514       if (getLangOpts().MicrosoftExt) {
    515         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
    516         if (MD && MD->getParent()->getDescribedClassTemplate()) {
    517           // Merge the old default argument into the new parameter.
    518           NewParam->setHasInheritedDefaultArg();
    519           if (OldParam->hasUninstantiatedDefaultArg())
    520             NewParam->setUninstantiatedDefaultArg(
    521                                       OldParam->getUninstantiatedDefaultArg());
    522           else
    523             NewParam->setDefaultArg(OldParam->getInit());
    524           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
    525           Invalid = false;
    526         }
    527       }
    528 
    529       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
    530       // hint here. Alternatively, we could walk the type-source information
    531       // for NewParam to find the last source location in the type... but it
    532       // isn't worth the effort right now. This is the kind of test case that
    533       // is hard to get right:
    534       //   int f(int);
    535       //   void g(int (*fp)(int) = f);
    536       //   void g(int (*fp)(int) = &f);
    537       Diag(NewParam->getLocation(), DiagDefaultParamID)
    538         << NewParam->getDefaultArgRange();
    539 
    540       // Look for the function declaration where the default argument was
    541       // actually written, which may be a declaration prior to Old.
    542       for (auto Older = PrevForDefaultArgs;
    543            OldParam->hasInheritedDefaultArg(); /**/) {
    544         Older = Older->getPreviousDecl();
    545         OldParam = Older->getParamDecl(p);
    546       }
    547 
    548       Diag(OldParam->getLocation(), diag::note_previous_definition)
    549         << OldParam->getDefaultArgRange();
    550     } else if (OldParamHasDfl) {
    551       // Merge the old default argument into the new parameter unless the new
    552       // function is a friend declaration in a template class. In the latter
    553       // case the default arguments will be inherited when the friend
    554       // declaration will be instantiated.
    555       if (New->getFriendObjectKind() == Decl::FOK_None ||
    556           !New->getLexicalDeclContext()->isDependentContext()) {
    557         // It's important to use getInit() here;  getDefaultArg()
    558         // strips off any top-level ExprWithCleanups.
    559         NewParam->setHasInheritedDefaultArg();
    560         if (OldParam->hasUnparsedDefaultArg())
    561           NewParam->setUnparsedDefaultArg();
    562         else if (OldParam->hasUninstantiatedDefaultArg())
    563           NewParam->setUninstantiatedDefaultArg(
    564                                        OldParam->getUninstantiatedDefaultArg());
    565         else
    566           NewParam->setDefaultArg(OldParam->getInit());
    567       }
    568     } else if (NewParamHasDfl) {
    569       if (New->getDescribedFunctionTemplate()) {
    570         // Paragraph 4, quoted above, only applies to non-template functions.
    571         Diag(NewParam->getLocation(),
    572              diag::err_param_default_argument_template_redecl)
    573           << NewParam->getDefaultArgRange();
    574         Diag(PrevForDefaultArgs->getLocation(),
    575              diag::note_template_prev_declaration)
    576             << false;
    577       } else if (New->getTemplateSpecializationKind()
    578                    != TSK_ImplicitInstantiation &&
    579                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
    580         // C++ [temp.expr.spec]p21:
    581         //   Default function arguments shall not be specified in a declaration
    582         //   or a definition for one of the following explicit specializations:
    583         //     - the explicit specialization of a function template;
    584         //     - the explicit specialization of a member function template;
    585         //     - the explicit specialization of a member function of a class
    586         //       template where the class template specialization to which the
    587         //       member function specialization belongs is implicitly
    588         //       instantiated.
    589         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
    590           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
    591           << New->getDeclName()
    592           << NewParam->getDefaultArgRange();
    593       } else if (New->getDeclContext()->isDependentContext()) {
    594         // C++ [dcl.fct.default]p6 (DR217):
    595         //   Default arguments for a member function of a class template shall
    596         //   be specified on the initial declaration of the member function
    597         //   within the class template.
    598         //
    599         // Reading the tea leaves a bit in DR217 and its reference to DR205
    600         // leads me to the conclusion that one cannot add default function
    601         // arguments for an out-of-line definition of a member function of a
    602         // dependent type.
    603         int WhichKind = 2;
    604         if (CXXRecordDecl *Record
    605               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
    606           if (Record->getDescribedClassTemplate())
    607             WhichKind = 0;
    608           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
    609             WhichKind = 1;
    610           else
    611             WhichKind = 2;
    612         }
    613 
    614         Diag(NewParam->getLocation(),
    615              diag::err_param_default_argument_member_template_redecl)
    616           << WhichKind
    617           << NewParam->getDefaultArgRange();
    618       }
    619     }
    620   }
    621 
    622   // DR1344: If a default argument is added outside a class definition and that
    623   // default argument makes the function a special member function, the program
    624   // is ill-formed. This can only happen for constructors.
    625   if (isa<CXXConstructorDecl>(New) &&
    626       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
    627     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
    628                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
    629     if (NewSM != OldSM) {
    630       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
    631       assert(NewParam->hasDefaultArg());
    632       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
    633         << NewParam->getDefaultArgRange() << NewSM;
    634       Diag(Old->getLocation(), diag::note_previous_declaration);
    635     }
    636   }
    637 
    638   const FunctionDecl *Def;
    639   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
    640   // template has a constexpr specifier then all its declarations shall
    641   // contain the constexpr specifier.
    642   if (New->getConstexprKind() != Old->getConstexprKind()) {
    643     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
    644         << New << New->getConstexprKind() << Old->getConstexprKind();
    645     Diag(Old->getLocation(), diag::note_previous_declaration);
    646     Invalid = true;
    647   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
    648              Old->isDefined(Def) &&
    649              // If a friend function is inlined but does not have 'inline'
    650              // specifier, it is a definition. Do not report attribute conflict
    651              // in this case, redefinition will be diagnosed later.
    652              (New->isInlineSpecified() ||
    653               New->getFriendObjectKind() == Decl::FOK_None)) {
    654     // C++11 [dcl.fcn.spec]p4:
    655     //   If the definition of a function appears in a translation unit before its
    656     //   first declaration as inline, the program is ill-formed.
    657     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
    658     Diag(Def->getLocation(), diag::note_previous_definition);
    659     Invalid = true;
    660   }
    661 
    662   // C++17 [temp.deduct.guide]p3:
    663   //   Two deduction guide declarations in the same translation unit
    664   //   for the same class template shall not have equivalent
    665   //   parameter-declaration-clauses.
    666   if (isa<CXXDeductionGuideDecl>(New) &&
    667       !New->isFunctionTemplateSpecialization()) {
    668     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
    669     Diag(Old->getLocation(), diag::note_previous_declaration);
    670   }
    671 
    672   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
    673   // argument expression, that declaration shall be a definition and shall be
    674   // the only declaration of the function or function template in the
    675   // translation unit.
    676   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
    677       functionDeclHasDefaultArgument(Old)) {
    678     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
    679     Diag(Old->getLocation(), diag::note_previous_declaration);
    680     Invalid = true;
    681   }
    682 
    683   return Invalid;
    684 }
    685 
    686 NamedDecl *
    687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
    688                                    MultiTemplateParamsArg TemplateParamLists) {
    689   assert(D.isDecompositionDeclarator());
    690   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
    691 
    692   // The syntax only allows a decomposition declarator as a simple-declaration,
    693   // a for-range-declaration, or a condition in Clang, but we parse it in more
    694   // cases than that.
    695   if (!D.mayHaveDecompositionDeclarator()) {
    696     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
    697       << Decomp.getSourceRange();
    698     return nullptr;
    699   }
    700 
    701   if (!TemplateParamLists.empty()) {
    702     // FIXME: There's no rule against this, but there are also no rules that
    703     // would actually make it usable, so we reject it for now.
    704     Diag(TemplateParamLists.front()->getTemplateLoc(),
    705          diag::err_decomp_decl_template);
    706     return nullptr;
    707   }
    708 
    709   Diag(Decomp.getLSquareLoc(),
    710        !getLangOpts().CPlusPlus17
    711            ? diag::ext_decomp_decl
    712            : D.getContext() == DeclaratorContext::ConditionContext
    713                  ? diag::ext_decomp_decl_cond
    714                  : diag::warn_cxx14_compat_decomp_decl)
    715       << Decomp.getSourceRange();
    716 
    717   // The semantic context is always just the current context.
    718   DeclContext *const DC = CurContext;
    719 
    720   // C++17 [dcl.dcl]/8:
    721   //   The decl-specifier-seq shall contain only the type-specifier auto
    722   //   and cv-qualifiers.
    723   // C++2a [dcl.dcl]/8:
    724   //   If decl-specifier-seq contains any decl-specifier other than static,
    725   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
    726   auto &DS = D.getDeclSpec();
    727   {
    728     SmallVector<StringRef, 8> BadSpecifiers;
    729     SmallVector<SourceLocation, 8> BadSpecifierLocs;
    730     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
    731     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
    732     if (auto SCS = DS.getStorageClassSpec()) {
    733       if (SCS == DeclSpec::SCS_static) {
    734         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
    735         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
    736       } else {
    737         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
    738         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
    739       }
    740     }
    741     if (auto TSCS = DS.getThreadStorageClassSpec()) {
    742       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
    743       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
    744     }
    745     if (DS.hasConstexprSpecifier()) {
    746       BadSpecifiers.push_back(
    747           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
    748       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
    749     }
    750     if (DS.isInlineSpecified()) {
    751       BadSpecifiers.push_back("inline");
    752       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
    753     }
    754     if (!BadSpecifiers.empty()) {
    755       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
    756       Err << (int)BadSpecifiers.size()
    757           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
    758       // Don't add FixItHints to remove the specifiers; we do still respect
    759       // them when building the underlying variable.
    760       for (auto Loc : BadSpecifierLocs)
    761         Err << SourceRange(Loc, Loc);
    762     } else if (!CPlusPlus20Specifiers.empty()) {
    763       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
    764                          getLangOpts().CPlusPlus2a
    765                              ? diag::warn_cxx17_compat_decomp_decl_spec
    766                              : diag::ext_decomp_decl_spec);
    767       Warn << (int)CPlusPlus20Specifiers.size()
    768            << llvm::join(CPlusPlus20Specifiers.begin(),
    769                          CPlusPlus20Specifiers.end(), " ");
    770       for (auto Loc : CPlusPlus20SpecifierLocs)
    771         Warn << SourceRange(Loc, Loc);
    772     }
    773     // We can't recover from it being declared as a typedef.
    774     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
    775       return nullptr;
    776   }
    777 
    778   // C++2a [dcl.struct.bind]p1:
    779   //   A cv that includes volatile is deprecated
    780   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
    781       getLangOpts().CPlusPlus2a)
    782     Diag(DS.getVolatileSpecLoc(),
    783          diag::warn_deprecated_volatile_structured_binding);
    784 
    785   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
    786   QualType R = TInfo->getType();
    787 
    788   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
    789                                       UPPC_DeclarationType))
    790     D.setInvalidType();
    791 
    792   // The syntax only allows a single ref-qualifier prior to the decomposition
    793   // declarator. No other declarator chunks are permitted. Also check the type
    794   // specifier here.
    795   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
    796       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
    797       (D.getNumTypeObjects() == 1 &&
    798        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
    799     Diag(Decomp.getLSquareLoc(),
    800          (D.hasGroupingParens() ||
    801           (D.getNumTypeObjects() &&
    802            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
    803              ? diag::err_decomp_decl_parens
    804              : diag::err_decomp_decl_type)
    805         << R;
    806 
    807     // In most cases, there's no actual problem with an explicitly-specified
    808     // type, but a function type won't work here, and ActOnVariableDeclarator
    809     // shouldn't be called for such a type.
    810     if (R->isFunctionType())
    811       D.setInvalidType();
    812   }
    813 
    814   // Build the BindingDecls.
    815   SmallVector<BindingDecl*, 8> Bindings;
    816 
    817   // Build the BindingDecls.
    818   for (auto &B : D.getDecompositionDeclarator().bindings()) {
    819     // Check for name conflicts.
    820     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
    821     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
    822                           ForVisibleRedeclaration);
    823     LookupName(Previous, S,
    824                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
    825 
    826     // It's not permitted to shadow a template parameter name.
    827     if (Previous.isSingleResult() &&
    828         Previous.getFoundDecl()->isTemplateParameter()) {
    829       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
    830                                       Previous.getFoundDecl());
    831       Previous.clear();
    832     }
    833 
    834     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
    835                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
    836     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
    837                          /*AllowInlineNamespace*/false);
    838     if (!Previous.empty()) {
    839       auto *Old = Previous.getRepresentativeDecl();
    840       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
    841       Diag(Old->getLocation(), diag::note_previous_definition);
    842     }
    843 
    844     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
    845     PushOnScopeChains(BD, S, true);
    846     Bindings.push_back(BD);
    847     ParsingInitForAutoVars.insert(BD);
    848   }
    849 
    850   // There are no prior lookup results for the variable itself, because it
    851   // is unnamed.
    852   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
    853                                Decomp.getLSquareLoc());
    854   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
    855                         ForVisibleRedeclaration);
    856 
    857   // Build the variable that holds the non-decomposed object.
    858   bool AddToScope = true;
    859   NamedDecl *New =
    860       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
    861                               MultiTemplateParamsArg(), AddToScope, Bindings);
    862   if (AddToScope) {
    863     S->AddDecl(New);
    864     CurContext->addHiddenDecl(New);
    865   }
    866 
    867   if (isInOpenMPDeclareTargetContext())
    868     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
    869 
    870   return New;
    871 }
    872 
    873 static bool checkSimpleDecomposition(
    874     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
    875     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
    876     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
    877   if ((int64_t)Bindings.size() != NumElems) {
    878     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
    879         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
    880         << (NumElems < Bindings.size());
    881     return true;
    882   }
    883 
    884   unsigned I = 0;
    885   for (auto *B : Bindings) {
    886     SourceLocation Loc = B->getLocation();
    887     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
    888     if (E.isInvalid())
    889       return true;
    890     E = GetInit(Loc, E.get(), I++);
    891     if (E.isInvalid())
    892       return true;
    893     B->setBinding(ElemType, E.get());
    894   }
    895 
    896   return false;
    897 }
    898 
    899 static bool checkArrayLikeDecomposition(Sema &S,
    900                                         ArrayRef<BindingDecl *> Bindings,
    901                                         ValueDecl *Src, QualType DecompType,
    902                                         const llvm::APSInt &NumElems,
    903                                         QualType ElemType) {
    904   return checkSimpleDecomposition(
    905       S, Bindings, Src, DecompType, NumElems, ElemType,
    906       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
    907         ExprResult E = S.ActOnIntegerConstant(Loc, I);
    908         if (E.isInvalid())
    909           return ExprError();
    910         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
    911       });
    912 }
    913 
    914 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
    915                                     ValueDecl *Src, QualType DecompType,
    916                                     const ConstantArrayType *CAT) {
    917   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
    918                                      llvm::APSInt(CAT->getSize()),
    919                                      CAT->getElementType());
    920 }
    921 
    922 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
    923                                      ValueDecl *Src, QualType DecompType,
    924                                      const VectorType *VT) {
    925   return checkArrayLikeDecomposition(
    926       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
    927       S.Context.getQualifiedType(VT->getElementType(),
    928                                  DecompType.getQualifiers()));
    929 }
    930 
    931 static bool checkComplexDecomposition(Sema &S,
    932                                       ArrayRef<BindingDecl *> Bindings,
    933                                       ValueDecl *Src, QualType DecompType,
    934                                       const ComplexType *CT) {
    935   return checkSimpleDecomposition(
    936       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
    937       S.Context.getQualifiedType(CT->getElementType(),
    938                                  DecompType.getQualifiers()),
    939       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
    940         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
    941       });
    942 }
    943 
    944 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
    945                                      TemplateArgumentListInfo &Args) {
    946   SmallString<128> SS;
    947   llvm::raw_svector_ostream OS(SS);
    948   bool First = true;
    949   for (auto &Arg : Args.arguments()) {
    950     if (!First)
    951       OS << ", ";
    952     Arg.getArgument().print(PrintingPolicy, OS);
    953     First = false;
    954   }
    955   return OS.str();
    956 }
    957 
    958 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
    959                                      SourceLocation Loc, StringRef Trait,
    960                                      TemplateArgumentListInfo &Args,
    961                                      unsigned DiagID) {
    962   auto DiagnoseMissing = [&] {
    963     if (DiagID)
    964       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
    965                                                Args);
    966     return true;
    967   };
    968 
    969   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
    970   NamespaceDecl *Std = S.getStdNamespace();
    971   if (!Std)
    972     return DiagnoseMissing();
    973 
    974   // Look up the trait itself, within namespace std. We can diagnose various
    975   // problems with this lookup even if we've been asked to not diagnose a
    976   // missing specialization, because this can only fail if the user has been
    977   // declaring their own names in namespace std or we don't support the
    978   // standard library implementation in use.
    979   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
    980                       Loc, Sema::LookupOrdinaryName);
    981   if (!S.LookupQualifiedName(Result, Std))
    982     return DiagnoseMissing();
    983   if (Result.isAmbiguous())
    984     return true;
    985 
    986   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
    987   if (!TraitTD) {
    988     Result.suppressDiagnostics();
    989     NamedDecl *Found = *Result.begin();
    990     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
    991     S.Diag(Found->getLocation(), diag::note_declared_at);
    992     return true;
    993   }
    994 
    995   // Build the template-id.
    996   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
    997   if (TraitTy.isNull())
    998     return true;
    999   if (!S.isCompleteType(Loc, TraitTy)) {
   1000     if (DiagID)
   1001       S.RequireCompleteType(
   1002           Loc, TraitTy, DiagID,
   1003           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
   1004     return true;
   1005   }
   1006 
   1007   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
   1008   assert(RD && "specialization of class template is not a class?");
   1009 
   1010   // Look up the member of the trait type.
   1011   S.LookupQualifiedName(TraitMemberLookup, RD);
   1012   return TraitMemberLookup.isAmbiguous();
   1013 }
   1014 
   1015 static TemplateArgumentLoc
   1016 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
   1017                                    uint64_t I) {
   1018   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
   1019   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
   1020 }
   1021 
   1022 static TemplateArgumentLoc
   1023 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
   1024   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
   1025 }
   1026 
   1027 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
   1028 
   1029 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
   1030                                llvm::APSInt &Size) {
   1031   EnterExpressionEvaluationContext ContextRAII(
   1032       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
   1033 
   1034   DeclarationName Value = S.PP.getIdentifierInfo("value");
   1035   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
   1036 
   1037   // Form template argument list for tuple_size<T>.
   1038   TemplateArgumentListInfo Args(Loc, Loc);
   1039   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
   1040 
   1041   // If there's no tuple_size specialization or the lookup of 'value' is empty,
   1042   // it's not tuple-like.
   1043   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
   1044       R.empty())
   1045     return IsTupleLike::NotTupleLike;
   1046 
   1047   // If we get this far, we've committed to the tuple interpretation, but
   1048   // we can still fail if there actually isn't a usable ::value.
   1049 
   1050   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
   1051     LookupResult &R;
   1052     TemplateArgumentListInfo &Args;
   1053     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
   1054         : R(R), Args(Args) {}
   1055     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
   1056       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
   1057           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
   1058     }
   1059   } Diagnoser(R, Args);
   1060 
   1061   ExprResult E =
   1062       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
   1063   if (E.isInvalid())
   1064     return IsTupleLike::Error;
   1065 
   1066   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
   1067   if (E.isInvalid())
   1068     return IsTupleLike::Error;
   1069 
   1070   return IsTupleLike::TupleLike;
   1071 }
   1072 
   1073 /// \return std::tuple_element<I, T>::type.
   1074 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
   1075                                         unsigned I, QualType T) {
   1076   // Form template argument list for tuple_element<I, T>.
   1077   TemplateArgumentListInfo Args(Loc, Loc);
   1078   Args.addArgument(
   1079       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
   1080   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
   1081 
   1082   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
   1083   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
   1084   if (lookupStdTypeTraitMember(
   1085           S, R, Loc, "tuple_element", Args,
   1086           diag::err_decomp_decl_std_tuple_element_not_specialized))
   1087     return QualType();
   1088 
   1089   auto *TD = R.getAsSingle<TypeDecl>();
   1090   if (!TD) {
   1091     R.suppressDiagnostics();
   1092     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
   1093       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
   1094     if (!R.empty())
   1095       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
   1096     return QualType();
   1097   }
   1098 
   1099   return S.Context.getTypeDeclType(TD);
   1100 }
   1101 
   1102 namespace {
   1103 struct BindingDiagnosticTrap {
   1104   Sema &S;
   1105   DiagnosticErrorTrap Trap;
   1106   BindingDecl *BD;
   1107 
   1108   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
   1109       : S(S), Trap(S.Diags), BD(BD) {}
   1110   ~BindingDiagnosticTrap() {
   1111     if (Trap.hasErrorOccurred())
   1112       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
   1113   }
   1114 };
   1115 }
   1116 
   1117 static bool checkTupleLikeDecomposition(Sema &S,
   1118                                         ArrayRef<BindingDecl *> Bindings,
   1119                                         VarDecl *Src, QualType DecompType,
   1120                                         const llvm::APSInt &TupleSize) {
   1121   if ((int64_t)Bindings.size() != TupleSize) {
   1122     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
   1123         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
   1124         << (TupleSize < Bindings.size());
   1125     return true;
   1126   }
   1127 
   1128   if (Bindings.empty())
   1129     return false;
   1130 
   1131   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
   1132 
   1133   // [dcl.decomp]p3:
   1134   //   The unqualified-id get is looked up in the scope of E by class member
   1135   //   access lookup ...
   1136   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
   1137   bool UseMemberGet = false;
   1138   if (S.isCompleteType(Src->getLocation(), DecompType)) {
   1139     if (auto *RD = DecompType->getAsCXXRecordDecl())
   1140       S.LookupQualifiedName(MemberGet, RD);
   1141     if (MemberGet.isAmbiguous())
   1142       return true;
   1143     //   ... and if that finds at least one declaration that is a function
   1144     //   template whose first template parameter is a non-type parameter ...
   1145     for (NamedDecl *D : MemberGet) {
   1146       if (FunctionTemplateDecl *FTD =
   1147               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
   1148         TemplateParameterList *TPL = FTD->getTemplateParameters();
   1149         if (TPL->size() != 0 &&
   1150             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
   1151           //   ... the initializer is e.get<i>().
   1152           UseMemberGet = true;
   1153           break;
   1154         }
   1155       }
   1156     }
   1157   }
   1158 
   1159   unsigned I = 0;
   1160   for (auto *B : Bindings) {
   1161     BindingDiagnosticTrap Trap(S, B);
   1162     SourceLocation Loc = B->getLocation();
   1163 
   1164     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
   1165     if (E.isInvalid())
   1166       return true;
   1167 
   1168     //   e is an lvalue if the type of the entity is an lvalue reference and
   1169     //   an xvalue otherwise
   1170     if (!Src->getType()->isLValueReferenceType())
   1171       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
   1172                                    E.get(), nullptr, VK_XValue);
   1173 
   1174     TemplateArgumentListInfo Args(Loc, Loc);
   1175     Args.addArgument(
   1176         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
   1177 
   1178     if (UseMemberGet) {
   1179       //   if [lookup of member get] finds at least one declaration, the
   1180       //   initializer is e.get<i-1>().
   1181       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
   1182                                      CXXScopeSpec(), SourceLocation(), nullptr,
   1183                                      MemberGet, &Args, nullptr);
   1184       if (E.isInvalid())
   1185         return true;
   1186 
   1187       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
   1188     } else {
   1189       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
   1190       //   in the associated namespaces.
   1191       Expr *Get = UnresolvedLookupExpr::Create(
   1192           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
   1193           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
   1194           UnresolvedSetIterator(), UnresolvedSetIterator());
   1195 
   1196       Expr *Arg = E.get();
   1197       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
   1198     }
   1199     if (E.isInvalid())
   1200       return true;
   1201     Expr *Init = E.get();
   1202 
   1203     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
   1204     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
   1205     if (T.isNull())
   1206       return true;
   1207 
   1208     //   each vi is a variable of type "reference to T" initialized with the
   1209     //   initializer, where the reference is an lvalue reference if the
   1210     //   initializer is an lvalue and an rvalue reference otherwise
   1211     QualType RefType =
   1212         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
   1213     if (RefType.isNull())
   1214       return true;
   1215     auto *RefVD = VarDecl::Create(
   1216         S.Context, Src->getDeclContext(), Loc, Loc,
   1217         B->getDeclName().getAsIdentifierInfo(), RefType,
   1218         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
   1219     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
   1220     RefVD->setTSCSpec(Src->getTSCSpec());
   1221     RefVD->setImplicit();
   1222     if (Src->isInlineSpecified())
   1223       RefVD->setInlineSpecified();
   1224     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
   1225 
   1226     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
   1227     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
   1228     InitializationSequence Seq(S, Entity, Kind, Init);
   1229     E = Seq.Perform(S, Entity, Kind, Init);
   1230     if (E.isInvalid())
   1231       return true;
   1232     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
   1233     if (E.isInvalid())
   1234       return true;
   1235     RefVD->setInit(E.get());
   1236     if (!E.get()->isValueDependent())
   1237       RefVD->checkInitIsICE();
   1238 
   1239     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
   1240                                    DeclarationNameInfo(B->getDeclName(), Loc),
   1241                                    RefVD);
   1242     if (E.isInvalid())
   1243       return true;
   1244 
   1245     B->setBinding(T, E.get());
   1246     I++;
   1247   }
   1248 
   1249   return false;
   1250 }
   1251 
   1252 /// Find the base class to decompose in a built-in decomposition of a class type.
   1253 /// This base class search is, unfortunately, not quite like any other that we
   1254 /// perform anywhere else in C++.
   1255 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
   1256                                                 const CXXRecordDecl *RD,
   1257                                                 CXXCastPath &BasePath) {
   1258   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
   1259                           CXXBasePath &Path) {
   1260     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
   1261   };
   1262 
   1263   const CXXRecordDecl *ClassWithFields = nullptr;
   1264   AccessSpecifier AS = AS_public;
   1265   if (RD->hasDirectFields())
   1266     // [dcl.decomp]p4:
   1267     //   Otherwise, all of E's non-static data members shall be public direct
   1268     //   members of E ...
   1269     ClassWithFields = RD;
   1270   else {
   1271     //   ... or of ...
   1272     CXXBasePaths Paths;
   1273     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
   1274     if (!RD->lookupInBases(BaseHasFields, Paths)) {
   1275       // If no classes have fields, just decompose RD itself. (This will work
   1276       // if and only if zero bindings were provided.)
   1277       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
   1278     }
   1279 
   1280     CXXBasePath *BestPath = nullptr;
   1281     for (auto &P : Paths) {
   1282       if (!BestPath)
   1283         BestPath = &P;
   1284       else if (!S.Context.hasSameType(P.back().Base->getType(),
   1285                                       BestPath->back().Base->getType())) {
   1286         //   ... the same ...
   1287         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
   1288           << false << RD << BestPath->back().Base->getType()
   1289           << P.back().Base->getType();
   1290         return DeclAccessPair();
   1291       } else if (P.Access < BestPath->Access) {
   1292         BestPath = &P;
   1293       }
   1294     }
   1295 
   1296     //   ... unambiguous ...
   1297     QualType BaseType = BestPath->back().Base->getType();
   1298     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
   1299       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
   1300         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
   1301       return DeclAccessPair();
   1302     }
   1303 
   1304     //   ... [accessible, implied by other rules] base class of E.
   1305     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
   1306                            *BestPath, diag::err_decomp_decl_inaccessible_base);
   1307     AS = BestPath->Access;
   1308 
   1309     ClassWithFields = BaseType->getAsCXXRecordDecl();
   1310     S.BuildBasePathArray(Paths, BasePath);
   1311   }
   1312 
   1313   // The above search did not check whether the selected class itself has base
   1314   // classes with fields, so check that now.
   1315   CXXBasePaths Paths;
   1316   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
   1317     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
   1318       << (ClassWithFields == RD) << RD << ClassWithFields
   1319       << Paths.front().back().Base->getType();
   1320     return DeclAccessPair();
   1321   }
   1322 
   1323   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
   1324 }
   1325 
   1326 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
   1327                                      ValueDecl *Src, QualType DecompType,
   1328                                      const CXXRecordDecl *OrigRD) {
   1329   if (S.RequireCompleteType(Src->getLocation(), DecompType,
   1330                             diag::err_incomplete_type))
   1331     return true;
   1332 
   1333   CXXCastPath BasePath;
   1334   DeclAccessPair BasePair =
   1335       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
   1336   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
   1337   if (!RD)
   1338     return true;
   1339   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
   1340                                                  DecompType.getQualifiers());
   1341 
   1342   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
   1343     unsigned NumFields =
   1344         std::count_if(RD->field_begin(), RD->field_end(),
   1345                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
   1346     assert(Bindings.size() != NumFields);
   1347     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
   1348         << DecompType << (unsigned)Bindings.size() << NumFields
   1349         << (NumFields < Bindings.size());
   1350     return true;
   1351   };
   1352 
   1353   //   all of E's non-static data members shall be [...] well-formed
   1354   //   when named as e.name in the context of the structured binding,
   1355   //   E shall not have an anonymous union member, ...
   1356   unsigned I = 0;
   1357   for (auto *FD : RD->fields()) {
   1358     if (FD->isUnnamedBitfield())
   1359       continue;
   1360 
   1361     if (FD->isAnonymousStructOrUnion()) {
   1362       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
   1363         << DecompType << FD->getType()->isUnionType();
   1364       S.Diag(FD->getLocation(), diag::note_declared_at);
   1365       return true;
   1366     }
   1367 
   1368     // We have a real field to bind.
   1369     if (I >= Bindings.size())
   1370       return DiagnoseBadNumberOfBindings();
   1371     auto *B = Bindings[I++];
   1372     SourceLocation Loc = B->getLocation();
   1373 
   1374     // The field must be accessible in the context of the structured binding.
   1375     // We already checked that the base class is accessible.
   1376     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
   1377     // const_cast here.
   1378     S.CheckStructuredBindingMemberAccess(
   1379         Loc, const_cast<CXXRecordDecl *>(OrigRD),
   1380         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
   1381                                      BasePair.getAccess(), FD->getAccess())));
   1382 
   1383     // Initialize the binding to Src.FD.
   1384     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
   1385     if (E.isInvalid())
   1386       return true;
   1387     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
   1388                             VK_LValue, &BasePath);
   1389     if (E.isInvalid())
   1390       return true;
   1391     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
   1392                                   CXXScopeSpec(), FD,
   1393                                   DeclAccessPair::make(FD, FD->getAccess()),
   1394                                   DeclarationNameInfo(FD->getDeclName(), Loc));
   1395     if (E.isInvalid())
   1396       return true;
   1397 
   1398     // If the type of the member is T, the referenced type is cv T, where cv is
   1399     // the cv-qualification of the decomposition expression.
   1400     //
   1401     // FIXME: We resolve a defect here: if the field is mutable, we do not add
   1402     // 'const' to the type of the field.
   1403     Qualifiers Q = DecompType.getQualifiers();
   1404     if (FD->isMutable())
   1405       Q.removeConst();
   1406     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
   1407   }
   1408 
   1409   if (I != Bindings.size())
   1410     return DiagnoseBadNumberOfBindings();
   1411 
   1412   return false;
   1413 }
   1414 
   1415 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
   1416   QualType DecompType = DD->getType();
   1417 
   1418   // If the type of the decomposition is dependent, then so is the type of
   1419   // each binding.
   1420   if (DecompType->isDependentType()) {
   1421     for (auto *B : DD->bindings())
   1422       B->setType(Context.DependentTy);
   1423     return;
   1424   }
   1425 
   1426   DecompType = DecompType.getNonReferenceType();
   1427   ArrayRef<BindingDecl*> Bindings = DD->bindings();
   1428 
   1429   // C++1z [dcl.decomp]/2:
   1430   //   If E is an array type [...]
   1431   // As an extension, we also support decomposition of built-in complex and
   1432   // vector types.
   1433   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
   1434     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
   1435       DD->setInvalidDecl();
   1436     return;
   1437   }
   1438   if (auto *VT = DecompType->getAs<VectorType>()) {
   1439     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
   1440       DD->setInvalidDecl();
   1441     return;
   1442   }
   1443   if (auto *CT = DecompType->getAs<ComplexType>()) {
   1444     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
   1445       DD->setInvalidDecl();
   1446     return;
   1447   }
   1448 
   1449   // C++1z [dcl.decomp]/3:
   1450   //   if the expression std::tuple_size<E>::value is a well-formed integral
   1451   //   constant expression, [...]
   1452   llvm::APSInt TupleSize(32);
   1453   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
   1454   case IsTupleLike::Error:
   1455     DD->setInvalidDecl();
   1456     return;
   1457 
   1458   case IsTupleLike::TupleLike:
   1459     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
   1460       DD->setInvalidDecl();
   1461     return;
   1462 
   1463   case IsTupleLike::NotTupleLike:
   1464     break;
   1465   }
   1466 
   1467   // C++1z [dcl.dcl]/8:
   1468   //   [E shall be of array or non-union class type]
   1469   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
   1470   if (!RD || RD->isUnion()) {
   1471     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
   1472         << DD << !RD << DecompType;
   1473     DD->setInvalidDecl();
   1474     return;
   1475   }
   1476 
   1477   // C++1z [dcl.decomp]/4:
   1478   //   all of E's non-static data members shall be [...] direct members of
   1479   //   E or of the same unambiguous public base class of E, ...
   1480   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
   1481     DD->setInvalidDecl();
   1482 }
   1483 
   1484 /// Merge the exception specifications of two variable declarations.
   1485 ///
   1486 /// This is called when there's a redeclaration of a VarDecl. The function
   1487 /// checks if the redeclaration might have an exception specification and
   1488 /// validates compatibility and merges the specs if necessary.
   1489 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
   1490   // Shortcut if exceptions are disabled.
   1491   if (!getLangOpts().CXXExceptions)
   1492     return;
   1493 
   1494   assert(Context.hasSameType(New->getType(), Old->getType()) &&
   1495          "Should only be called if types are otherwise the same.");
   1496 
   1497   QualType NewType = New->getType();
   1498   QualType OldType = Old->getType();
   1499 
   1500   // We're only interested in pointers and references to functions, as well
   1501   // as pointers to member functions.
   1502   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
   1503     NewType = R->getPointeeType();
   1504     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
   1505   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
   1506     NewType = P->getPointeeType();
   1507     OldType = OldType->getAs<PointerType>()->getPointeeType();
   1508   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
   1509     NewType = M->getPointeeType();
   1510     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
   1511   }
   1512 
   1513   if (!NewType->isFunctionProtoType())
   1514     return;
   1515 
   1516   // There's lots of special cases for functions. For function pointers, system
   1517   // libraries are hopefully not as broken so that we don't need these
   1518   // workarounds.
   1519   if (CheckEquivalentExceptionSpec(
   1520         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
   1521         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
   1522     New->setInvalidDecl();
   1523   }
   1524 }
   1525 
   1526 /// CheckCXXDefaultArguments - Verify that the default arguments for a
   1527 /// function declaration are well-formed according to C++
   1528 /// [dcl.fct.default].
   1529 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
   1530   unsigned NumParams = FD->getNumParams();
   1531   unsigned p;
   1532 
   1533   // Find first parameter with a default argument
   1534   for (p = 0; p < NumParams; ++p) {
   1535     ParmVarDecl *Param = FD->getParamDecl(p);
   1536     if (Param->hasDefaultArg())
   1537       break;
   1538   }
   1539 
   1540   // C++11 [dcl.fct.default]p4:
   1541   //   In a given function declaration, each parameter subsequent to a parameter
   1542   //   with a default argument shall have a default argument supplied in this or
   1543   //   a previous declaration or shall be a function parameter pack. A default
   1544   //   argument shall not be redefined by a later declaration (not even to the
   1545   //   same value).
   1546   unsigned LastMissingDefaultArg = 0;
   1547   for (; p < NumParams; ++p) {
   1548     ParmVarDecl *Param = FD->getParamDecl(p);
   1549     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
   1550       if (Param->isInvalidDecl())
   1551         /* We already complained about this parameter. */;
   1552       else if (Param->getIdentifier())
   1553         Diag(Param->getLocation(),
   1554              diag::err_param_default_argument_missing_name)
   1555           << Param->getIdentifier();
   1556       else
   1557         Diag(Param->getLocation(),
   1558              diag::err_param_default_argument_missing);
   1559 
   1560       LastMissingDefaultArg = p;
   1561     }
   1562   }
   1563 
   1564   if (LastMissingDefaultArg > 0) {
   1565     // Some default arguments were missing. Clear out all of the
   1566     // default arguments up to (and including) the last missing
   1567     // default argument, so that we leave the function parameters
   1568     // in a semantically valid state.
   1569     for (p = 0; p <= LastMissingDefaultArg; ++p) {
   1570       ParmVarDecl *Param = FD->getParamDecl(p);
   1571       if (Param->hasDefaultArg()) {
   1572         Param->setDefaultArg(nullptr);
   1573       }
   1574     }
   1575   }
   1576 }
   1577 
   1578 /// Check that the given type is a literal type. Issue a diagnostic if not,
   1579 /// if Kind is Diagnose.
   1580 /// \return \c true if a problem has been found (and optionally diagnosed).
   1581 template <typename... Ts>
   1582 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
   1583                              SourceLocation Loc, QualType T, unsigned DiagID,
   1584                              Ts &&...DiagArgs) {
   1585   if (T->isDependentType())
   1586     return false;
   1587 
   1588   switch (Kind) {
   1589   case Sema::CheckConstexprKind::Diagnose:
   1590     return SemaRef.RequireLiteralType(Loc, T, DiagID,
   1591                                       std::forward<Ts>(DiagArgs)...);
   1592 
   1593   case Sema::CheckConstexprKind::CheckValid:
   1594     return !T->isLiteralType(SemaRef.Context);
   1595   }
   1596 
   1597   llvm_unreachable("unknown CheckConstexprKind");
   1598 }
   1599 
   1600 /// Determine whether a destructor cannot be constexpr due to
   1601 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
   1602                                                const CXXDestructorDecl *DD,
   1603                                                Sema::CheckConstexprKind Kind) {
   1604   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
   1605     const CXXRecordDecl *RD =
   1606         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
   1607     if (!RD || RD->hasConstexprDestructor())
   1608       return true;
   1609 
   1610     if (Kind == Sema::CheckConstexprKind::Diagnose) {
   1611       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
   1612           << DD->getConstexprKind() << !FD
   1613           << (FD ? FD->getDeclName() : DeclarationName()) << T;
   1614       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
   1615           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
   1616     }
   1617     return false;
   1618   };
   1619 
   1620   const CXXRecordDecl *RD = DD->getParent();
   1621   for (const CXXBaseSpecifier &B : RD->bases())
   1622     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
   1623       return false;
   1624   for (const FieldDecl *FD : RD->fields())
   1625     if (!Check(FD->getLocation(), FD->getType(), FD))
   1626       return false;
   1627   return true;
   1628 }
   1629 
   1630 // CheckConstexprParameterTypes - Check whether a function's parameter types
   1631 // are all literal types. If so, return true. If not, produce a suitable
   1632 // diagnostic and return false.
   1633 static bool CheckConstexprParameterTypes(Sema &SemaRef,
   1634                                          const FunctionDecl *FD,
   1635                                          Sema::CheckConstexprKind Kind) {
   1636   unsigned ArgIndex = 0;
   1637   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
   1638   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
   1639                                               e = FT->param_type_end();
   1640        i != e; ++i, ++ArgIndex) {
   1641     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
   1642     SourceLocation ParamLoc = PD->getLocation();
   1643     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
   1644                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
   1645                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
   1646                          FD->isConsteval()))
   1647       return false;
   1648   }
   1649   return true;
   1650 }
   1651 
   1652 /// Get diagnostic %select index for tag kind for
   1653 /// record diagnostic message.
   1654 /// WARNING: Indexes apply to particular diagnostics only!
   1655 ///
   1656 /// \returns diagnostic %select index.
   1657 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
   1658   switch (Tag) {
   1659   case TTK_Struct: return 0;
   1660   case TTK_Interface: return 1;
   1661   case TTK_Class:  return 2;
   1662   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
   1663   }
   1664 }
   1665 
   1666 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
   1667                                        Stmt *Body,
   1668                                        Sema::CheckConstexprKind Kind);
   1669 
   1670 // Check whether a function declaration satisfies the requirements of a
   1671 // constexpr function definition or a constexpr constructor definition. If so,
   1672 // return true. If not, produce appropriate diagnostics (unless asked not to by
   1673 // Kind) and return false.
   1674 //
   1675 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
   1676 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
   1677                                             CheckConstexprKind Kind) {
   1678   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
   1679   if (MD && MD->isInstance()) {
   1680     // C++11 [dcl.constexpr]p4:
   1681     //  The definition of a constexpr constructor shall satisfy the following
   1682     //  constraints:
   1683     //  - the class shall not have any virtual base classes;
   1684     //
   1685     // FIXME: This only applies to constructors and destructors, not arbitrary
   1686     // member functions.
   1687     const CXXRecordDecl *RD = MD->getParent();
   1688     if (RD->getNumVBases()) {
   1689       if (Kind == CheckConstexprKind::CheckValid)
   1690         return false;
   1691 
   1692       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
   1693         << isa<CXXConstructorDecl>(NewFD)
   1694         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
   1695       for (const auto &I : RD->vbases())
   1696         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
   1697             << I.getSourceRange();
   1698       return false;
   1699     }
   1700   }
   1701 
   1702   if (!isa<CXXConstructorDecl>(NewFD)) {
   1703     // C++11 [dcl.constexpr]p3:
   1704     //  The definition of a constexpr function shall satisfy the following
   1705     //  constraints:
   1706     // - it shall not be virtual; (removed in C++20)
   1707     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
   1708     if (Method && Method->isVirtual()) {
   1709       if (getLangOpts().CPlusPlus2a) {
   1710         if (Kind == CheckConstexprKind::Diagnose)
   1711           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
   1712       } else {
   1713         if (Kind == CheckConstexprKind::CheckValid)
   1714           return false;
   1715 
   1716         Method = Method->getCanonicalDecl();
   1717         Diag(Method->getLocation(), diag::err_constexpr_virtual);
   1718 
   1719         // If it's not obvious why this function is virtual, find an overridden
   1720         // function which uses the 'virtual' keyword.
   1721         const CXXMethodDecl *WrittenVirtual = Method;
   1722         while (!WrittenVirtual->isVirtualAsWritten())
   1723           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
   1724         if (WrittenVirtual != Method)
   1725           Diag(WrittenVirtual->getLocation(),
   1726                diag::note_overridden_virtual_function);
   1727         return false;
   1728       }
   1729     }
   1730 
   1731     // - its return type shall be a literal type;
   1732     QualType RT = NewFD->getReturnType();
   1733     if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT,
   1734                          diag::err_constexpr_non_literal_return,
   1735                          NewFD->isConsteval()))
   1736       return false;
   1737   }
   1738 
   1739   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
   1740     // A destructor can be constexpr only if the defaulted destructor could be;
   1741     // we don't need to check the members and bases if we already know they all
   1742     // have constexpr destructors.
   1743     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
   1744       if (Kind == CheckConstexprKind::CheckValid)
   1745         return false;
   1746       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
   1747         return false;
   1748     }
   1749   }
   1750 
   1751   // - each of its parameter types shall be a literal type;
   1752   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
   1753     return false;
   1754 
   1755   Stmt *Body = NewFD->getBody();
   1756   assert(Body &&
   1757          "CheckConstexprFunctionDefinition called on function with no body");
   1758   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
   1759 }
   1760 
   1761 /// Check the given declaration statement is legal within a constexpr function
   1762 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
   1763 ///
   1764 /// \return true if the body is OK (maybe only as an extension), false if we
   1765 ///         have diagnosed a problem.
   1766 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
   1767                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
   1768                                    Sema::CheckConstexprKind Kind) {
   1769   // C++11 [dcl.constexpr]p3 and p4:
   1770   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
   1771   //  contain only
   1772   for (const auto *DclIt : DS->decls()) {
   1773     switch (DclIt->getKind()) {
   1774     case Decl::StaticAssert:
   1775     case Decl::Using:
   1776     case Decl::UsingShadow:
   1777     case Decl::UsingDirective:
   1778     case Decl::UnresolvedUsingTypename:
   1779     case Decl::UnresolvedUsingValue:
   1780       //   - static_assert-declarations
   1781       //   - using-declarations,
   1782       //   - using-directives,
   1783       continue;
   1784 
   1785     case Decl::Typedef:
   1786     case Decl::TypeAlias: {
   1787       //   - typedef declarations and alias-declarations that do not define
   1788       //     classes or enumerations,
   1789       const auto *TN = cast<TypedefNameDecl>(DclIt);
   1790       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
   1791         // Don't allow variably-modified types in constexpr functions.
   1792         if (Kind == Sema::CheckConstexprKind::Diagnose) {
   1793           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
   1794           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
   1795             << TL.getSourceRange() << TL.getType()
   1796             << isa<CXXConstructorDecl>(Dcl);
   1797         }
   1798         return false;
   1799       }
   1800       continue;
   1801     }
   1802 
   1803     case Decl::Enum:
   1804     case Decl::CXXRecord:
   1805       // C++1y allows types to be defined, not just declared.
   1806       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
   1807         if (Kind == Sema::CheckConstexprKind::Diagnose) {
   1808           SemaRef.Diag(DS->getBeginLoc(),
   1809                        SemaRef.getLangOpts().CPlusPlus14
   1810                            ? diag::warn_cxx11_compat_constexpr_type_definition
   1811                            : diag::ext_constexpr_type_definition)
   1812               << isa<CXXConstructorDecl>(Dcl);
   1813         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
   1814           return false;
   1815         }
   1816       }
   1817       continue;
   1818 
   1819     case Decl::EnumConstant:
   1820     case Decl::IndirectField:
   1821     case Decl::ParmVar:
   1822       // These can only appear with other declarations which are banned in
   1823       // C++11 and permitted in C++1y, so ignore them.
   1824       continue;
   1825 
   1826     case Decl::Var:
   1827     case Decl::Decomposition: {
   1828       // C++1y [dcl.constexpr]p3 allows anything except:
   1829       //   a definition of a variable of non-literal type or of static or
   1830       //   thread storage duration or [before C++2a] for which no
   1831       //   initialization is performed.
   1832       const auto *VD = cast<VarDecl>(DclIt);
   1833       if (VD->isThisDeclarationADefinition()) {
   1834         if (VD->isStaticLocal()) {
   1835           if (Kind == Sema::CheckConstexprKind::Diagnose) {
   1836             SemaRef.Diag(VD->getLocation(),
   1837                          diag::err_constexpr_local_var_static)
   1838               << isa<CXXConstructorDecl>(Dcl)
   1839               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
   1840           }
   1841           return false;
   1842         }
   1843         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
   1844                              diag::err_constexpr_local_var_non_literal_type,
   1845                              isa<CXXConstructorDecl>(Dcl)))
   1846           return false;
   1847         if (!VD->getType()->isDependentType() &&
   1848             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
   1849           if (Kind == Sema::CheckConstexprKind::Diagnose) {
   1850             SemaRef.Diag(
   1851                 VD->getLocation(),
   1852                 SemaRef.getLangOpts().CPlusPlus2a
   1853                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
   1854                     : diag::ext_constexpr_local_var_no_init)
   1855                 << isa<CXXConstructorDecl>(Dcl);
   1856           } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
   1857             return false;
   1858           }
   1859           continue;
   1860         }
   1861       }
   1862       if (Kind == Sema::CheckConstexprKind::Diagnose) {
   1863         SemaRef.Diag(VD->getLocation(),
   1864                      SemaRef.getLangOpts().CPlusPlus14
   1865                       ? diag::warn_cxx11_compat_constexpr_local_var
   1866                       : diag::ext_constexpr_local_var)
   1867           << isa<CXXConstructorDecl>(Dcl);
   1868       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
   1869         return false;
   1870       }
   1871       continue;
   1872     }
   1873 
   1874     case Decl::NamespaceAlias:
   1875     case Decl::Function:
   1876       // These are disallowed in C++11 and permitted in C++1y. Allow them
   1877       // everywhere as an extension.
   1878       if (!Cxx1yLoc.isValid())
   1879         Cxx1yLoc = DS->getBeginLoc();
   1880       continue;
   1881 
   1882     default:
   1883       if (Kind == Sema::CheckConstexprKind::Diagnose) {
   1884         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
   1885             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
   1886       }
   1887       return false;
   1888     }
   1889   }
   1890 
   1891   return true;
   1892 }
   1893 
   1894 /// Check that the given field is initialized within a constexpr constructor.
   1895 ///
   1896 /// \param Dcl The constexpr constructor being checked.
   1897 /// \param Field The field being checked. This may be a member of an anonymous
   1898 ///        struct or union nested within the class being checked.
   1899 /// \param Inits All declarations, including anonymous struct/union members and
   1900 ///        indirect members, for which any initialization was provided.
   1901 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
   1902 ///        multiple notes for different members to the same error.
   1903 /// \param Kind Whether we're diagnosing a constructor as written or determining
   1904 ///        whether the formal requirements are satisfied.
   1905 /// \return \c false if we're checking for validity and the constructor does
   1906 ///         not satisfy the requirements on a constexpr constructor.
   1907 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
   1908                                           const FunctionDecl *Dcl,
   1909                                           FieldDecl *Field,
   1910                                           llvm::SmallSet<Decl*, 16> &Inits,
   1911                                           bool &Diagnosed,
   1912                                           Sema::CheckConstexprKind Kind) {
   1913   // In C++20 onwards, there's nothing to check for validity.
   1914   if (Kind == Sema::CheckConstexprKind::CheckValid &&
   1915       SemaRef.getLangOpts().CPlusPlus2a)
   1916     return true;
   1917 
   1918   if (Field->isInvalidDecl())
   1919     return true;
   1920 
   1921   if (Field->isUnnamedBitfield())
   1922     return true;
   1923 
   1924   // Anonymous unions with no variant members and empty anonymous structs do not
   1925   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
   1926   // indirect fields don't need initializing.
   1927   if (Field->isAnonymousStructOrUnion() &&
   1928       (Field->getType()->isUnionType()
   1929            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
   1930            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
   1931     return true;
   1932 
   1933   if (!Inits.count(Field)) {
   1934     if (Kind == Sema::CheckConstexprKind::Diagnose) {
   1935       if (!Diagnosed) {
   1936         SemaRef.Diag(Dcl->getLocation(),
   1937                      SemaRef.getLangOpts().CPlusPlus2a
   1938                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
   1939                          : diag::ext_constexpr_ctor_missing_init);
   1940         Diagnosed = true;
   1941       }
   1942       SemaRef.Diag(Field->getLocation(),
   1943                    diag::note_constexpr_ctor_missing_init);
   1944     } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
   1945       return false;
   1946     }
   1947   } else if (Field->isAnonymousStructOrUnion()) {
   1948     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
   1949     for (auto *I : RD->fields())
   1950       // If an anonymous union contains an anonymous struct of which any member
   1951       // is initialized, all members must be initialized.
   1952       if (!RD->isUnion() || Inits.count(I))
   1953         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
   1954                                            Kind))
   1955           return false;
   1956   }
   1957   return true;
   1958 }
   1959 
   1960 /// Check the provided statement is allowed in a constexpr function
   1961 /// definition.
   1962 static bool
   1963 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
   1964                            SmallVectorImpl<SourceLocation> &ReturnStmts,
   1965                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
   1966                            Sema::CheckConstexprKind Kind) {
   1967   // - its function-body shall be [...] a compound-statement that contains only
   1968   switch (S->getStmtClass()) {
   1969   case Stmt::NullStmtClass:
   1970     //   - null statements,
   1971     return true;
   1972 
   1973   case Stmt::DeclStmtClass:
   1974     //   - static_assert-declarations
   1975     //   - using-declarations,
   1976     //   - using-directives,
   1977     //   - typedef declarations and alias-declarations that do not define
   1978     //     classes or enumerations,
   1979     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
   1980       return false;
   1981     return true;
   1982 
   1983   case Stmt::ReturnStmtClass:
   1984     //   - and exactly one return statement;
   1985     if (isa<CXXConstructorDecl>(Dcl)) {
   1986       // C++1y allows return statements in constexpr constructors.
   1987       if (!Cxx1yLoc.isValid())
   1988         Cxx1yLoc = S->getBeginLoc();
   1989       return true;
   1990     }
   1991 
   1992     ReturnStmts.push_back(S->getBeginLoc());
   1993     return true;
   1994 
   1995   case Stmt::CompoundStmtClass: {
   1996     // C++1y allows compound-statements.
   1997     if (!Cxx1yLoc.isValid())
   1998       Cxx1yLoc = S->getBeginLoc();
   1999 
   2000     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
   2001     for (auto *BodyIt : CompStmt->body()) {
   2002       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
   2003                                       Cxx1yLoc, Cxx2aLoc, Kind))
   2004         return false;
   2005     }
   2006     return true;
   2007   }
   2008 
   2009   case Stmt::AttributedStmtClass:
   2010     if (!Cxx1yLoc.isValid())
   2011       Cxx1yLoc = S->getBeginLoc();
   2012     return true;
   2013 
   2014   case Stmt::IfStmtClass: {
   2015     // C++1y allows if-statements.
   2016     if (!Cxx1yLoc.isValid())
   2017       Cxx1yLoc = S->getBeginLoc();
   2018 
   2019     IfStmt *If = cast<IfStmt>(S);
   2020     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
   2021                                     Cxx1yLoc, Cxx2aLoc, Kind))
   2022       return false;
   2023     if (If->getElse() &&
   2024         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
   2025                                     Cxx1yLoc, Cxx2aLoc, Kind))
   2026       return false;
   2027     return true;
   2028   }
   2029 
   2030   case Stmt::WhileStmtClass:
   2031   case Stmt::DoStmtClass:
   2032   case Stmt::ForStmtClass:
   2033   case Stmt::CXXForRangeStmtClass:
   2034   case Stmt::ContinueStmtClass:
   2035     // C++1y allows all of these. We don't allow them as extensions in C++11,
   2036     // because they don't make sense without variable mutation.
   2037     if (!SemaRef.getLangOpts().CPlusPlus14)
   2038       break;
   2039     if (!Cxx1yLoc.isValid())
   2040       Cxx1yLoc = S->getBeginLoc();
   2041     for (Stmt *SubStmt : S->children())
   2042       if (SubStmt &&
   2043           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
   2044                                       Cxx1yLoc, Cxx2aLoc, Kind))
   2045         return false;
   2046     return true;
   2047 
   2048   case Stmt::SwitchStmtClass:
   2049   case Stmt::CaseStmtClass:
   2050   case Stmt::DefaultStmtClass:
   2051   case Stmt::BreakStmtClass:
   2052     // C++1y allows switch-statements, and since they don't need variable
   2053     // mutation, we can reasonably allow them in C++11 as an extension.
   2054     if (!Cxx1yLoc.isValid())
   2055       Cxx1yLoc = S->getBeginLoc();
   2056     for (Stmt *SubStmt : S->children())
   2057       if (SubStmt &&
   2058           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
   2059                                       Cxx1yLoc, Cxx2aLoc, Kind))
   2060         return false;
   2061     return true;
   2062 
   2063   case Stmt::GCCAsmStmtClass:
   2064   case Stmt::MSAsmStmtClass:
   2065     // C++2a allows inline assembly statements.
   2066   case Stmt::CXXTryStmtClass:
   2067     if (Cxx2aLoc.isInvalid())
   2068       Cxx2aLoc = S->getBeginLoc();
   2069     for (Stmt *SubStmt : S->children()) {
   2070       if (SubStmt &&
   2071           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
   2072                                       Cxx1yLoc, Cxx2aLoc, Kind))
   2073         return false;
   2074     }
   2075     return true;
   2076 
   2077   case Stmt::CXXCatchStmtClass:
   2078     // Do not bother checking the language mode (already covered by the
   2079     // try block check).
   2080     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
   2081                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
   2082                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
   2083       return false;
   2084     return true;
   2085 
   2086   default:
   2087     if (!isa<Expr>(S))
   2088       break;
   2089 
   2090     // C++1y allows expression-statements.
   2091     if (!Cxx1yLoc.isValid())
   2092       Cxx1yLoc = S->getBeginLoc();
   2093     return true;
   2094   }
   2095 
   2096   if (Kind == Sema::CheckConstexprKind::Diagnose) {
   2097     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
   2098         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
   2099   }
   2100   return false;
   2101 }
   2102 
   2103 /// Check the body for the given constexpr function declaration only contains
   2104 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
   2105 ///
   2106 /// \return true if the body is OK, false if we have found or diagnosed a
   2107 /// problem.
   2108 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
   2109                                        Stmt *Body,
   2110                                        Sema::CheckConstexprKind Kind) {
   2111   SmallVector<SourceLocation, 4> ReturnStmts;
   2112 
   2113   if (isa<CXXTryStmt>(Body)) {
   2114     // C++11 [dcl.constexpr]p3:
   2115     //  The definition of a constexpr function shall satisfy the following
   2116     //  constraints: [...]
   2117     // - its function-body shall be = delete, = default, or a
   2118     //   compound-statement
   2119     //
   2120     // C++11 [dcl.constexpr]p4:
   2121     //  In the definition of a constexpr constructor, [...]
   2122     // - its function-body shall not be a function-try-block;
   2123     //
   2124     // This restriction is lifted in C++2a, as long as inner statements also
   2125     // apply the general constexpr rules.
   2126     switch (Kind) {
   2127     case Sema::CheckConstexprKind::CheckValid:
   2128       if (!SemaRef.getLangOpts().CPlusPlus2a)
   2129         return false;
   2130       break;
   2131 
   2132     case Sema::CheckConstexprKind::Diagnose:
   2133       SemaRef.Diag(Body->getBeginLoc(),
   2134            !SemaRef.getLangOpts().CPlusPlus2a
   2135                ? diag::ext_constexpr_function_try_block_cxx2a
   2136                : diag::warn_cxx17_compat_constexpr_function_try_block)
   2137           << isa<CXXConstructorDecl>(Dcl);
   2138       break;
   2139     }
   2140   }
   2141 
   2142   // - its function-body shall be [...] a compound-statement that contains only
   2143   //   [... list of cases ...]
   2144   //
   2145   // Note that walking the children here is enough to properly check for
   2146   // CompoundStmt and CXXTryStmt body.
   2147   SourceLocation Cxx1yLoc, Cxx2aLoc;
   2148   for (Stmt *SubStmt : Body->children()) {
   2149     if (SubStmt &&
   2150         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
   2151                                     Cxx1yLoc, Cxx2aLoc, Kind))
   2152       return false;
   2153   }
   2154 
   2155   if (Kind == Sema::CheckConstexprKind::CheckValid) {
   2156     // If this is only valid as an extension, report that we don't satisfy the
   2157     // constraints of the current language.
   2158     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) ||
   2159         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
   2160       return false;
   2161   } else if (Cxx2aLoc.isValid()) {
   2162     SemaRef.Diag(Cxx2aLoc,
   2163          SemaRef.getLangOpts().CPlusPlus2a
   2164            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
   2165            : diag::ext_constexpr_body_invalid_stmt_cxx2a)
   2166       << isa<CXXConstructorDecl>(Dcl);
   2167   } else if (Cxx1yLoc.isValid()) {
   2168     SemaRef.Diag(Cxx1yLoc,
   2169          SemaRef.getLangOpts().CPlusPlus14
   2170            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
   2171            : diag::ext_constexpr_body_invalid_stmt)
   2172       << isa<CXXConstructorDecl>(Dcl);
   2173   }
   2174 
   2175   if (const CXXConstructorDecl *Constructor
   2176         = dyn_cast<CXXConstructorDecl>(Dcl)) {
   2177     const CXXRecordDecl *RD = Constructor->getParent();
   2178     // DR1359:
   2179     // - every non-variant non-static data member and base class sub-object
   2180     //   shall be initialized;
   2181     // DR1460:
   2182     // - if the class is a union having variant members, exactly one of them
   2183     //   shall be initialized;
   2184     if (RD->isUnion()) {
   2185       if (Constructor->getNumCtorInitializers() == 0 &&
   2186           RD->hasVariantMembers()) {
   2187         if (Kind == Sema::CheckConstexprKind::Diagnose) {
   2188           SemaRef.Diag(
   2189               Dcl->getLocation(),
   2190               SemaRef.getLangOpts().CPlusPlus2a
   2191                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
   2192                   : diag::ext_constexpr_union_ctor_no_init);
   2193         } else if (!SemaRef.getLangOpts().CPlusPlus2a) {
   2194           return false;
   2195         }
   2196       }
   2197     } else if (!Constructor->isDependentContext() &&
   2198                !Constructor->isDelegatingConstructor()) {
   2199       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
   2200 
   2201       // Skip detailed checking if we have enough initializers, and we would
   2202       // allow at most one initializer per member.
   2203       bool AnyAnonStructUnionMembers = false;
   2204       unsigned Fields = 0;
   2205       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
   2206            E = RD->field_end(); I != E; ++I, ++Fields) {
   2207         if (I->isAnonymousStructOrUnion()) {
   2208           AnyAnonStructUnionMembers = true;
   2209           break;
   2210         }
   2211       }
   2212       // DR1460:
   2213       // - if the class is a union-like class, but is not a union, for each of
   2214       //   its anonymous union members having variant members, exactly one of
   2215       //   them shall be initialized;
   2216       if (AnyAnonStructUnionMembers ||
   2217           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
   2218         // Check initialization of non-static data members. Base classes are
   2219         // always initialized so do not need to be checked. Dependent bases
   2220         // might not have initializers in the member initializer list.
   2221         llvm::SmallSet<Decl*, 16> Inits;
   2222         for (const auto *I: Constructor->inits()) {
   2223           if (FieldDecl *FD = I->getMember())
   2224             Inits.insert(FD);
   2225           else if (IndirectFieldDecl *ID = I->getIndirectMember())
   2226             Inits.insert(ID->chain_begin(), ID->chain_end());
   2227         }
   2228 
   2229         bool Diagnosed = false;
   2230         for (auto *I : RD->fields())
   2231           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
   2232                                              Kind))
   2233             return false;
   2234       }
   2235     }
   2236   } else {
   2237     if (ReturnStmts.empty()) {
   2238       // C++1y doesn't require constexpr functions to contain a 'return'
   2239       // statement. We still do, unless the return type might be void, because
   2240       // otherwise if there's no return statement, the function cannot
   2241       // be used in a core constant expression.
   2242       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
   2243                 (Dcl->getReturnType()->isVoidType() ||
   2244                  Dcl->getReturnType()->isDependentType());
   2245       switch (Kind) {
   2246       case Sema::CheckConstexprKind::Diagnose:
   2247         SemaRef.Diag(Dcl->getLocation(),
   2248                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
   2249                         : diag::err_constexpr_body_no_return)
   2250             << Dcl->isConsteval();
   2251         if (!OK)
   2252           return false;
   2253         break;
   2254 
   2255       case Sema::CheckConstexprKind::CheckValid:
   2256         // The formal requirements don't include this rule in C++14, even
   2257         // though the "must be able to produce a constant expression" rules
   2258         // still imply it in some cases.
   2259         if (!SemaRef.getLangOpts().CPlusPlus14)
   2260           return false;
   2261         break;
   2262       }
   2263     } else if (ReturnStmts.size() > 1) {
   2264       switch (Kind) {
   2265       case Sema::CheckConstexprKind::Diagnose:
   2266         SemaRef.Diag(
   2267             ReturnStmts.back(),
   2268             SemaRef.getLangOpts().CPlusPlus14
   2269                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
   2270                 : diag::ext_constexpr_body_multiple_return);
   2271         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
   2272           SemaRef.Diag(ReturnStmts[I],
   2273                        diag::note_constexpr_body_previous_return);
   2274         break;
   2275 
   2276       case Sema::CheckConstexprKind::CheckValid:
   2277         if (!SemaRef.getLangOpts().CPlusPlus14)
   2278           return false;
   2279         break;
   2280       }
   2281     }
   2282   }
   2283 
   2284   // C++11 [dcl.constexpr]p5:
   2285   //   if no function argument values exist such that the function invocation
   2286   //   substitution would produce a constant expression, the program is
   2287   //   ill-formed; no diagnostic required.
   2288   // C++11 [dcl.constexpr]p3:
   2289   //   - every constructor call and implicit conversion used in initializing the
   2290   //     return value shall be one of those allowed in a constant expression.
   2291   // C++11 [dcl.constexpr]p4:
   2292   //   - every constructor involved in initializing non-static data members and
   2293   //     base class sub-objects shall be a constexpr constructor.
   2294   //
   2295   // Note that this rule is distinct from the "requirements for a constexpr
   2296   // function", so is not checked in CheckValid mode.
   2297   SmallVector<PartialDiagnosticAt, 8> Diags;
   2298   if (Kind == Sema::CheckConstexprKind::Diagnose &&
   2299       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
   2300     SemaRef.Diag(Dcl->getLocation(),
   2301                  diag::ext_constexpr_function_never_constant_expr)
   2302         << isa<CXXConstructorDecl>(Dcl);
   2303     for (size_t I = 0, N = Diags.size(); I != N; ++I)
   2304       SemaRef.Diag(Diags[I].first, Diags[I].second);
   2305     // Don't return false here: we allow this for compatibility in
   2306     // system headers.
   2307   }
   2308 
   2309   return true;
   2310 }
   2311 
   2312 /// Get the class that is directly named by the current context. This is the
   2313 /// class for which an unqualified-id in this scope could name a constructor
   2314 /// or destructor.
   2315 ///
   2316 /// If the scope specifier denotes a class, this will be that class.
   2317 /// If the scope specifier is empty, this will be the class whose
   2318 /// member-specification we are currently within. Otherwise, there
   2319 /// is no such class.
   2320 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
   2321   assert(getLangOpts().CPlusPlus && "No class names in C!");
   2322 
   2323   if (SS && SS->isInvalid())
   2324     return nullptr;
   2325 
   2326   if (SS && SS->isNotEmpty()) {
   2327     DeclContext *DC = computeDeclContext(*SS, true);
   2328     return dyn_cast_or_null<CXXRecordDecl>(DC);
   2329   }
   2330 
   2331   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
   2332 }
   2333 
   2334 /// isCurrentClassName - Determine whether the identifier II is the
   2335 /// name of the class type currently being defined. In the case of
   2336 /// nested classes, this will only return true if II is the name of
   2337 /// the innermost class.
   2338 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
   2339                               const CXXScopeSpec *SS) {
   2340   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
   2341   return CurDecl && &II == CurDecl->getIdentifier();
   2342 }
   2343 
   2344 /// Determine whether the identifier II is a typo for the name of
   2345 /// the class type currently being defined. If so, update it to the identifier
   2346 /// that should have been used.
   2347 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
   2348   assert(getLangOpts().CPlusPlus && "No class names in C!");
   2349 
   2350   if (!getLangOpts().SpellChecking)
   2351     return false;
   2352 
   2353   CXXRecordDecl *CurDecl;
   2354   if (SS && SS->isSet() && !SS->isInvalid()) {
   2355     DeclContext *DC = computeDeclContext(*SS, true);
   2356     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
   2357   } else
   2358     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
   2359 
   2360   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
   2361       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
   2362           < II->getLength()) {
   2363     II = CurDecl->getIdentifier();
   2364     return true;
   2365   }
   2366 
   2367   return false;
   2368 }
   2369 
   2370 /// Determine whether the given class is a base class of the given
   2371 /// class, including looking at dependent bases.
   2372 static bool findCircularInheritance(const CXXRecordDecl *Class,
   2373                                     const CXXRecordDecl *Current) {
   2374   SmallVector<const CXXRecordDecl*, 8> Queue;
   2375 
   2376   Class = Class->getCanonicalDecl();
   2377   while (true) {
   2378     for (const auto &I : Current->bases()) {
   2379       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
   2380       if (!Base)
   2381         continue;
   2382 
   2383       Base = Base->getDefinition();
   2384       if (!Base)
   2385         continue;
   2386 
   2387       if (Base->getCanonicalDecl() == Class)
   2388         return true;
   2389 
   2390       Queue.push_back(Base);
   2391     }
   2392 
   2393     if (Queue.empty())
   2394       return false;
   2395 
   2396     Current = Queue.pop_back_val();
   2397   }
   2398 
   2399   return false;
   2400 }
   2401 
   2402 /// Check the validity of a C++ base class specifier.
   2403 ///
   2404 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
   2405 /// and returns NULL otherwise.
   2406 CXXBaseSpecifier *
   2407 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
   2408                          SourceRange SpecifierRange,
   2409                          bool Virtual, AccessSpecifier Access,
   2410                          TypeSourceInfo *TInfo,
   2411                          SourceLocation EllipsisLoc) {
   2412   QualType BaseType = TInfo->getType();
   2413 
   2414   // C++ [class.union]p1:
   2415   //   A union shall not have base classes.
   2416   if (Class->isUnion()) {
   2417     Diag(Class->getLocation(), diag::err_base_clause_on_union)
   2418       << SpecifierRange;
   2419     return nullptr;
   2420   }
   2421 
   2422   if (EllipsisLoc.isValid() &&
   2423       !TInfo->getType()->containsUnexpandedParameterPack()) {
   2424     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
   2425       << TInfo->getTypeLoc().getSourceRange();
   2426     EllipsisLoc = SourceLocation();
   2427   }
   2428 
   2429   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
   2430 
   2431   if (BaseType->isDependentType()) {
   2432     // Make sure that we don't have circular inheritance among our dependent
   2433     // bases. For non-dependent bases, the check for completeness below handles
   2434     // this.
   2435     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
   2436       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
   2437           ((BaseDecl = BaseDecl->getDefinition()) &&
   2438            findCircularInheritance(Class, BaseDecl))) {
   2439         Diag(BaseLoc, diag::err_circular_inheritance)
   2440           << BaseType << Context.getTypeDeclType(Class);
   2441 
   2442         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
   2443           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
   2444             << BaseType;
   2445 
   2446         return nullptr;
   2447       }
   2448     }
   2449 
   2450     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
   2451                                           Class->getTagKind() == TTK_Class,
   2452                                           Access, TInfo, EllipsisLoc);
   2453   }
   2454 
   2455   // Base specifiers must be record types.
   2456   if (!BaseType->isRecordType()) {
   2457     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
   2458     return nullptr;
   2459   }
   2460 
   2461   // C++ [class.union]p1:
   2462   //   A union shall not be used as a base class.
   2463   if (BaseType->isUnionType()) {
   2464     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
   2465     return nullptr;
   2466   }
   2467 
   2468   // For the MS ABI, propagate DLL attributes to base class templates.
   2469   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
   2470     if (Attr *ClassAttr = getDLLAttr(Class)) {
   2471       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
   2472               BaseType->getAsCXXRecordDecl())) {
   2473         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
   2474                                             BaseLoc);
   2475       }
   2476     }
   2477   }
   2478 
   2479   // C++ [class.derived]p2:
   2480   //   The class-name in a base-specifier shall not be an incompletely
   2481   //   defined class.
   2482   if (RequireCompleteType(BaseLoc, BaseType,
   2483                           diag::err_incomplete_base_class, SpecifierRange)) {
   2484     Class->setInvalidDecl();
   2485     return nullptr;
   2486   }
   2487 
   2488   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
   2489   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
   2490   assert(BaseDecl && "Record type has no declaration");
   2491   BaseDecl = BaseDecl->getDefinition();
   2492   assert(BaseDecl && "Base type is not incomplete, but has no definition");
   2493   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
   2494   assert(CXXBaseDecl && "Base type is not a C++ type");
   2495 
   2496   // Microsoft docs say:
   2497   // "If a base-class has a code_seg attribute, derived classes must have the
   2498   // same attribute."
   2499   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
   2500   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
   2501   if ((DerivedCSA || BaseCSA) &&
   2502       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
   2503     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
   2504     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
   2505       << CXXBaseDecl;
   2506     return nullptr;
   2507   }
   2508 
   2509   // A class which contains a flexible array member is not suitable for use as a
   2510   // base class:
   2511   //   - If the layout determines that a base comes before another base,
   2512   //     the flexible array member would index into the subsequent base.
   2513   //   - If the layout determines that base comes before the derived class,
   2514   //     the flexible array member would index into the derived class.
   2515   if (CXXBaseDecl->hasFlexibleArrayMember()) {
   2516     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
   2517       << CXXBaseDecl->getDeclName();
   2518     return nullptr;
   2519   }
   2520 
   2521   // C++ [class]p3:
   2522   //   If a class is marked final and it appears as a base-type-specifier in
   2523   //   base-clause, the program is ill-formed.
   2524   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
   2525     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
   2526       << CXXBaseDecl->getDeclName()
   2527       << FA->isSpelledAsSealed();
   2528     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
   2529         << CXXBaseDecl->getDeclName() << FA->getRange();
   2530     return nullptr;
   2531   }
   2532 
   2533   if (BaseDecl->isInvalidDecl())
   2534     Class->setInvalidDecl();
   2535 
   2536   // Create the base specifier.
   2537   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
   2538                                         Class->getTagKind() == TTK_Class,
   2539                                         Access, TInfo, EllipsisLoc);
   2540 }
   2541 
   2542 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
   2543 /// one entry in the base class list of a class specifier, for
   2544 /// example:
   2545 ///    class foo : public bar, virtual private baz {
   2546 /// 'public bar' and 'virtual private baz' are each base-specifiers.
   2547 BaseResult
   2548 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
   2549                          ParsedAttributes &Attributes,
   2550                          bool Virtual, AccessSpecifier Access,
   2551                          ParsedType basetype, SourceLocation BaseLoc,
   2552                          SourceLocation EllipsisLoc) {
   2553   if (!classdecl)
   2554     return true;
   2555 
   2556   AdjustDeclIfTemplate(classdecl);
   2557   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
   2558   if (!Class)
   2559     return true;
   2560 
   2561   // We haven't yet attached the base specifiers.
   2562   Class->setIsParsingBaseSpecifiers();
   2563 
   2564   // We do not support any C++11 attributes on base-specifiers yet.
   2565   // Diagnose any attributes we see.
   2566   for (const ParsedAttr &AL : Attributes) {
   2567     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
   2568       continue;
   2569     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
   2570                           ? (unsigned)diag::warn_unknown_attribute_ignored
   2571                           : (unsigned)diag::err_base_specifier_attribute)
   2572         << AL;
   2573   }
   2574 
   2575   TypeSourceInfo *TInfo = nullptr;
   2576   GetTypeFromParser(basetype, &TInfo);
   2577 
   2578   if (EllipsisLoc.isInvalid() &&
   2579       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
   2580                                       UPPC_BaseType))
   2581     return true;
   2582 
   2583   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
   2584                                                       Virtual, Access, TInfo,
   2585                                                       EllipsisLoc))
   2586     return BaseSpec;
   2587   else
   2588     Class->setInvalidDecl();
   2589 
   2590   return true;
   2591 }
   2592 
   2593 /// Use small set to collect indirect bases.  As this is only used
   2594 /// locally, there's no need to abstract the small size parameter.
   2595 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
   2596 
   2597 /// Recursively add the bases of Type.  Don't add Type itself.
   2598 static void
   2599 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
   2600                   const QualType &Type)
   2601 {
   2602   // Even though the incoming type is a base, it might not be
   2603   // a class -- it could be a template parm, for instance.
   2604   if (auto Rec = Type->getAs<RecordType>()) {
   2605     auto Decl = Rec->getAsCXXRecordDecl();
   2606 
   2607     // Iterate over its bases.
   2608     for (const auto &BaseSpec : Decl->bases()) {
   2609       QualType Base = Context.getCanonicalType(BaseSpec.getType())
   2610         .getUnqualifiedType();
   2611       if (Set.insert(Base).second)
   2612         // If we've not already seen it, recurse.
   2613         NoteIndirectBases(Context, Set, Base);
   2614     }
   2615   }
   2616 }
   2617 
   2618 /// Performs the actual work of attaching the given base class
   2619 /// specifiers to a C++ class.
   2620 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
   2621                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
   2622  if (Bases.empty())
   2623     return false;
   2624 
   2625   // Used to keep track of which base types we have already seen, so
   2626   // that we can properly diagnose redundant direct base types. Note
   2627   // that the key is always the unqualified canonical type of the base
   2628   // class.
   2629   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
   2630 
   2631   // Used to track indirect bases so we can see if a direct base is
   2632   // ambiguous.
   2633   IndirectBaseSet IndirectBaseTypes;
   2634 
   2635   // Copy non-redundant base specifiers into permanent storage.
   2636   unsigned NumGoodBases = 0;
   2637   bool Invalid = false;
   2638   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
   2639     QualType NewBaseType
   2640       = Context.getCanonicalType(Bases[idx]->getType());
   2641     NewBaseType = NewBaseType.getLocalUnqualifiedType();
   2642 
   2643     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
   2644     if (KnownBase) {
   2645       // C++ [class.mi]p3:
   2646       //   A class shall not be specified as a direct base class of a
   2647       //   derived class more than once.
   2648       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
   2649           << KnownBase->getType() << Bases[idx]->getSourceRange();
   2650 
   2651       // Delete the duplicate base class specifier; we're going to
   2652       // overwrite its pointer later.
   2653       Context.Deallocate(Bases[idx]);
   2654 
   2655       Invalid = true;
   2656     } else {
   2657       // Okay, add this new base class.
   2658       KnownBase = Bases[idx];
   2659       Bases[NumGoodBases++] = Bases[idx];
   2660 
   2661       // Note this base's direct & indirect bases, if there could be ambiguity.
   2662       if (Bases.size() > 1)
   2663         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
   2664 
   2665       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
   2666         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
   2667         if (Class->isInterface() &&
   2668               (!RD->isInterfaceLike() ||
   2669                KnownBase->getAccessSpecifier() != AS_public)) {
   2670           // The Microsoft extension __interface does not permit bases that
   2671           // are not themselves public interfaces.
   2672           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
   2673               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
   2674               << RD->getSourceRange();
   2675           Invalid = true;
   2676         }
   2677         if (RD->hasAttr<WeakAttr>())
   2678           Class->addAttr(WeakAttr::CreateImplicit(Context));
   2679       }
   2680     }
   2681   }
   2682 
   2683   // Attach the remaining base class specifiers to the derived class.
   2684   Class->setBases(Bases.data(), NumGoodBases);
   2685 
   2686   // Check that the only base classes that are duplicate are virtual.
   2687   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
   2688     // Check whether this direct base is inaccessible due to ambiguity.
   2689     QualType BaseType = Bases[idx]->getType();
   2690 
   2691     // Skip all dependent types in templates being used as base specifiers.
   2692     // Checks below assume that the base specifier is a CXXRecord.
   2693     if (BaseType->isDependentType())
   2694       continue;
   2695 
   2696     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
   2697       .getUnqualifiedType();
   2698 
   2699     if (IndirectBaseTypes.count(CanonicalBase)) {
   2700       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   2701                          /*DetectVirtual=*/true);
   2702       bool found
   2703         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
   2704       assert(found);
   2705       (void)found;
   2706 
   2707       if (Paths.isAmbiguous(CanonicalBase))
   2708         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
   2709             << BaseType << getAmbiguousPathsDisplayString(Paths)
   2710             << Bases[idx]->getSourceRange();
   2711       else
   2712         assert(Bases[idx]->isVirtual());
   2713     }
   2714 
   2715     // Delete the base class specifier, since its data has been copied
   2716     // into the CXXRecordDecl.
   2717     Context.Deallocate(Bases[idx]);
   2718   }
   2719 
   2720   return Invalid;
   2721 }
   2722 
   2723 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
   2724 /// class, after checking whether there are any duplicate base
   2725 /// classes.
   2726 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
   2727                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
   2728   if (!ClassDecl || Bases.empty())
   2729     return;
   2730 
   2731   AdjustDeclIfTemplate(ClassDecl);
   2732   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
   2733 }
   2734 
   2735 /// Determine whether the type \p Derived is a C++ class that is
   2736 /// derived from the type \p Base.
   2737 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
   2738   if (!getLangOpts().CPlusPlus)
   2739     return false;
   2740 
   2741   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
   2742   if (!DerivedRD)
   2743     return false;
   2744 
   2745   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
   2746   if (!BaseRD)
   2747     return false;
   2748 
   2749   // If either the base or the derived type is invalid, don't try to
   2750   // check whether one is derived from the other.
   2751   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
   2752     return false;
   2753 
   2754   // FIXME: In a modules build, do we need the entire path to be visible for us
   2755   // to be able to use the inheritance relationship?
   2756   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
   2757     return false;
   2758 
   2759   return DerivedRD->isDerivedFrom(BaseRD);
   2760 }
   2761 
   2762 /// Determine whether the type \p Derived is a C++ class that is
   2763 /// derived from the type \p Base.
   2764 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
   2765                          CXXBasePaths &Paths) {
   2766   if (!getLangOpts().CPlusPlus)
   2767     return false;
   2768 
   2769   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
   2770   if (!DerivedRD)
   2771     return false;
   2772 
   2773   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
   2774   if (!BaseRD)
   2775     return false;
   2776 
   2777   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
   2778     return false;
   2779 
   2780   return DerivedRD->isDerivedFrom(BaseRD, Paths);
   2781 }
   2782 
   2783 static void BuildBasePathArray(const CXXBasePath &Path,
   2784                                CXXCastPath &BasePathArray) {
   2785   // We first go backward and check if we have a virtual base.
   2786   // FIXME: It would be better if CXXBasePath had the base specifier for
   2787   // the nearest virtual base.
   2788   unsigned Start = 0;
   2789   for (unsigned I = Path.size(); I != 0; --I) {
   2790     if (Path[I - 1].Base->isVirtual()) {
   2791       Start = I - 1;
   2792       break;
   2793     }
   2794   }
   2795 
   2796   // Now add all bases.
   2797   for (unsigned I = Start, E = Path.size(); I != E; ++I)
   2798     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
   2799 }
   2800 
   2801 
   2802 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
   2803                               CXXCastPath &BasePathArray) {
   2804   assert(BasePathArray.empty() && "Base path array must be empty!");
   2805   assert(Paths.isRecordingPaths() && "Must record paths!");
   2806   return ::BuildBasePathArray(Paths.front(), BasePathArray);
   2807 }
   2808 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
   2809 /// conversion (where Derived and Base are class types) is
   2810 /// well-formed, meaning that the conversion is unambiguous (and
   2811 /// that all of the base classes are accessible). Returns true
   2812 /// and emits a diagnostic if the code is ill-formed, returns false
   2813 /// otherwise. Loc is the location where this routine should point to
   2814 /// if there is an error, and Range is the source range to highlight
   2815 /// if there is an error.
   2816 ///
   2817 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
   2818 /// diagnostic for the respective type of error will be suppressed, but the
   2819 /// check for ill-formed code will still be performed.
   2820 bool
   2821 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
   2822                                    unsigned InaccessibleBaseID,
   2823                                    unsigned AmbigiousBaseConvID,
   2824                                    SourceLocation Loc, SourceRange Range,
   2825                                    DeclarationName Name,
   2826                                    CXXCastPath *BasePath,
   2827                                    bool IgnoreAccess) {
   2828   // First, determine whether the path from Derived to Base is
   2829   // ambiguous. This is slightly more expensive than checking whether
   2830   // the Derived to Base conversion exists, because here we need to
   2831   // explore multiple paths to determine if there is an ambiguity.
   2832   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   2833                      /*DetectVirtual=*/false);
   2834   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
   2835   if (!DerivationOkay)
   2836     return true;
   2837 
   2838   const CXXBasePath *Path = nullptr;
   2839   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
   2840     Path = &Paths.front();
   2841 
   2842   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
   2843   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
   2844   // user to access such bases.
   2845   if (!Path && getLangOpts().MSVCCompat) {
   2846     for (const CXXBasePath &PossiblePath : Paths) {
   2847       if (PossiblePath.size() == 1) {
   2848         Path = &PossiblePath;
   2849         if (AmbigiousBaseConvID)
   2850           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
   2851               << Base << Derived << Range;
   2852         break;
   2853       }
   2854     }
   2855   }
   2856 
   2857   if (Path) {
   2858     if (!IgnoreAccess) {
   2859       // Check that the base class can be accessed.
   2860       switch (
   2861           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
   2862       case AR_inaccessible:
   2863         return true;
   2864       case AR_accessible:
   2865       case AR_dependent:
   2866       case AR_delayed:
   2867         break;
   2868       }
   2869     }
   2870 
   2871     // Build a base path if necessary.
   2872     if (BasePath)
   2873       ::BuildBasePathArray(*Path, *BasePath);
   2874     return false;
   2875   }
   2876 
   2877   if (AmbigiousBaseConvID) {
   2878     // We know that the derived-to-base conversion is ambiguous, and
   2879     // we're going to produce a diagnostic. Perform the derived-to-base
   2880     // search just one more time to compute all of the possible paths so
   2881     // that we can print them out. This is more expensive than any of
   2882     // the previous derived-to-base checks we've done, but at this point
   2883     // performance isn't as much of an issue.
   2884     Paths.clear();
   2885     Paths.setRecordingPaths(true);
   2886     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
   2887     assert(StillOkay && "Can only be used with a derived-to-base conversion");
   2888     (void)StillOkay;
   2889 
   2890     // Build up a textual representation of the ambiguous paths, e.g.,
   2891     // D -> B -> A, that will be used to illustrate the ambiguous
   2892     // conversions in the diagnostic. We only print one of the paths
   2893     // to each base class subobject.
   2894     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
   2895 
   2896     Diag(Loc, AmbigiousBaseConvID)
   2897     << Derived << Base << PathDisplayStr << Range << Name;
   2898   }
   2899   return true;
   2900 }
   2901 
   2902 bool
   2903 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
   2904                                    SourceLocation Loc, SourceRange Range,
   2905                                    CXXCastPath *BasePath,
   2906                                    bool IgnoreAccess) {
   2907   return CheckDerivedToBaseConversion(
   2908       Derived, Base, diag::err_upcast_to_inaccessible_base,
   2909       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
   2910       BasePath, IgnoreAccess);
   2911 }
   2912 
   2913 
   2914 /// Builds a string representing ambiguous paths from a
   2915 /// specific derived class to different subobjects of the same base
   2916 /// class.
   2917 ///
   2918 /// This function builds a string that can be used in error messages
   2919 /// to show the different paths that one can take through the
   2920 /// inheritance hierarchy to go from the derived class to different
   2921 /// subobjects of a base class. The result looks something like this:
   2922 /// @code
   2923 /// struct D -> struct B -> struct A
   2924 /// struct D -> struct C -> struct A
   2925 /// @endcode
   2926 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
   2927   std::string PathDisplayStr;
   2928   std::set<unsigned> DisplayedPaths;
   2929   for (CXXBasePaths::paths_iterator Path = Paths.begin();
   2930        Path != Paths.end(); ++Path) {
   2931     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
   2932       // We haven't displayed a path to this particular base
   2933       // class subobject yet.
   2934       PathDisplayStr += "\n    ";
   2935       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
   2936       for (CXXBasePath::const_iterator Element = Path->begin();
   2937            Element != Path->end(); ++Element)
   2938         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
   2939     }
   2940   }
   2941 
   2942   return PathDisplayStr;
   2943 }
   2944 
   2945 //===----------------------------------------------------------------------===//
   2946 // C++ class member Handling
   2947 //===----------------------------------------------------------------------===//
   2948 
   2949 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
   2950 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
   2951                                 SourceLocation ColonLoc,
   2952                                 const ParsedAttributesView &Attrs) {
   2953   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
   2954   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
   2955                                                   ASLoc, ColonLoc);
   2956   CurContext->addHiddenDecl(ASDecl);
   2957   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
   2958 }
   2959 
   2960 /// CheckOverrideControl - Check C++11 override control semantics.
   2961 void Sema::CheckOverrideControl(NamedDecl *D) {
   2962   if (D->isInvalidDecl())
   2963     return;
   2964 
   2965   // We only care about "override" and "final" declarations.
   2966   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
   2967     return;
   2968 
   2969   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
   2970 
   2971   // We can't check dependent instance methods.
   2972   if (MD && MD->isInstance() &&
   2973       (MD->getParent()->hasAnyDependentBases() ||
   2974        MD->getType()->isDependentType()))
   2975     return;
   2976 
   2977   if (MD && !MD->isVirtual()) {
   2978     // If we have a non-virtual method, check if if hides a virtual method.
   2979     // (In that case, it's most likely the method has the wrong type.)
   2980     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
   2981     FindHiddenVirtualMethods(MD, OverloadedMethods);
   2982 
   2983     if (!OverloadedMethods.empty()) {
   2984       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
   2985         Diag(OA->getLocation(),
   2986              diag::override_keyword_hides_virtual_member_function)
   2987           << "override" << (OverloadedMethods.size() > 1);
   2988       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
   2989         Diag(FA->getLocation(),
   2990              diag::override_keyword_hides_virtual_member_function)
   2991           << (FA->isSpelledAsSealed() ? "sealed" : "final")
   2992           << (OverloadedMethods.size() > 1);
   2993       }
   2994       NoteHiddenVirtualMethods(MD, OverloadedMethods);
   2995       MD->setInvalidDecl();
   2996       return;
   2997     }
   2998     // Fall through into the general case diagnostic.
   2999     // FIXME: We might want to attempt typo correction here.
   3000   }
   3001 
   3002   if (!MD || !MD->isVirtual()) {
   3003     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
   3004       Diag(OA->getLocation(),
   3005            diag::override_keyword_only_allowed_on_virtual_member_functions)
   3006         << "override" << FixItHint::CreateRemoval(OA->getLocation());
   3007       D->dropAttr<OverrideAttr>();
   3008     }
   3009     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
   3010       Diag(FA->getLocation(),
   3011            diag::override_keyword_only_allowed_on_virtual_member_functions)
   3012         << (FA->isSpelledAsSealed() ? "sealed" : "final")
   3013         << FixItHint::CreateRemoval(FA->getLocation());
   3014       D->dropAttr<FinalAttr>();
   3015     }
   3016     return;
   3017   }
   3018 
   3019   // C++11 [class.virtual]p5:
   3020   //   If a function is marked with the virt-specifier override and
   3021   //   does not override a member function of a base class, the program is
   3022   //   ill-formed.
   3023   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
   3024   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
   3025     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
   3026       << MD->getDeclName();
   3027 }
   3028 
   3029 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
   3030   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
   3031     return;
   3032   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
   3033   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
   3034     return;
   3035 
   3036   SourceLocation Loc = MD->getLocation();
   3037   SourceLocation SpellingLoc = Loc;
   3038   if (getSourceManager().isMacroArgExpansion(Loc))
   3039     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
   3040   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
   3041   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
   3042       return;
   3043 
   3044   if (MD->size_overridden_methods() > 0) {
   3045     unsigned DiagID = isa<CXXDestructorDecl>(MD)
   3046                           ? diag::warn_destructor_marked_not_override_overriding
   3047                           : diag::warn_function_marked_not_override_overriding;
   3048     Diag(MD->getLocation(), DiagID) << MD->getDeclName();
   3049     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
   3050     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
   3051   }
   3052 }
   3053 
   3054 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
   3055 /// function overrides a virtual member function marked 'final', according to
   3056 /// C++11 [class.virtual]p4.
   3057 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
   3058                                                   const CXXMethodDecl *Old) {
   3059   FinalAttr *FA = Old->getAttr<FinalAttr>();
   3060   if (!FA)
   3061     return false;
   3062 
   3063   Diag(New->getLocation(), diag::err_final_function_overridden)
   3064     << New->getDeclName()
   3065     << FA->isSpelledAsSealed();
   3066   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
   3067   return true;
   3068 }
   3069 
   3070 static bool InitializationHasSideEffects(const FieldDecl &FD) {
   3071   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
   3072   // FIXME: Destruction of ObjC lifetime types has side-effects.
   3073   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
   3074     return !RD->isCompleteDefinition() ||
   3075            !RD->hasTrivialDefaultConstructor() ||
   3076            !RD->hasTrivialDestructor();
   3077   return false;
   3078 }
   3079 
   3080 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
   3081   ParsedAttributesView::const_iterator Itr =
   3082       llvm::find_if(list, [](const ParsedAttr &AL) {
   3083         return AL.isDeclspecPropertyAttribute();
   3084       });
   3085   if (Itr != list.end())
   3086     return &*Itr;
   3087   return nullptr;
   3088 }
   3089 
   3090 // Check if there is a field shadowing.
   3091 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
   3092                                       DeclarationName FieldName,
   3093                                       const CXXRecordDecl *RD,
   3094                                       bool DeclIsField) {
   3095   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
   3096     return;
   3097 
   3098   // To record a shadowed field in a base
   3099   std::map<CXXRecordDecl*, NamedDecl*> Bases;
   3100   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
   3101                            CXXBasePath &Path) {
   3102     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
   3103     // Record an ambiguous path directly
   3104     if (Bases.find(Base) != Bases.end())
   3105       return true;
   3106     for (const auto Field : Base->lookup(FieldName)) {
   3107       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
   3108           Field->getAccess() != AS_private) {
   3109         assert(Field->getAccess() != AS_none);
   3110         assert(Bases.find(Base) == Bases.end());
   3111         Bases[Base] = Field;
   3112         return true;
   3113       }
   3114     }
   3115     return false;
   3116   };
   3117 
   3118   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   3119                      /*DetectVirtual=*/true);
   3120   if (!RD->lookupInBases(FieldShadowed, Paths))
   3121     return;
   3122 
   3123   for (const auto &P : Paths) {
   3124     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
   3125     auto It = Bases.find(Base);
   3126     // Skip duplicated bases
   3127     if (It == Bases.end())
   3128       continue;
   3129     auto BaseField = It->second;
   3130     assert(BaseField->getAccess() != AS_private);
   3131     if (AS_none !=
   3132         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
   3133       Diag(Loc, diag::warn_shadow_field)
   3134         << FieldName << RD << Base << DeclIsField;
   3135       Diag(BaseField->getLocation(), diag::note_shadow_field);
   3136       Bases.erase(It);
   3137     }
   3138   }
   3139 }
   3140 
   3141 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
   3142 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
   3143 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
   3144 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
   3145 /// present (but parsing it has been deferred).
   3146 NamedDecl *
   3147 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
   3148                                MultiTemplateParamsArg TemplateParameterLists,
   3149                                Expr *BW, const VirtSpecifiers &VS,
   3150                                InClassInitStyle InitStyle) {
   3151   const DeclSpec &DS = D.getDeclSpec();
   3152   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
   3153   DeclarationName Name = NameInfo.getName();
   3154   SourceLocation Loc = NameInfo.getLoc();
   3155 
   3156   // For anonymous bitfields, the location should point to the type.
   3157   if (Loc.isInvalid())
   3158     Loc = D.getBeginLoc();
   3159 
   3160   Expr *BitWidth = static_cast<Expr*>(BW);
   3161 
   3162   assert(isa<CXXRecordDecl>(CurContext));
   3163   assert(!DS.isFriendSpecified());
   3164 
   3165   bool isFunc = D.isDeclarationOfFunction();
   3166   const ParsedAttr *MSPropertyAttr =
   3167       getMSPropertyAttr(D.getDeclSpec().getAttributes());
   3168 
   3169   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
   3170     // The Microsoft extension __interface only permits public member functions
   3171     // and prohibits constructors, destructors, operators, non-public member
   3172     // functions, static methods and data members.
   3173     unsigned InvalidDecl;
   3174     bool ShowDeclName = true;
   3175     if (!isFunc &&
   3176         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
   3177       InvalidDecl = 0;
   3178     else if (!isFunc)
   3179       InvalidDecl = 1;
   3180     else if (AS != AS_public)
   3181       InvalidDecl = 2;
   3182     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
   3183       InvalidDecl = 3;
   3184     else switch (Name.getNameKind()) {
   3185       case DeclarationName::CXXConstructorName:
   3186         InvalidDecl = 4;
   3187         ShowDeclName = false;
   3188         break;
   3189 
   3190       case DeclarationName::CXXDestructorName:
   3191         InvalidDecl = 5;
   3192         ShowDeclName = false;
   3193         break;
   3194 
   3195       case DeclarationName::CXXOperatorName:
   3196       case DeclarationName::CXXConversionFunctionName:
   3197         InvalidDecl = 6;
   3198         break;
   3199 
   3200       default:
   3201         InvalidDecl = 0;
   3202         break;
   3203     }
   3204 
   3205     if (InvalidDecl) {
   3206       if (ShowDeclName)
   3207         Diag(Loc, diag::err_invalid_member_in_interface)
   3208           << (InvalidDecl-1) << Name;
   3209       else
   3210         Diag(Loc, diag::err_invalid_member_in_interface)
   3211           << (InvalidDecl-1) << "";
   3212       return nullptr;
   3213     }
   3214   }
   3215 
   3216   // C++ 9.2p6: A member shall not be declared to have automatic storage
   3217   // duration (auto, register) or with the extern storage-class-specifier.
   3218   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
   3219   // data members and cannot be applied to names declared const or static,
   3220   // and cannot be applied to reference members.
   3221   switch (DS.getStorageClassSpec()) {
   3222   case DeclSpec::SCS_unspecified:
   3223   case DeclSpec::SCS_typedef:
   3224   case DeclSpec::SCS_static:
   3225     break;
   3226   case DeclSpec::SCS_mutable:
   3227     if (isFunc) {
   3228       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
   3229 
   3230       // FIXME: It would be nicer if the keyword was ignored only for this
   3231       // declarator. Otherwise we could get follow-up errors.
   3232       D.getMutableDeclSpec().ClearStorageClassSpecs();
   3233     }
   3234     break;
   3235   default:
   3236     Diag(DS.getStorageClassSpecLoc(),
   3237          diag::err_storageclass_invalid_for_member);
   3238     D.getMutableDeclSpec().ClearStorageClassSpecs();
   3239     break;
   3240   }
   3241 
   3242   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
   3243                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
   3244                       !isFunc);
   3245 
   3246   if (DS.hasConstexprSpecifier() && isInstField) {
   3247     SemaDiagnosticBuilder B =
   3248         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
   3249     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
   3250     if (InitStyle == ICIS_NoInit) {
   3251       B << 0 << 0;
   3252       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
   3253         B << FixItHint::CreateRemoval(ConstexprLoc);
   3254       else {
   3255         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
   3256         D.getMutableDeclSpec().ClearConstexprSpec();
   3257         const char *PrevSpec;
   3258         unsigned DiagID;
   3259         bool Failed = D.getMutableDeclSpec().SetTypeQual(
   3260             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
   3261         (void)Failed;
   3262         assert(!Failed && "Making a constexpr member const shouldn't fail");
   3263       }
   3264     } else {
   3265       B << 1;
   3266       const char *PrevSpec;
   3267       unsigned DiagID;
   3268       if (D.getMutableDeclSpec().SetStorageClassSpec(
   3269           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
   3270           Context.getPrintingPolicy())) {
   3271         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
   3272                "This is the only DeclSpec that should fail to be applied");
   3273         B << 1;
   3274       } else {
   3275         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
   3276         isInstField = false;
   3277       }
   3278     }
   3279   }
   3280 
   3281   NamedDecl *Member;
   3282   if (isInstField) {
   3283     CXXScopeSpec &SS = D.getCXXScopeSpec();
   3284 
   3285     // Data members must have identifiers for names.
   3286     if (!Name.isIdentifier()) {
   3287       Diag(Loc, diag::err_bad_variable_name)
   3288         << Name;
   3289       return nullptr;
   3290     }
   3291 
   3292     IdentifierInfo *II = Name.getAsIdentifierInfo();
   3293 
   3294     // Member field could not be with "template" keyword.
   3295     // So TemplateParameterLists should be empty in this case.
   3296     if (TemplateParameterLists.size()) {
   3297       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
   3298       if (TemplateParams->size()) {
   3299         // There is no such thing as a member field template.
   3300         Diag(D.getIdentifierLoc(), diag::err_template_member)
   3301             << II
   3302             << SourceRange(TemplateParams->getTemplateLoc(),
   3303                 TemplateParams->getRAngleLoc());
   3304       } else {
   3305         // There is an extraneous 'template<>' for this member.
   3306         Diag(TemplateParams->getTemplateLoc(),
   3307             diag::err_template_member_noparams)
   3308             << II
   3309             << SourceRange(TemplateParams->getTemplateLoc(),
   3310                 TemplateParams->getRAngleLoc());
   3311       }
   3312       return nullptr;
   3313     }
   3314 
   3315     if (SS.isSet() && !SS.isInvalid()) {
   3316       // The user provided a superfluous scope specifier inside a class
   3317       // definition:
   3318       //
   3319       // class X {
   3320       //   int X::member;
   3321       // };
   3322       if (DeclContext *DC = computeDeclContext(SS, false))
   3323         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
   3324                                      D.getName().getKind() ==
   3325                                          UnqualifiedIdKind::IK_TemplateId);
   3326       else
   3327         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
   3328           << Name << SS.getRange();
   3329 
   3330       SS.clear();
   3331     }
   3332 
   3333     if (MSPropertyAttr) {
   3334       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
   3335                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
   3336       if (!Member)
   3337         return nullptr;
   3338       isInstField = false;
   3339     } else {
   3340       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
   3341                                 BitWidth, InitStyle, AS);
   3342       if (!Member)
   3343         return nullptr;
   3344     }
   3345 
   3346     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
   3347   } else {
   3348     Member = HandleDeclarator(S, D, TemplateParameterLists);
   3349     if (!Member)
   3350       return nullptr;
   3351 
   3352     // Non-instance-fields can't have a bitfield.
   3353     if (BitWidth) {
   3354       if (Member->isInvalidDecl()) {
   3355         // don't emit another diagnostic.
   3356       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
   3357         // C++ 9.6p3: A bit-field shall not be a static member.
   3358         // "static member 'A' cannot be a bit-field"
   3359         Diag(Loc, diag::err_static_not_bitfield)
   3360           << Name << BitWidth->getSourceRange();
   3361       } else if (isa<TypedefDecl>(Member)) {
   3362         // "typedef member 'x' cannot be a bit-field"
   3363         Diag(Loc, diag::err_typedef_not_bitfield)
   3364           << Name << BitWidth->getSourceRange();
   3365       } else {
   3366         // A function typedef ("typedef int f(); f a;").
   3367         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
   3368         Diag(Loc, diag::err_not_integral_type_bitfield)
   3369           << Name << cast<ValueDecl>(Member)->getType()
   3370           << BitWidth->getSourceRange();
   3371       }
   3372 
   3373       BitWidth = nullptr;
   3374       Member->setInvalidDecl();
   3375     }
   3376 
   3377     NamedDecl *NonTemplateMember = Member;
   3378     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
   3379       NonTemplateMember = FunTmpl->getTemplatedDecl();
   3380     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
   3381       NonTemplateMember = VarTmpl->getTemplatedDecl();
   3382 
   3383     Member->setAccess(AS);
   3384 
   3385     // If we have declared a member function template or static data member
   3386     // template, set the access of the templated declaration as well.
   3387     if (NonTemplateMember != Member)
   3388       NonTemplateMember->setAccess(AS);
   3389 
   3390     // C++ [temp.deduct.guide]p3:
   3391     //   A deduction guide [...] for a member class template [shall be
   3392     //   declared] with the same access [as the template].
   3393     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
   3394       auto *TD = DG->getDeducedTemplate();
   3395       // Access specifiers are only meaningful if both the template and the
   3396       // deduction guide are from the same scope.
   3397       if (AS != TD->getAccess() &&
   3398           TD->getDeclContext()->getRedeclContext()->Equals(
   3399               DG->getDeclContext()->getRedeclContext())) {
   3400         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
   3401         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
   3402             << TD->getAccess();
   3403         const AccessSpecDecl *LastAccessSpec = nullptr;
   3404         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
   3405           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
   3406             LastAccessSpec = AccessSpec;
   3407         }
   3408         assert(LastAccessSpec && "differing access with no access specifier");
   3409         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
   3410             << AS;
   3411       }
   3412     }
   3413   }
   3414 
   3415   if (VS.isOverrideSpecified())
   3416     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
   3417                                          AttributeCommonInfo::AS_Keyword));
   3418   if (VS.isFinalSpecified())
   3419     Member->addAttr(FinalAttr::Create(
   3420         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
   3421         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
   3422 
   3423   if (VS.getLastLocation().isValid()) {
   3424     // Update the end location of a method that has a virt-specifiers.
   3425     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
   3426       MD->setRangeEnd(VS.getLastLocation());
   3427   }
   3428 
   3429   CheckOverrideControl(Member);
   3430 
   3431   assert((Name || isInstField) && "No identifier for non-field ?");
   3432 
   3433   if (isInstField) {
   3434     FieldDecl *FD = cast<FieldDecl>(Member);
   3435     FieldCollector->Add(FD);
   3436 
   3437     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
   3438       // Remember all explicit private FieldDecls that have a name, no side
   3439       // effects and are not part of a dependent type declaration.
   3440       if (!FD->isImplicit() && FD->getDeclName() &&
   3441           FD->getAccess() == AS_private &&
   3442           !FD->hasAttr<UnusedAttr>() &&
   3443           !FD->getParent()->isDependentContext() &&
   3444           !InitializationHasSideEffects(*FD))
   3445         UnusedPrivateFields.insert(FD);
   3446     }
   3447   }
   3448 
   3449   return Member;
   3450 }
   3451 
   3452 namespace {
   3453   class UninitializedFieldVisitor
   3454       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
   3455     Sema &S;
   3456     // List of Decls to generate a warning on.  Also remove Decls that become
   3457     // initialized.
   3458     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
   3459     // List of base classes of the record.  Classes are removed after their
   3460     // initializers.
   3461     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
   3462     // Vector of decls to be removed from the Decl set prior to visiting the
   3463     // nodes.  These Decls may have been initialized in the prior initializer.
   3464     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
   3465     // If non-null, add a note to the warning pointing back to the constructor.
   3466     const CXXConstructorDecl *Constructor;
   3467     // Variables to hold state when processing an initializer list.  When
   3468     // InitList is true, special case initialization of FieldDecls matching
   3469     // InitListFieldDecl.
   3470     bool InitList;
   3471     FieldDecl *InitListFieldDecl;
   3472     llvm::SmallVector<unsigned, 4> InitFieldIndex;
   3473 
   3474   public:
   3475     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
   3476     UninitializedFieldVisitor(Sema &S,
   3477                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
   3478                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
   3479       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
   3480         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
   3481 
   3482     // Returns true if the use of ME is not an uninitialized use.
   3483     bool IsInitListMemberExprInitialized(MemberExpr *ME,
   3484                                          bool CheckReferenceOnly) {
   3485       llvm::SmallVector<FieldDecl*, 4> Fields;
   3486       bool ReferenceField = false;
   3487       while (ME) {
   3488         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
   3489         if (!FD)
   3490           return false;
   3491         Fields.push_back(FD);
   3492         if (FD->getType()->isReferenceType())
   3493           ReferenceField = true;
   3494         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
   3495       }
   3496 
   3497       // Binding a reference to an uninitialized field is not an
   3498       // uninitialized use.
   3499       if (CheckReferenceOnly && !ReferenceField)
   3500         return true;
   3501 
   3502       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
   3503       // Discard the first field since it is the field decl that is being
   3504       // initialized.
   3505       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
   3506         UsedFieldIndex.push_back((*I)->getFieldIndex());
   3507       }
   3508 
   3509       for (auto UsedIter = UsedFieldIndex.begin(),
   3510                 UsedEnd = UsedFieldIndex.end(),
   3511                 OrigIter = InitFieldIndex.begin(),
   3512                 OrigEnd = InitFieldIndex.end();
   3513            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
   3514         if (*UsedIter < *OrigIter)
   3515           return true;
   3516         if (*UsedIter > *OrigIter)
   3517           break;
   3518       }
   3519 
   3520       return false;
   3521     }
   3522 
   3523     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
   3524                           bool AddressOf) {
   3525       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
   3526         return;
   3527 
   3528       // FieldME is the inner-most MemberExpr that is not an anonymous struct
   3529       // or union.
   3530       MemberExpr *FieldME = ME;
   3531 
   3532       bool AllPODFields = FieldME->getType().isPODType(S.Context);
   3533 
   3534       Expr *Base = ME;
   3535       while (MemberExpr *SubME =
   3536                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
   3537 
   3538         if (isa<VarDecl>(SubME->getMemberDecl()))
   3539           return;
   3540 
   3541         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
   3542           if (!FD->isAnonymousStructOrUnion())
   3543             FieldME = SubME;
   3544 
   3545         if (!FieldME->getType().isPODType(S.Context))
   3546           AllPODFields = false;
   3547 
   3548         Base = SubME->getBase();
   3549       }
   3550 
   3551       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
   3552         return;
   3553 
   3554       if (AddressOf && AllPODFields)
   3555         return;
   3556 
   3557       ValueDecl* FoundVD = FieldME->getMemberDecl();
   3558 
   3559       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
   3560         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
   3561           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
   3562         }
   3563 
   3564         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
   3565           QualType T = BaseCast->getType();
   3566           if (T->isPointerType() &&
   3567               BaseClasses.count(T->getPointeeType())) {
   3568             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
   3569                 << T->getPointeeType() << FoundVD;
   3570           }
   3571         }
   3572       }
   3573 
   3574       if (!Decls.count(FoundVD))
   3575         return;
   3576 
   3577       const bool IsReference = FoundVD->getType()->isReferenceType();
   3578 
   3579       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
   3580         // Special checking for initializer lists.
   3581         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
   3582           return;
   3583         }
   3584       } else {
   3585         // Prevent double warnings on use of unbounded references.
   3586         if (CheckReferenceOnly && !IsReference)
   3587           return;
   3588       }
   3589 
   3590       unsigned diag = IsReference
   3591           ? diag::warn_reference_field_is_uninit
   3592           : diag::warn_field_is_uninit;
   3593       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
   3594       if (Constructor)
   3595         S.Diag(Constructor->getLocation(),
   3596                diag::note_uninit_in_this_constructor)
   3597           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
   3598 
   3599     }
   3600 
   3601     void HandleValue(Expr *E, bool AddressOf) {
   3602       E = E->IgnoreParens();
   3603 
   3604       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
   3605         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
   3606                          AddressOf /*AddressOf*/);
   3607         return;
   3608       }
   3609 
   3610       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
   3611         Visit(CO->getCond());
   3612         HandleValue(CO->getTrueExpr(), AddressOf);
   3613         HandleValue(CO->getFalseExpr(), AddressOf);
   3614         return;
   3615       }
   3616 
   3617       if (BinaryConditionalOperator *BCO =
   3618               dyn_cast<BinaryConditionalOperator>(E)) {
   3619         Visit(BCO->getCond());
   3620         HandleValue(BCO->getFalseExpr(), AddressOf);
   3621         return;
   3622       }
   3623 
   3624       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
   3625         HandleValue(OVE->getSourceExpr(), AddressOf);
   3626         return;
   3627       }
   3628 
   3629       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
   3630         switch (BO->getOpcode()) {
   3631         default:
   3632           break;
   3633         case(BO_PtrMemD):
   3634         case(BO_PtrMemI):
   3635           HandleValue(BO->getLHS(), AddressOf);
   3636           Visit(BO->getRHS());
   3637           return;
   3638         case(BO_Comma):
   3639           Visit(BO->getLHS());
   3640           HandleValue(BO->getRHS(), AddressOf);
   3641           return;
   3642         }
   3643       }
   3644 
   3645       Visit(E);
   3646     }
   3647 
   3648     void CheckInitListExpr(InitListExpr *ILE) {
   3649       InitFieldIndex.push_back(0);
   3650       for (auto Child : ILE->children()) {
   3651         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
   3652           CheckInitListExpr(SubList);
   3653         } else {
   3654           Visit(Child);
   3655         }
   3656         ++InitFieldIndex.back();
   3657       }
   3658       InitFieldIndex.pop_back();
   3659     }
   3660 
   3661     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
   3662                           FieldDecl *Field, const Type *BaseClass) {
   3663       // Remove Decls that may have been initialized in the previous
   3664       // initializer.
   3665       for (ValueDecl* VD : DeclsToRemove)
   3666         Decls.erase(VD);
   3667       DeclsToRemove.clear();
   3668 
   3669       Constructor = FieldConstructor;
   3670       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
   3671 
   3672       if (ILE && Field) {
   3673         InitList = true;
   3674         InitListFieldDecl = Field;
   3675         InitFieldIndex.clear();
   3676         CheckInitListExpr(ILE);
   3677       } else {
   3678         InitList = false;
   3679         Visit(E);
   3680       }
   3681 
   3682       if (Field)
   3683         Decls.erase(Field);
   3684       if (BaseClass)
   3685         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
   3686     }
   3687 
   3688     void VisitMemberExpr(MemberExpr *ME) {
   3689       // All uses of unbounded reference fields will warn.
   3690       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
   3691     }
   3692 
   3693     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
   3694       if (E->getCastKind() == CK_LValueToRValue) {
   3695         HandleValue(E->getSubExpr(), false /*AddressOf*/);
   3696         return;
   3697       }
   3698 
   3699       Inherited::VisitImplicitCastExpr(E);
   3700     }
   3701 
   3702     void VisitCXXConstructExpr(CXXConstructExpr *E) {
   3703       if (E->getConstructor()->isCopyConstructor()) {
   3704         Expr *ArgExpr = E->getArg(0);
   3705         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
   3706           if (ILE->getNumInits() == 1)
   3707             ArgExpr = ILE->getInit(0);
   3708         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
   3709           if (ICE->getCastKind() == CK_NoOp)
   3710             ArgExpr = ICE->getSubExpr();
   3711         HandleValue(ArgExpr, false /*AddressOf*/);
   3712         return;
   3713       }
   3714       Inherited::VisitCXXConstructExpr(E);
   3715     }
   3716 
   3717     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
   3718       Expr *Callee = E->getCallee();
   3719       if (isa<MemberExpr>(Callee)) {
   3720         HandleValue(Callee, false /*AddressOf*/);
   3721         for (auto Arg : E->arguments())
   3722           Visit(Arg);
   3723         return;
   3724       }
   3725 
   3726       Inherited::VisitCXXMemberCallExpr(E);
   3727     }
   3728 
   3729     void VisitCallExpr(CallExpr *E) {
   3730       // Treat std::move as a use.
   3731       if (E->isCallToStdMove()) {
   3732         HandleValue(E->getArg(0), /*AddressOf=*/false);
   3733         return;
   3734       }
   3735 
   3736       Inherited::VisitCallExpr(E);
   3737     }
   3738 
   3739     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
   3740       Expr *Callee = E->getCallee();
   3741 
   3742       if (isa<UnresolvedLookupExpr>(Callee))
   3743         return Inherited::VisitCXXOperatorCallExpr(E);
   3744 
   3745       Visit(Callee);
   3746       for (auto Arg : E->arguments())
   3747         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
   3748     }
   3749 
   3750     void VisitBinaryOperator(BinaryOperator *E) {
   3751       // If a field assignment is detected, remove the field from the
   3752       // uninitiailized field set.
   3753       if (E->getOpcode() == BO_Assign)
   3754         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
   3755           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
   3756             if (!FD->getType()->isReferenceType())
   3757               DeclsToRemove.push_back(FD);
   3758 
   3759       if (E->isCompoundAssignmentOp()) {
   3760         HandleValue(E->getLHS(), false /*AddressOf*/);
   3761         Visit(E->getRHS());
   3762         return;
   3763       }
   3764 
   3765       Inherited::VisitBinaryOperator(E);
   3766     }
   3767 
   3768     void VisitUnaryOperator(UnaryOperator *E) {
   3769       if (E->isIncrementDecrementOp()) {
   3770         HandleValue(E->getSubExpr(), false /*AddressOf*/);
   3771         return;
   3772       }
   3773       if (E->getOpcode() == UO_AddrOf) {
   3774         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
   3775           HandleValue(ME->getBase(), true /*AddressOf*/);
   3776           return;
   3777         }
   3778       }
   3779 
   3780       Inherited::VisitUnaryOperator(E);
   3781     }
   3782   };
   3783 
   3784   // Diagnose value-uses of fields to initialize themselves, e.g.
   3785   //   foo(foo)
   3786   // where foo is not also a parameter to the constructor.
   3787   // Also diagnose across field uninitialized use such as
   3788   //   x(y), y(x)
   3789   // TODO: implement -Wuninitialized and fold this into that framework.
   3790   static void DiagnoseUninitializedFields(
   3791       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
   3792 
   3793     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
   3794                                            Constructor->getLocation())) {
   3795       return;
   3796     }
   3797 
   3798     if (Constructor->isInvalidDecl())
   3799       return;
   3800 
   3801     const CXXRecordDecl *RD = Constructor->getParent();
   3802 
   3803     if (RD->getDescribedClassTemplate())
   3804       return;
   3805 
   3806     // Holds fields that are uninitialized.
   3807     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
   3808 
   3809     // At the beginning, all fields are uninitialized.
   3810     for (auto *I : RD->decls()) {
   3811       if (auto *FD = dyn_cast<FieldDecl>(I)) {
   3812         UninitializedFields.insert(FD);
   3813       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
   3814         UninitializedFields.insert(IFD->getAnonField());
   3815       }
   3816     }
   3817 
   3818     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
   3819     for (auto I : RD->bases())
   3820       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
   3821 
   3822     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
   3823       return;
   3824 
   3825     UninitializedFieldVisitor UninitializedChecker(SemaRef,
   3826                                                    UninitializedFields,
   3827                                                    UninitializedBaseClasses);
   3828 
   3829     for (const auto *FieldInit : Constructor->inits()) {
   3830       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
   3831         break;
   3832 
   3833       Expr *InitExpr = FieldInit->getInit();
   3834       if (!InitExpr)
   3835         continue;
   3836 
   3837       if (CXXDefaultInitExpr *Default =
   3838               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
   3839         InitExpr = Default->getExpr();
   3840         if (!InitExpr)
   3841           continue;
   3842         // In class initializers will point to the constructor.
   3843         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
   3844                                               FieldInit->getAnyMember(),
   3845                                               FieldInit->getBaseClass());
   3846       } else {
   3847         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
   3848                                               FieldInit->getAnyMember(),
   3849                                               FieldInit->getBaseClass());
   3850       }
   3851     }
   3852   }
   3853 } // namespace
   3854 
   3855 /// Enter a new C++ default initializer scope. After calling this, the
   3856 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
   3857 /// parsing or instantiating the initializer failed.
   3858 void Sema::ActOnStartCXXInClassMemberInitializer() {
   3859   // Create a synthetic function scope to represent the call to the constructor
   3860   // that notionally surrounds a use of this initializer.
   3861   PushFunctionScope();
   3862 }
   3863 
   3864 /// This is invoked after parsing an in-class initializer for a
   3865 /// non-static C++ class member, and after instantiating an in-class initializer
   3866 /// in a class template. Such actions are deferred until the class is complete.
   3867 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
   3868                                                   SourceLocation InitLoc,
   3869                                                   Expr *InitExpr) {
   3870   // Pop the notional constructor scope we created earlier.
   3871   PopFunctionScopeInfo(nullptr, D);
   3872 
   3873   FieldDecl *FD = dyn_cast<FieldDecl>(D);
   3874   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
   3875          "must set init style when field is created");
   3876 
   3877   if (!InitExpr) {
   3878     D->setInvalidDecl();
   3879     if (FD)
   3880       FD->removeInClassInitializer();
   3881     return;
   3882   }
   3883 
   3884   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
   3885     FD->setInvalidDecl();
   3886     FD->removeInClassInitializer();
   3887     return;
   3888   }
   3889 
   3890   ExprResult Init = InitExpr;
   3891   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
   3892     InitializedEntity Entity =
   3893         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
   3894     InitializationKind Kind =
   3895         FD->getInClassInitStyle() == ICIS_ListInit
   3896             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
   3897                                                    InitExpr->getBeginLoc(),
   3898                                                    InitExpr->getEndLoc())
   3899             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
   3900     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
   3901     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
   3902     if (Init.isInvalid()) {
   3903       FD->setInvalidDecl();
   3904       return;
   3905     }
   3906   }
   3907 
   3908   // C++11 [class.base.init]p7:
   3909   //   The initialization of each base and member constitutes a
   3910   //   full-expression.
   3911   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
   3912   if (Init.isInvalid()) {
   3913     FD->setInvalidDecl();
   3914     return;
   3915   }
   3916 
   3917   InitExpr = Init.get();
   3918 
   3919   FD->setInClassInitializer(InitExpr);
   3920 }
   3921 
   3922 /// Find the direct and/or virtual base specifiers that
   3923 /// correspond to the given base type, for use in base initialization
   3924 /// within a constructor.
   3925 static bool FindBaseInitializer(Sema &SemaRef,
   3926                                 CXXRecordDecl *ClassDecl,
   3927                                 QualType BaseType,
   3928                                 const CXXBaseSpecifier *&DirectBaseSpec,
   3929                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
   3930   // First, check for a direct base class.
   3931   DirectBaseSpec = nullptr;
   3932   for (const auto &Base : ClassDecl->bases()) {
   3933     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
   3934       // We found a direct base of this type. That's what we're
   3935       // initializing.
   3936       DirectBaseSpec = &Base;
   3937       break;
   3938     }
   3939   }
   3940 
   3941   // Check for a virtual base class.
   3942   // FIXME: We might be able to short-circuit this if we know in advance that
   3943   // there are no virtual bases.
   3944   VirtualBaseSpec = nullptr;
   3945   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
   3946     // We haven't found a base yet; search the class hierarchy for a
   3947     // virtual base class.
   3948     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   3949                        /*DetectVirtual=*/false);
   3950     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
   3951                               SemaRef.Context.getTypeDeclType(ClassDecl),
   3952                               BaseType, Paths)) {
   3953       for (CXXBasePaths::paths_iterator Path = Paths.begin();
   3954            Path != Paths.end(); ++Path) {
   3955         if (Path->back().Base->isVirtual()) {
   3956           VirtualBaseSpec = Path->back().Base;
   3957           break;
   3958         }
   3959       }
   3960     }
   3961   }
   3962 
   3963   return DirectBaseSpec || VirtualBaseSpec;
   3964 }
   3965 
   3966 /// Handle a C++ member initializer using braced-init-list syntax.
   3967 MemInitResult
   3968 Sema::ActOnMemInitializer(Decl *ConstructorD,
   3969                           Scope *S,
   3970                           CXXScopeSpec &SS,
   3971                           IdentifierInfo *MemberOrBase,
   3972                           ParsedType TemplateTypeTy,
   3973                           const DeclSpec &DS,
   3974                           SourceLocation IdLoc,
   3975                           Expr *InitList,
   3976                           SourceLocation EllipsisLoc) {
   3977   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
   3978                              DS, IdLoc, InitList,
   3979                              EllipsisLoc);
   3980 }
   3981 
   3982 /// Handle a C++ member initializer using parentheses syntax.
   3983 MemInitResult
   3984 Sema::ActOnMemInitializer(Decl *ConstructorD,
   3985                           Scope *S,
   3986                           CXXScopeSpec &SS,
   3987                           IdentifierInfo *MemberOrBase,
   3988                           ParsedType TemplateTypeTy,
   3989                           const DeclSpec &DS,
   3990                           SourceLocation IdLoc,
   3991                           SourceLocation LParenLoc,
   3992                           ArrayRef<Expr *> Args,
   3993                           SourceLocation RParenLoc,
   3994                           SourceLocation EllipsisLoc) {
   3995   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
   3996   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
   3997                              DS, IdLoc, List, EllipsisLoc);
   3998 }
   3999 
   4000 namespace {
   4001 
   4002 // Callback to only accept typo corrections that can be a valid C++ member
   4003 // intializer: either a non-static field member or a base class.
   4004 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
   4005 public:
   4006   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
   4007       : ClassDecl(ClassDecl) {}
   4008 
   4009   bool ValidateCandidate(const TypoCorrection &candidate) override {
   4010     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
   4011       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
   4012         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
   4013       return isa<TypeDecl>(ND);
   4014     }
   4015     return false;
   4016   }
   4017 
   4018   std::unique_ptr<CorrectionCandidateCallback> clone() override {
   4019     return std::make_unique<MemInitializerValidatorCCC>(*this);
   4020   }
   4021 
   4022 private:
   4023   CXXRecordDecl *ClassDecl;
   4024 };
   4025 
   4026 }
   4027 
   4028 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
   4029                                              CXXScopeSpec &SS,
   4030                                              ParsedType TemplateTypeTy,
   4031                                              IdentifierInfo *MemberOrBase) {
   4032   if (SS.getScopeRep() || TemplateTypeTy)
   4033     return nullptr;
   4034   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
   4035   if (Result.empty())
   4036     return nullptr;
   4037   ValueDecl *Member;
   4038   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
   4039       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
   4040     return Member;
   4041   return nullptr;
   4042 }
   4043 
   4044 /// Handle a C++ member initializer.
   4045 MemInitResult
   4046 Sema::BuildMemInitializer(Decl *ConstructorD,
   4047                           Scope *S,
   4048                           CXXScopeSpec &SS,
   4049                           IdentifierInfo *MemberOrBase,
   4050                           ParsedType TemplateTypeTy,
   4051                           const DeclSpec &DS,
   4052                           SourceLocation IdLoc,
   4053                           Expr *Init,
   4054                           SourceLocation EllipsisLoc) {
   4055   ExprResult Res = CorrectDelayedTyposInExpr(Init);
   4056   if (!Res.isUsable())
   4057     return true;
   4058   Init = Res.get();
   4059 
   4060   if (!ConstructorD)
   4061     return true;
   4062 
   4063   AdjustDeclIfTemplate(ConstructorD);
   4064 
   4065   CXXConstructorDecl *Constructor
   4066     = dyn_cast<CXXConstructorDecl>(ConstructorD);
   4067   if (!Constructor) {
   4068     // The user wrote a constructor initializer on a function that is
   4069     // not a C++ constructor. Ignore the error for now, because we may
   4070     // have more member initializers coming; we'll diagnose it just
   4071     // once in ActOnMemInitializers.
   4072     return true;
   4073   }
   4074 
   4075   CXXRecordDecl *ClassDecl = Constructor->getParent();
   4076 
   4077   // C++ [class.base.init]p2:
   4078   //   Names in a mem-initializer-id are looked up in the scope of the
   4079   //   constructor's class and, if not found in that scope, are looked
   4080   //   up in the scope containing the constructor's definition.
   4081   //   [Note: if the constructor's class contains a member with the
   4082   //   same name as a direct or virtual base class of the class, a
   4083   //   mem-initializer-id naming the member or base class and composed
   4084   //   of a single identifier refers to the class member. A
   4085   //   mem-initializer-id for the hidden base class may be specified
   4086   //   using a qualified name. ]
   4087 
   4088   // Look for a member, first.
   4089   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
   4090           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
   4091     if (EllipsisLoc.isValid())
   4092       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
   4093           << MemberOrBase
   4094           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
   4095 
   4096     return BuildMemberInitializer(Member, Init, IdLoc);
   4097   }
   4098   // It didn't name a member, so see if it names a class.
   4099   QualType BaseType;
   4100   TypeSourceInfo *TInfo = nullptr;
   4101 
   4102   if (TemplateTypeTy) {
   4103     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
   4104     if (BaseType.isNull())
   4105       return true;
   4106   } else if (DS.getTypeSpecType() == TST_decltype) {
   4107     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
   4108   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
   4109     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
   4110     return true;
   4111   } else {
   4112     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
   4113     LookupParsedName(R, S, &SS);
   4114 
   4115     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
   4116     if (!TyD) {
   4117       if (R.isAmbiguous()) return true;
   4118 
   4119       // We don't want access-control diagnostics here.
   4120       R.suppressDiagnostics();
   4121 
   4122       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
   4123         bool NotUnknownSpecialization = false;
   4124         DeclContext *DC = computeDeclContext(SS, false);
   4125         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
   4126           NotUnknownSpecialization = !Record->hasAnyDependentBases();
   4127 
   4128         if (!NotUnknownSpecialization) {
   4129           // When the scope specifier can refer to a member of an unknown
   4130           // specialization, we take it as a type name.
   4131           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
   4132                                        SS.getWithLocInContext(Context),
   4133                                        *MemberOrBase, IdLoc);
   4134           if (BaseType.isNull())
   4135             return true;
   4136 
   4137           TInfo = Context.CreateTypeSourceInfo(BaseType);
   4138           DependentNameTypeLoc TL =
   4139               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
   4140           if (!TL.isNull()) {
   4141             TL.setNameLoc(IdLoc);
   4142             TL.setElaboratedKeywordLoc(SourceLocation());
   4143             TL.setQualifierLoc(SS.getWithLocInContext(Context));
   4144           }
   4145 
   4146           R.clear();
   4147           R.setLookupName(MemberOrBase);
   4148         }
   4149       }
   4150 
   4151       // If no results were found, try to correct typos.
   4152       TypoCorrection Corr;
   4153       MemInitializerValidatorCCC CCC(ClassDecl);
   4154       if (R.empty() && BaseType.isNull() &&
   4155           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
   4156                               CCC, CTK_ErrorRecovery, ClassDecl))) {
   4157         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
   4158           // We have found a non-static data member with a similar
   4159           // name to what was typed; complain and initialize that
   4160           // member.
   4161           diagnoseTypo(Corr,
   4162                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
   4163                          << MemberOrBase << true);
   4164           return BuildMemberInitializer(Member, Init, IdLoc);
   4165         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
   4166           const CXXBaseSpecifier *DirectBaseSpec;
   4167           const CXXBaseSpecifier *VirtualBaseSpec;
   4168           if (FindBaseInitializer(*this, ClassDecl,
   4169                                   Context.getTypeDeclType(Type),
   4170                                   DirectBaseSpec, VirtualBaseSpec)) {
   4171             // We have found a direct or virtual base class with a
   4172             // similar name to what was typed; complain and initialize
   4173             // that base class.
   4174             diagnoseTypo(Corr,
   4175                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
   4176                            << MemberOrBase << false,
   4177                          PDiag() /*Suppress note, we provide our own.*/);
   4178 
   4179             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
   4180                                                               : VirtualBaseSpec;
   4181             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
   4182                 << BaseSpec->getType() << BaseSpec->getSourceRange();
   4183 
   4184             TyD = Type;
   4185           }
   4186         }
   4187       }
   4188 
   4189       if (!TyD && BaseType.isNull()) {
   4190         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
   4191           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
   4192         return true;
   4193       }
   4194     }
   4195 
   4196     if (BaseType.isNull()) {
   4197       BaseType = Context.getTypeDeclType(TyD);
   4198       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
   4199       if (SS.isSet()) {
   4200         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
   4201                                              BaseType);
   4202         TInfo = Context.CreateTypeSourceInfo(BaseType);
   4203         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
   4204         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
   4205         TL.setElaboratedKeywordLoc(SourceLocation());
   4206         TL.setQualifierLoc(SS.getWithLocInContext(Context));
   4207       }
   4208     }
   4209   }
   4210 
   4211   if (!TInfo)
   4212     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
   4213 
   4214   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
   4215 }
   4216 
   4217 MemInitResult
   4218 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
   4219                              SourceLocation IdLoc) {
   4220   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
   4221   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
   4222   assert((DirectMember || IndirectMember) &&
   4223          "Member must be a FieldDecl or IndirectFieldDecl");
   4224 
   4225   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
   4226     return true;
   4227 
   4228   if (Member->isInvalidDecl())
   4229     return true;
   4230 
   4231   MultiExprArg Args;
   4232   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
   4233     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
   4234   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
   4235     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
   4236   } else {
   4237     // Template instantiation doesn't reconstruct ParenListExprs for us.
   4238     Args = Init;
   4239   }
   4240 
   4241   SourceRange InitRange = Init->getSourceRange();
   4242 
   4243   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
   4244     // Can't check initialization for a member of dependent type or when
   4245     // any of the arguments are type-dependent expressions.
   4246     DiscardCleanupsInEvaluationContext();
   4247   } else {
   4248     bool InitList = false;
   4249     if (isa<InitListExpr>(Init)) {
   4250       InitList = true;
   4251       Args = Init;
   4252     }
   4253 
   4254     // Initialize the member.
   4255     InitializedEntity MemberEntity =
   4256       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
   4257                    : InitializedEntity::InitializeMember(IndirectMember,
   4258                                                          nullptr);
   4259     InitializationKind Kind =
   4260         InitList ? InitializationKind::CreateDirectList(
   4261                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
   4262                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
   4263                                                     InitRange.getEnd());
   4264 
   4265     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
   4266     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
   4267                                             nullptr);
   4268     if (MemberInit.isInvalid())
   4269       return true;
   4270 
   4271     // C++11 [class.base.init]p7:
   4272     //   The initialization of each base and member constitutes a
   4273     //   full-expression.
   4274     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
   4275                                      /*DiscardedValue*/ false);
   4276     if (MemberInit.isInvalid())
   4277       return true;
   4278 
   4279     Init = MemberInit.get();
   4280   }
   4281 
   4282   if (DirectMember) {
   4283     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
   4284                                             InitRange.getBegin(), Init,
   4285                                             InitRange.getEnd());
   4286   } else {
   4287     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
   4288                                             InitRange.getBegin(), Init,
   4289                                             InitRange.getEnd());
   4290   }
   4291 }
   4292 
   4293 MemInitResult
   4294 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
   4295                                  CXXRecordDecl *ClassDecl) {
   4296   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
   4297   if (!LangOpts.CPlusPlus11)
   4298     return Diag(NameLoc, diag::err_delegating_ctor)
   4299       << TInfo->getTypeLoc().getLocalSourceRange();
   4300   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
   4301 
   4302   bool InitList = true;
   4303   MultiExprArg Args = Init;
   4304   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
   4305     InitList = false;
   4306     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
   4307   }
   4308 
   4309   SourceRange InitRange = Init->getSourceRange();
   4310   // Initialize the object.
   4311   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
   4312                                      QualType(ClassDecl->getTypeForDecl(), 0));
   4313   InitializationKind Kind =
   4314       InitList ? InitializationKind::CreateDirectList(
   4315                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
   4316                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
   4317                                                   InitRange.getEnd());
   4318   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
   4319   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
   4320                                               Args, nullptr);
   4321   if (DelegationInit.isInvalid())
   4322     return true;
   4323 
   4324   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
   4325          "Delegating constructor with no target?");
   4326 
   4327   // C++11 [class.base.init]p7:
   4328   //   The initialization of each base and member constitutes a
   4329   //   full-expression.
   4330   DelegationInit = ActOnFinishFullExpr(
   4331       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
   4332   if (DelegationInit.isInvalid())
   4333     return true;
   4334 
   4335   // If we are in a dependent context, template instantiation will
   4336   // perform this type-checking again. Just save the arguments that we
   4337   // received in a ParenListExpr.
   4338   // FIXME: This isn't quite ideal, since our ASTs don't capture all
   4339   // of the information that we have about the base
   4340   // initializer. However, deconstructing the ASTs is a dicey process,
   4341   // and this approach is far more likely to get the corner cases right.
   4342   if (CurContext->isDependentContext())
   4343     DelegationInit = Init;
   4344 
   4345   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
   4346                                           DelegationInit.getAs<Expr>(),
   4347                                           InitRange.getEnd());
   4348 }
   4349 
   4350 MemInitResult
   4351 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
   4352                            Expr *Init, CXXRecordDecl *ClassDecl,
   4353                            SourceLocation EllipsisLoc) {
   4354   SourceLocation BaseLoc
   4355     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
   4356 
   4357   if (!BaseType->isDependentType() && !BaseType->isRecordType())
   4358     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
   4359              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
   4360 
   4361   // C++ [class.base.init]p2:
   4362   //   [...] Unless the mem-initializer-id names a nonstatic data
   4363   //   member of the constructor's class or a direct or virtual base
   4364   //   of that class, the mem-initializer is ill-formed. A
   4365   //   mem-initializer-list can initialize a base class using any
   4366   //   name that denotes that base class type.
   4367   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
   4368 
   4369   SourceRange InitRange = Init->getSourceRange();
   4370   if (EllipsisLoc.isValid()) {
   4371     // This is a pack expansion.
   4372     if (!BaseType->containsUnexpandedParameterPack())  {
   4373       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
   4374         << SourceRange(BaseLoc, InitRange.getEnd());
   4375 
   4376       EllipsisLoc = SourceLocation();
   4377     }
   4378   } else {
   4379     // Check for any unexpanded parameter packs.
   4380     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
   4381       return true;
   4382 
   4383     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
   4384       return true;
   4385   }
   4386 
   4387   // Check for direct and virtual base classes.
   4388   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
   4389   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
   4390   if (!Dependent) {
   4391     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
   4392                                        BaseType))
   4393       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
   4394 
   4395     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
   4396                         VirtualBaseSpec);
   4397 
   4398     // C++ [base.class.init]p2:
   4399     // Unless the mem-initializer-id names a nonstatic data member of the
   4400     // constructor's class or a direct or virtual base of that class, the
   4401     // mem-initializer is ill-formed.
   4402     if (!DirectBaseSpec && !VirtualBaseSpec) {
   4403       // If the class has any dependent bases, then it's possible that
   4404       // one of those types will resolve to the same type as
   4405       // BaseType. Therefore, just treat this as a dependent base
   4406       // class initialization.  FIXME: Should we try to check the
   4407       // initialization anyway? It seems odd.
   4408       if (ClassDecl->hasAnyDependentBases())
   4409         Dependent = true;
   4410       else
   4411         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
   4412           << BaseType << Context.getTypeDeclType(ClassDecl)
   4413           << BaseTInfo->getTypeLoc().getLocalSourceRange();
   4414     }
   4415   }
   4416 
   4417   if (Dependent) {
   4418     DiscardCleanupsInEvaluationContext();
   4419 
   4420     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
   4421                                             /*IsVirtual=*/false,
   4422                                             InitRange.getBegin(), Init,
   4423                                             InitRange.getEnd(), EllipsisLoc);
   4424   }
   4425 
   4426   // C++ [base.class.init]p2:
   4427   //   If a mem-initializer-id is ambiguous because it designates both
   4428   //   a direct non-virtual base class and an inherited virtual base
   4429   //   class, the mem-initializer is ill-formed.
   4430   if (DirectBaseSpec && VirtualBaseSpec)
   4431     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
   4432       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
   4433 
   4434   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
   4435   if (!BaseSpec)
   4436     BaseSpec = VirtualBaseSpec;
   4437 
   4438   // Initialize the base.
   4439   bool InitList = true;
   4440   MultiExprArg Args = Init;
   4441   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
   4442     InitList = false;
   4443     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
   4444   }
   4445 
   4446   InitializedEntity BaseEntity =
   4447     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
   4448   InitializationKind Kind =
   4449       InitList ? InitializationKind::CreateDirectList(BaseLoc)
   4450                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
   4451                                                   InitRange.getEnd());
   4452   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
   4453   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
   4454   if (BaseInit.isInvalid())
   4455     return true;
   4456 
   4457   // C++11 [class.base.init]p7:
   4458   //   The initialization of each base and member constitutes a
   4459   //   full-expression.
   4460   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
   4461                                  /*DiscardedValue*/ false);
   4462   if (BaseInit.isInvalid())
   4463     return true;
   4464 
   4465   // If we are in a dependent context, template instantiation will
   4466   // perform this type-checking again. Just save the arguments that we
   4467   // received in a ParenListExpr.
   4468   // FIXME: This isn't quite ideal, since our ASTs don't capture all
   4469   // of the information that we have about the base
   4470   // initializer. However, deconstructing the ASTs is a dicey process,
   4471   // and this approach is far more likely to get the corner cases right.
   4472   if (CurContext->isDependentContext())
   4473     BaseInit = Init;
   4474 
   4475   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
   4476                                           BaseSpec->isVirtual(),
   4477                                           InitRange.getBegin(),
   4478                                           BaseInit.getAs<Expr>(),
   4479                                           InitRange.getEnd(), EllipsisLoc);
   4480 }
   4481 
   4482 // Create a static_cast\<T&&>(expr).
   4483 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
   4484   if (T.isNull()) T = E->getType();
   4485   QualType TargetType = SemaRef.BuildReferenceType(
   4486       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
   4487   SourceLocation ExprLoc = E->getBeginLoc();
   4488   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
   4489       TargetType, ExprLoc);
   4490 
   4491   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
   4492                                    SourceRange(ExprLoc, ExprLoc),
   4493                                    E->getSourceRange()).get();
   4494 }
   4495 
   4496 /// ImplicitInitializerKind - How an implicit base or member initializer should
   4497 /// initialize its base or member.
   4498 enum ImplicitInitializerKind {
   4499   IIK_Default,
   4500   IIK_Copy,
   4501   IIK_Move,
   4502   IIK_Inherit
   4503 };
   4504 
   4505 static bool
   4506 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
   4507                              ImplicitInitializerKind ImplicitInitKind,
   4508                              CXXBaseSpecifier *BaseSpec,
   4509                              bool IsInheritedVirtualBase,
   4510                              CXXCtorInitializer *&CXXBaseInit) {
   4511   InitializedEntity InitEntity
   4512     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
   4513                                         IsInheritedVirtualBase);
   4514 
   4515   ExprResult BaseInit;
   4516 
   4517   switch (ImplicitInitKind) {
   4518   case IIK_Inherit:
   4519   case IIK_Default: {
   4520     InitializationKind InitKind
   4521       = InitializationKind::CreateDefault(Constructor->getLocation());
   4522     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
   4523     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
   4524     break;
   4525   }
   4526 
   4527   case IIK_Move:
   4528   case IIK_Copy: {
   4529     bool Moving = ImplicitInitKind == IIK_Move;
   4530     ParmVarDecl *Param = Constructor->getParamDecl(0);
   4531     QualType ParamType = Param->getType().getNonReferenceType();
   4532 
   4533     Expr *CopyCtorArg =
   4534       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
   4535                           SourceLocation(), Param, false,
   4536                           Constructor->getLocation(), ParamType,
   4537                           VK_LValue, nullptr);
   4538 
   4539     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
   4540 
   4541     // Cast to the base class to avoid ambiguities.
   4542     QualType ArgTy =
   4543       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
   4544                                        ParamType.getQualifiers());
   4545 
   4546     if (Moving) {
   4547       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
   4548     }
   4549 
   4550     CXXCastPath BasePath;
   4551     BasePath.push_back(BaseSpec);
   4552     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
   4553                                             CK_UncheckedDerivedToBase,
   4554                                             Moving ? VK_XValue : VK_LValue,
   4555                                             &BasePath).get();
   4556 
   4557     InitializationKind InitKind
   4558       = InitializationKind::CreateDirect(Constructor->getLocation(),
   4559                                          SourceLocation(), SourceLocation());
   4560     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
   4561     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
   4562     break;
   4563   }
   4564   }
   4565 
   4566   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
   4567   if (BaseInit.isInvalid())
   4568     return true;
   4569 
   4570   CXXBaseInit =
   4571     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
   4572                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
   4573                                                         SourceLocation()),
   4574                                              BaseSpec->isVirtual(),
   4575                                              SourceLocation(),
   4576                                              BaseInit.getAs<Expr>(),
   4577                                              SourceLocation(),
   4578                                              SourceLocation());
   4579 
   4580   return false;
   4581 }
   4582 
   4583 static bool RefersToRValueRef(Expr *MemRef) {
   4584   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
   4585   return Referenced->getType()->isRValueReferenceType();
   4586 }
   4587 
   4588 static bool
   4589 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
   4590                                ImplicitInitializerKind ImplicitInitKind,
   4591                                FieldDecl *Field, IndirectFieldDecl *Indirect,
   4592                                CXXCtorInitializer *&CXXMemberInit) {
   4593   if (Field->isInvalidDecl())
   4594     return true;
   4595 
   4596   SourceLocation Loc = Constructor->getLocation();
   4597 
   4598   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
   4599     bool Moving = ImplicitInitKind == IIK_Move;
   4600     ParmVarDecl *Param = Constructor->getParamDecl(0);
   4601     QualType ParamType = Param->getType().getNonReferenceType();
   4602 
   4603     // Suppress copying zero-width bitfields.
   4604     if (Field->isZeroLengthBitField(SemaRef.Context))
   4605       return false;
   4606 
   4607     Expr *MemberExprBase =
   4608       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
   4609                           SourceLocation(), Param, false,
   4610                           Loc, ParamType, VK_LValue, nullptr);
   4611 
   4612     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
   4613 
   4614     if (Moving) {
   4615       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
   4616     }
   4617 
   4618     // Build a reference to this field within the parameter.
   4619     CXXScopeSpec SS;
   4620     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
   4621                               Sema::LookupMemberName);
   4622     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
   4623                                   : cast<ValueDecl>(Field), AS_public);
   4624     MemberLookup.resolveKind();
   4625     ExprResult CtorArg
   4626       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
   4627                                          ParamType, Loc,
   4628                                          /*IsArrow=*/false,
   4629                                          SS,
   4630                                          /*TemplateKWLoc=*/SourceLocation(),
   4631                                          /*FirstQualifierInScope=*/nullptr,
   4632                                          MemberLookup,
   4633                                          /*TemplateArgs=*/nullptr,
   4634                                          /*S*/nullptr);
   4635     if (CtorArg.isInvalid())
   4636       return true;
   4637 
   4638     // C++11 [class.copy]p15:
   4639     //   - if a member m has rvalue reference type T&&, it is direct-initialized
   4640     //     with static_cast<T&&>(x.m);
   4641     if (RefersToRValueRef(CtorArg.get())) {
   4642       CtorArg = CastForMoving(SemaRef, CtorArg.get());
   4643     }
   4644 
   4645     InitializedEntity Entity =
   4646         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
   4647                                                        /*Implicit*/ true)
   4648                  : InitializedEntity::InitializeMember(Field, nullptr,
   4649                                                        /*Implicit*/ true);
   4650 
   4651     // Direct-initialize to use the copy constructor.
   4652     InitializationKind InitKind =
   4653       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
   4654 
   4655     Expr *CtorArgE = CtorArg.getAs<Expr>();
   4656     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
   4657     ExprResult MemberInit =
   4658         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
   4659     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
   4660     if (MemberInit.isInvalid())
   4661       return true;
   4662 
   4663     if (Indirect)
   4664       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
   4665           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
   4666     else
   4667       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
   4668           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
   4669     return false;
   4670   }
   4671 
   4672   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
   4673          "Unhandled implicit init kind!");
   4674 
   4675   QualType FieldBaseElementType =
   4676     SemaRef.Context.getBaseElementType(Field->getType());
   4677 
   4678   if (FieldBaseElementType->isRecordType()) {
   4679     InitializedEntity InitEntity =
   4680         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
   4681                                                        /*Implicit*/ true)
   4682                  : InitializedEntity::InitializeMember(Field, nullptr,
   4683                                                        /*Implicit*/ true);
   4684     InitializationKind InitKind =
   4685       InitializationKind::CreateDefault(Loc);
   4686 
   4687     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
   4688     ExprResult MemberInit =
   4689       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
   4690 
   4691     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
   4692     if (MemberInit.isInvalid())
   4693       return true;
   4694 
   4695     if (Indirect)
   4696       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
   4697                                                                Indirect, Loc,
   4698                                                                Loc,
   4699                                                                MemberInit.get(),
   4700                                                                Loc);
   4701     else
   4702       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
   4703                                                                Field, Loc, Loc,
   4704                                                                MemberInit.get(),
   4705                                                                Loc);
   4706     return false;
   4707   }
   4708 
   4709   if (!Field->getParent()->isUnion()) {
   4710     if (FieldBaseElementType->isReferenceType()) {
   4711       SemaRef.Diag(Constructor->getLocation(),
   4712                    diag::err_uninitialized_member_in_ctor)
   4713       << (int)Constructor->isImplicit()
   4714       << SemaRef.Context.getTagDeclType(Constructor->getParent())
   4715       << 0 << Field->getDeclName();
   4716       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
   4717       return true;
   4718     }
   4719 
   4720     if (FieldBaseElementType.isConstQualified()) {
   4721       SemaRef.Diag(Constructor->getLocation(),
   4722                    diag::err_uninitialized_member_in_ctor)
   4723       << (int)Constructor->isImplicit()
   4724       << SemaRef.Context.getTagDeclType(Constructor->getParent())
   4725       << 1 << Field->getDeclName();
   4726       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
   4727       return true;
   4728     }
   4729   }
   4730 
   4731   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
   4732     // ARC and Weak:
   4733     //   Default-initialize Objective-C pointers to NULL.
   4734     CXXMemberInit
   4735       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
   4736                                                  Loc, Loc,
   4737                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
   4738                                                  Loc);
   4739     return false;
   4740   }
   4741 
   4742   // Nothing to initialize.
   4743   CXXMemberInit = nullptr;
   4744   return false;
   4745 }
   4746 
   4747 namespace {
   4748 struct BaseAndFieldInfo {
   4749   Sema &S;
   4750   CXXConstructorDecl *Ctor;
   4751   bool AnyErrorsInInits;
   4752   ImplicitInitializerKind IIK;
   4753   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
   4754   SmallVector<CXXCtorInitializer*, 8> AllToInit;
   4755   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
   4756 
   4757   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
   4758     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
   4759     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
   4760     if (Ctor->getInheritedConstructor())
   4761       IIK = IIK_Inherit;
   4762     else if (Generated && Ctor->isCopyConstructor())
   4763       IIK = IIK_Copy;
   4764     else if (Generated && Ctor->isMoveConstructor())
   4765       IIK = IIK_Move;
   4766     else
   4767       IIK = IIK_Default;
   4768   }
   4769 
   4770   bool isImplicitCopyOrMove() const {
   4771     switch (IIK) {
   4772     case IIK_Copy:
   4773     case IIK_Move:
   4774       return true;
   4775 
   4776     case IIK_Default:
   4777     case IIK_Inherit:
   4778       return false;
   4779     }
   4780 
   4781     llvm_unreachable("Invalid ImplicitInitializerKind!");
   4782   }
   4783 
   4784   bool addFieldInitializer(CXXCtorInitializer *Init) {
   4785     AllToInit.push_back(Init);
   4786 
   4787     // Check whether this initializer makes the field "used".
   4788     if (Init->getInit()->HasSideEffects(S.Context))
   4789       S.UnusedPrivateFields.remove(Init->getAnyMember());
   4790 
   4791     return false;
   4792   }
   4793 
   4794   bool isInactiveUnionMember(FieldDecl *Field) {
   4795     RecordDecl *Record = Field->getParent();
   4796     if (!Record->isUnion())
   4797       return false;
   4798 
   4799     if (FieldDecl *Active =
   4800             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
   4801       return Active != Field->getCanonicalDecl();
   4802 
   4803     // In an implicit copy or move constructor, ignore any in-class initializer.
   4804     if (isImplicitCopyOrMove())
   4805       return true;
   4806 
   4807     // If there's no explicit initialization, the field is active only if it
   4808     // has an in-class initializer...
   4809     if (Field->hasInClassInitializer())
   4810       return false;
   4811     // ... or it's an anonymous struct or union whose class has an in-class
   4812     // initializer.
   4813     if (!Field->isAnonymousStructOrUnion())
   4814       return true;
   4815     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
   4816     return !FieldRD->hasInClassInitializer();
   4817   }
   4818 
   4819   /// Determine whether the given field is, or is within, a union member
   4820   /// that is inactive (because there was an initializer given for a different
   4821   /// member of the union, or because the union was not initialized at all).
   4822   bool isWithinInactiveUnionMember(FieldDecl *Field,
   4823                                    IndirectFieldDecl *Indirect) {
   4824     if (!Indirect)
   4825       return isInactiveUnionMember(Field);
   4826 
   4827     for (auto *C : Indirect->chain()) {
   4828       FieldDecl *Field = dyn_cast<FieldDecl>(C);
   4829       if (Field && isInactiveUnionMember(Field))
   4830         return true;
   4831     }
   4832     return false;
   4833   }
   4834 };
   4835 }
   4836 
   4837 /// Determine whether the given type is an incomplete or zero-lenfgth
   4838 /// array type.
   4839 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
   4840   if (T->isIncompleteArrayType())
   4841     return true;
   4842 
   4843   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
   4844     if (!ArrayT->getSize())
   4845       return true;
   4846 
   4847     T = ArrayT->getElementType();
   4848   }
   4849 
   4850   return false;
   4851 }
   4852 
   4853 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
   4854                                     FieldDecl *Field,
   4855                                     IndirectFieldDecl *Indirect = nullptr) {
   4856   if (Field->isInvalidDecl())
   4857     return false;
   4858 
   4859   // Overwhelmingly common case: we have a direct initializer for this field.
   4860   if (CXXCtorInitializer *Init =
   4861           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
   4862     return Info.addFieldInitializer(Init);
   4863 
   4864   // C++11 [class.base.init]p8:
   4865   //   if the entity is a non-static data member that has a
   4866   //   brace-or-equal-initializer and either
   4867   //   -- the constructor's class is a union and no other variant member of that
   4868   //      union is designated by a mem-initializer-id or
   4869   //   -- the constructor's class is not a union, and, if the entity is a member
   4870   //      of an anonymous union, no other member of that union is designated by
   4871   //      a mem-initializer-id,
   4872   //   the entity is initialized as specified in [dcl.init].
   4873   //
   4874   // We also apply the same rules to handle anonymous structs within anonymous
   4875   // unions.
   4876   if (Info.isWithinInactiveUnionMember(Field, Indirect))
   4877     return false;
   4878 
   4879   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
   4880     ExprResult DIE =
   4881         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
   4882     if (DIE.isInvalid())
   4883       return true;
   4884 
   4885     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
   4886     SemaRef.checkInitializerLifetime(Entity, DIE.get());
   4887 
   4888     CXXCtorInitializer *Init;
   4889     if (Indirect)
   4890       Init = new (SemaRef.Context)
   4891           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
   4892                              SourceLocation(), DIE.get(), SourceLocation());
   4893     else
   4894       Init = new (SemaRef.Context)
   4895           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
   4896                              SourceLocation(), DIE.get(), SourceLocation());
   4897     return Info.addFieldInitializer(Init);
   4898   }
   4899 
   4900   // Don't initialize incomplete or zero-length arrays.
   4901   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
   4902     return false;
   4903 
   4904   // Don't try to build an implicit initializer if there were semantic
   4905   // errors in any of the initializers (and therefore we might be
   4906   // missing some that the user actually wrote).
   4907   if (Info.AnyErrorsInInits)
   4908     return false;
   4909 
   4910   CXXCtorInitializer *Init = nullptr;
   4911   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
   4912                                      Indirect, Init))
   4913     return true;
   4914 
   4915   if (!Init)
   4916     return false;
   4917 
   4918   return Info.addFieldInitializer(Init);
   4919 }
   4920 
   4921 bool
   4922 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
   4923                                CXXCtorInitializer *Initializer) {
   4924   assert(Initializer->isDelegatingInitializer());
   4925   Constructor->setNumCtorInitializers(1);
   4926   CXXCtorInitializer **initializer =
   4927     new (Context) CXXCtorInitializer*[1];
   4928   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
   4929   Constructor->setCtorInitializers(initializer);
   4930 
   4931   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
   4932     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
   4933     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
   4934   }
   4935 
   4936   DelegatingCtorDecls.push_back(Constructor);
   4937 
   4938   DiagnoseUninitializedFields(*this, Constructor);
   4939 
   4940   return false;
   4941 }
   4942 
   4943 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
   4944                                ArrayRef<CXXCtorInitializer *> Initializers) {
   4945   if (Constructor->isDependentContext()) {
   4946     // Just store the initializers as written, they will be checked during
   4947     // instantiation.
   4948     if (!Initializers.empty()) {
   4949       Constructor->setNumCtorInitializers(Initializers.size());
   4950       CXXCtorInitializer **baseOrMemberInitializers =
   4951         new (Context) CXXCtorInitializer*[Initializers.size()];
   4952       memcpy(baseOrMemberInitializers, Initializers.data(),
   4953              Initializers.size() * sizeof(CXXCtorInitializer*));
   4954       Constructor->setCtorInitializers(baseOrMemberInitializers);
   4955     }
   4956 
   4957     // Let template instantiation know whether we had errors.
   4958     if (AnyErrors)
   4959       Constructor->setInvalidDecl();
   4960 
   4961     return false;
   4962   }
   4963 
   4964   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
   4965 
   4966   // We need to build the initializer AST according to order of construction
   4967   // and not what user specified in the Initializers list.
   4968   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
   4969   if (!ClassDecl)
   4970     return true;
   4971 
   4972   bool HadError = false;
   4973 
   4974   for (unsigned i = 0; i < Initializers.size(); i++) {
   4975     CXXCtorInitializer *Member = Initializers[i];
   4976 
   4977     if (Member->isBaseInitializer())
   4978       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
   4979     else {
   4980       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
   4981 
   4982       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
   4983         for (auto *C : F->chain()) {
   4984           FieldDecl *FD = dyn_cast<FieldDecl>(C);
   4985           if (FD && FD->getParent()->isUnion())
   4986             Info.ActiveUnionMember.insert(std::make_pair(
   4987                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
   4988         }
   4989       } else if (FieldDecl *FD = Member->getMember()) {
   4990         if (FD->getParent()->isUnion())
   4991           Info.ActiveUnionMember.insert(std::make_pair(
   4992               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
   4993       }
   4994     }
   4995   }
   4996 
   4997   // Keep track of the direct virtual bases.
   4998   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
   4999   for (auto &I : ClassDecl->bases()) {
   5000     if (I.isVirtual())
   5001       DirectVBases.insert(&I);
   5002   }
   5003 
   5004   // Push virtual bases before others.
   5005   for (auto &VBase : ClassDecl->vbases()) {
   5006     if (CXXCtorInitializer *Value
   5007         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
   5008       // [class.base.init]p7, per DR257:
   5009       //   A mem-initializer where the mem-initializer-id names a virtual base
   5010       //   class is ignored during execution of a constructor of any class that
   5011       //   is not the most derived class.
   5012       if (ClassDecl->isAbstract()) {
   5013         // FIXME: Provide a fixit to remove the base specifier. This requires
   5014         // tracking the location of the associated comma for a base specifier.
   5015         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
   5016           << VBase.getType() << ClassDecl;
   5017         DiagnoseAbstractType(ClassDecl);
   5018       }
   5019 
   5020       Info.AllToInit.push_back(Value);
   5021     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
   5022       // [class.base.init]p8, per DR257:
   5023       //   If a given [...] base class is not named by a mem-initializer-id
   5024       //   [...] and the entity is not a virtual base class of an abstract
   5025       //   class, then [...] the entity is default-initialized.
   5026       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
   5027       CXXCtorInitializer *CXXBaseInit;
   5028       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
   5029                                        &VBase, IsInheritedVirtualBase,
   5030                                        CXXBaseInit)) {
   5031         HadError = true;
   5032         continue;
   5033       }
   5034 
   5035       Info.AllToInit.push_back(CXXBaseInit);
   5036     }
   5037   }
   5038 
   5039   // Non-virtual bases.
   5040   for (auto &Base : ClassDecl->bases()) {
   5041     // Virtuals are in the virtual base list and already constructed.
   5042     if (Base.isVirtual())
   5043       continue;
   5044 
   5045     if (CXXCtorInitializer *Value
   5046           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
   5047       Info.AllToInit.push_back(Value);
   5048     } else if (!AnyErrors) {
   5049       CXXCtorInitializer *CXXBaseInit;
   5050       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
   5051                                        &Base, /*IsInheritedVirtualBase=*/false,
   5052                                        CXXBaseInit)) {
   5053         HadError = true;
   5054         continue;
   5055       }
   5056 
   5057       Info.AllToInit.push_back(CXXBaseInit);
   5058     }
   5059   }
   5060 
   5061   // Fields.
   5062   for (auto *Mem : ClassDecl->decls()) {
   5063     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
   5064       // C++ [class.bit]p2:
   5065       //   A declaration for a bit-field that omits the identifier declares an
   5066       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
   5067       //   initialized.
   5068       if (F->isUnnamedBitfield())
   5069         continue;
   5070 
   5071       // If we're not generating the implicit copy/move constructor, then we'll
   5072       // handle anonymous struct/union fields based on their individual
   5073       // indirect fields.
   5074       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
   5075         continue;
   5076 
   5077       if (CollectFieldInitializer(*this, Info, F))
   5078         HadError = true;
   5079       continue;
   5080     }
   5081 
   5082     // Beyond this point, we only consider default initialization.
   5083     if (Info.isImplicitCopyOrMove())
   5084       continue;
   5085 
   5086     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
   5087       if (F->getType()->isIncompleteArrayType()) {
   5088         assert(ClassDecl->hasFlexibleArrayMember() &&
   5089                "Incomplete array type is not valid");
   5090         continue;
   5091       }
   5092 
   5093       // Initialize each field of an anonymous struct individually.
   5094       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
   5095         HadError = true;
   5096 
   5097       continue;
   5098     }
   5099   }
   5100 
   5101   unsigned NumInitializers = Info.AllToInit.size();
   5102   if (NumInitializers > 0) {
   5103     Constructor->setNumCtorInitializers(NumInitializers);
   5104     CXXCtorInitializer **baseOrMemberInitializers =
   5105       new (Context) CXXCtorInitializer*[NumInitializers];
   5106     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
   5107            NumInitializers * sizeof(CXXCtorInitializer*));
   5108     Constructor->setCtorInitializers(baseOrMemberInitializers);
   5109 
   5110     // Constructors implicitly reference the base and member
   5111     // destructors.
   5112     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
   5113                                            Constructor->getParent());
   5114   }
   5115 
   5116   return HadError;
   5117 }
   5118 
   5119 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
   5120   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
   5121     const RecordDecl *RD = RT->getDecl();
   5122     if (RD->isAnonymousStructOrUnion()) {
   5123       for (auto *Field : RD->fields())
   5124         PopulateKeysForFields(Field, IdealInits);
   5125       return;
   5126     }
   5127   }
   5128   IdealInits.push_back(Field->getCanonicalDecl());
   5129 }
   5130 
   5131 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
   5132   return Context.getCanonicalType(BaseType).getTypePtr();
   5133 }
   5134 
   5135 static const void *GetKeyForMember(ASTContext &Context,
   5136                                    CXXCtorInitializer *Member) {
   5137   if (!Member->isAnyMemberInitializer())
   5138     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
   5139 
   5140   return Member->getAnyMember()->getCanonicalDecl();
   5141 }
   5142 
   5143 static void DiagnoseBaseOrMemInitializerOrder(
   5144     Sema &SemaRef, const CXXConstructorDecl *Constructor,
   5145     ArrayRef<CXXCtorInitializer *> Inits) {
   5146   if (Constructor->getDeclContext()->isDependentContext())
   5147     return;
   5148 
   5149   // Don't check initializers order unless the warning is enabled at the
   5150   // location of at least one initializer.
   5151   bool ShouldCheckOrder = false;
   5152   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
   5153     CXXCtorInitializer *Init = Inits[InitIndex];
   5154     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
   5155                                  Init->getSourceLocation())) {
   5156       ShouldCheckOrder = true;
   5157       break;
   5158     }
   5159   }
   5160   if (!ShouldCheckOrder)
   5161     return;
   5162 
   5163   // Build the list of bases and members in the order that they'll
   5164   // actually be initialized.  The explicit initializers should be in
   5165   // this same order but may be missing things.
   5166   SmallVector<const void*, 32> IdealInitKeys;
   5167 
   5168   const CXXRecordDecl *ClassDecl = Constructor->getParent();
   5169 
   5170   // 1. Virtual bases.
   5171   for (const auto &VBase : ClassDecl->vbases())
   5172     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
   5173 
   5174   // 2. Non-virtual bases.
   5175   for (const auto &Base : ClassDecl->bases()) {
   5176     if (Base.isVirtual())
   5177       continue;
   5178     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
   5179   }
   5180 
   5181   // 3. Direct fields.
   5182   for (auto *Field : ClassDecl->fields()) {
   5183     if (Field->isUnnamedBitfield())
   5184       continue;
   5185 
   5186     PopulateKeysForFields(Field, IdealInitKeys);
   5187   }
   5188 
   5189   unsigned NumIdealInits = IdealInitKeys.size();
   5190   unsigned IdealIndex = 0;
   5191 
   5192   CXXCtorInitializer *PrevInit = nullptr;
   5193   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
   5194     CXXCtorInitializer *Init = Inits[InitIndex];
   5195     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
   5196 
   5197     // Scan forward to try to find this initializer in the idealized
   5198     // initializers list.
   5199     for (; IdealIndex != NumIdealInits; ++IdealIndex)
   5200       if (InitKey == IdealInitKeys[IdealIndex])
   5201         break;
   5202 
   5203     // If we didn't find this initializer, it must be because we
   5204     // scanned past it on a previous iteration.  That can only
   5205     // happen if we're out of order;  emit a warning.
   5206     if (IdealIndex == NumIdealInits && PrevInit) {
   5207       Sema::SemaDiagnosticBuilder D =
   5208         SemaRef.Diag(PrevInit->getSourceLocation(),
   5209                      diag::warn_initializer_out_of_order);
   5210 
   5211       if (PrevInit->isAnyMemberInitializer())
   5212         D << 0 << PrevInit->getAnyMember()->getDeclName();
   5213       else
   5214         D << 1 << PrevInit->getTypeSourceInfo()->getType();
   5215 
   5216       if (Init->isAnyMemberInitializer())
   5217         D << 0 << Init->getAnyMember()->getDeclName();
   5218       else
   5219         D << 1 << Init->getTypeSourceInfo()->getType();
   5220 
   5221       // Move back to the initializer's location in the ideal list.
   5222       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
   5223         if (InitKey == IdealInitKeys[IdealIndex])
   5224           break;
   5225 
   5226       assert(IdealIndex < NumIdealInits &&
   5227              "initializer not found in initializer list");
   5228     }
   5229 
   5230     PrevInit = Init;
   5231   }
   5232 }
   5233 
   5234 namespace {
   5235 bool CheckRedundantInit(Sema &S,
   5236                         CXXCtorInitializer *Init,
   5237                         CXXCtorInitializer *&PrevInit) {
   5238   if (!PrevInit) {
   5239     PrevInit = Init;
   5240     return false;
   5241   }
   5242 
   5243   if (FieldDecl *Field = Init->getAnyMember())
   5244     S.Diag(Init->getSourceLocation(),
   5245            diag::err_multiple_mem_initialization)
   5246       << Field->getDeclName()
   5247       << Init->getSourceRange();
   5248   else {
   5249     const Type *BaseClass = Init->getBaseClass();
   5250     assert(BaseClass && "neither field nor base");
   5251     S.Diag(Init->getSourceLocation(),
   5252            diag::err_multiple_base_initialization)
   5253       << QualType(BaseClass, 0)
   5254       << Init->getSourceRange();
   5255   }
   5256   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
   5257     << 0 << PrevInit->getSourceRange();
   5258 
   5259   return true;
   5260 }
   5261 
   5262 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
   5263 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
   5264 
   5265 bool CheckRedundantUnionInit(Sema &S,
   5266                              CXXCtorInitializer *Init,
   5267                              RedundantUnionMap &Unions) {
   5268   FieldDecl *Field = Init->getAnyMember();
   5269   RecordDecl *Parent = Field->getParent();
   5270   NamedDecl *Child = Field;
   5271 
   5272   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
   5273     if (Parent->isUnion()) {
   5274       UnionEntry &En = Unions[Parent];
   5275       if (En.first && En.first != Child) {
   5276         S.Diag(Init->getSourceLocation(),
   5277                diag::err_multiple_mem_union_initialization)
   5278           << Field->getDeclName()
   5279           << Init->getSourceRange();
   5280         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
   5281           << 0 << En.second->getSourceRange();
   5282         return true;
   5283       }
   5284       if (!En.first) {
   5285         En.first = Child;
   5286         En.second = Init;
   5287       }
   5288       if (!Parent->isAnonymousStructOrUnion())
   5289         return false;
   5290     }
   5291 
   5292     Child = Parent;
   5293     Parent = cast<RecordDecl>(Parent->getDeclContext());
   5294   }
   5295 
   5296   return false;
   5297 }
   5298 }
   5299 
   5300 /// ActOnMemInitializers - Handle the member initializers for a constructor.
   5301 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
   5302                                 SourceLocation ColonLoc,
   5303                                 ArrayRef<CXXCtorInitializer*> MemInits,
   5304                                 bool AnyErrors) {
   5305   if (!ConstructorDecl)
   5306     return;
   5307 
   5308   AdjustDeclIfTemplate(ConstructorDecl);
   5309 
   5310   CXXConstructorDecl *Constructor
   5311     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
   5312 
   5313   if (!Constructor) {
   5314     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
   5315     return;
   5316   }
   5317 
   5318   // Mapping for the duplicate initializers check.
   5319   // For member initializers, this is keyed with a FieldDecl*.
   5320   // For base initializers, this is keyed with a Type*.
   5321   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
   5322 
   5323   // Mapping for the inconsistent anonymous-union initializers check.
   5324   RedundantUnionMap MemberUnions;
   5325 
   5326   bool HadError = false;
   5327   for (unsigned i = 0; i < MemInits.size(); i++) {
   5328     CXXCtorInitializer *Init = MemInits[i];
   5329 
   5330     // Set the source order index.
   5331     Init->setSourceOrder(i);
   5332 
   5333     if (Init->isAnyMemberInitializer()) {
   5334       const void *Key = GetKeyForMember(Context, Init);
   5335       if (CheckRedundantInit(*this, Init, Members[Key]) ||
   5336           CheckRedundantUnionInit(*this, Init, MemberUnions))
   5337         HadError = true;
   5338     } else if (Init->isBaseInitializer()) {
   5339       const void *Key = GetKeyForMember(Context, Init);
   5340       if (CheckRedundantInit(*this, Init, Members[Key]))
   5341         HadError = true;
   5342     } else {
   5343       assert(Init->isDelegatingInitializer());
   5344       // This must be the only initializer
   5345       if (MemInits.size() != 1) {
   5346         Diag(Init->getSourceLocation(),
   5347              diag::err_delegating_initializer_alone)
   5348           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
   5349         // We will treat this as being the only initializer.
   5350       }
   5351       SetDelegatingInitializer(Constructor, MemInits[i]);
   5352       // Return immediately as the initializer is set.
   5353       return;
   5354     }
   5355   }
   5356 
   5357   if (HadError)
   5358     return;
   5359 
   5360   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
   5361 
   5362   SetCtorInitializers(Constructor, AnyErrors, MemInits);
   5363 
   5364   DiagnoseUninitializedFields(*this, Constructor);
   5365 }
   5366 
   5367 void
   5368 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
   5369                                              CXXRecordDecl *ClassDecl) {
   5370   // Ignore dependent contexts. Also ignore unions, since their members never
   5371   // have destructors implicitly called.
   5372   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
   5373     return;
   5374 
   5375   // FIXME: all the access-control diagnostics are positioned on the
   5376   // field/base declaration.  That's probably good; that said, the
   5377   // user might reasonably want to know why the destructor is being
   5378   // emitted, and we currently don't say.
   5379 
   5380   // Non-static data members.
   5381   for (auto *Field : ClassDecl->fields()) {
   5382     if (Field->isInvalidDecl())
   5383       continue;
   5384 
   5385     // Don't destroy incomplete or zero-length arrays.
   5386     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
   5387       continue;
   5388 
   5389     QualType FieldType = Context.getBaseElementType(Field->getType());
   5390 
   5391     const RecordType* RT = FieldType->getAs<RecordType>();
   5392     if (!RT)
   5393       continue;
   5394 
   5395     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
   5396     if (FieldClassDecl->isInvalidDecl())
   5397       continue;
   5398     if (FieldClassDecl->hasIrrelevantDestructor())
   5399       continue;
   5400     // The destructor for an implicit anonymous union member is never invoked.
   5401     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
   5402       continue;
   5403 
   5404     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
   5405     assert(Dtor && "No dtor found for FieldClassDecl!");
   5406     CheckDestructorAccess(Field->getLocation(), Dtor,
   5407                           PDiag(diag::err_access_dtor_field)
   5408                             << Field->getDeclName()
   5409                             << FieldType);
   5410 
   5411     MarkFunctionReferenced(Location, Dtor);
   5412     DiagnoseUseOfDecl(Dtor, Location);
   5413   }
   5414 
   5415   // We only potentially invoke the destructors of potentially constructed
   5416   // subobjects.
   5417   bool VisitVirtualBases = !ClassDecl->isAbstract();
   5418 
   5419   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
   5420 
   5421   // Bases.
   5422   for (const auto &Base : ClassDecl->bases()) {
   5423     // Bases are always records in a well-formed non-dependent class.
   5424     const RecordType *RT = Base.getType()->getAs<RecordType>();
   5425 
   5426     // Remember direct virtual bases.
   5427     if (Base.isVirtual()) {
   5428       if (!VisitVirtualBases)
   5429         continue;
   5430       DirectVirtualBases.insert(RT);
   5431     }
   5432 
   5433     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
   5434     // If our base class is invalid, we probably can't get its dtor anyway.
   5435     if (BaseClassDecl->isInvalidDecl())
   5436       continue;
   5437     if (BaseClassDecl->hasIrrelevantDestructor())
   5438       continue;
   5439 
   5440     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
   5441     assert(Dtor && "No dtor found for BaseClassDecl!");
   5442 
   5443     // FIXME: caret should be on the start of the class name
   5444     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
   5445                           PDiag(diag::err_access_dtor_base)
   5446                               << Base.getType() << Base.getSourceRange(),
   5447                           Context.getTypeDeclType(ClassDecl));
   5448 
   5449     MarkFunctionReferenced(Location, Dtor);
   5450     DiagnoseUseOfDecl(Dtor, Location);
   5451   }
   5452 
   5453   if (!VisitVirtualBases)
   5454     return;
   5455 
   5456   // Virtual bases.
   5457   for (const auto &VBase : ClassDecl->vbases()) {
   5458     // Bases are always records in a well-formed non-dependent class.
   5459     const RecordType *RT = VBase.getType()->castAs<RecordType>();
   5460 
   5461     // Ignore direct virtual bases.
   5462     if (DirectVirtualBases.count(RT))
   5463       continue;
   5464 
   5465     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
   5466     // If our base class is invalid, we probably can't get its dtor anyway.
   5467     if (BaseClassDecl->isInvalidDecl())
   5468       continue;
   5469     if (BaseClassDecl->hasIrrelevantDestructor())
   5470       continue;
   5471 
   5472     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
   5473     assert(Dtor && "No dtor found for BaseClassDecl!");
   5474     if (CheckDestructorAccess(
   5475             ClassDecl->getLocation(), Dtor,
   5476             PDiag(diag::err_access_dtor_vbase)
   5477                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
   5478             Context.getTypeDeclType(ClassDecl)) ==
   5479         AR_accessible) {
   5480       CheckDerivedToBaseConversion(
   5481           Context.getTypeDeclType(ClassDecl), VBase.getType(),
   5482           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
   5483           SourceRange(), DeclarationName(), nullptr);
   5484     }
   5485 
   5486     MarkFunctionReferenced(Location, Dtor);
   5487     DiagnoseUseOfDecl(Dtor, Location);
   5488   }
   5489 }
   5490 
   5491 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
   5492   if (!CDtorDecl)
   5493     return;
   5494 
   5495   if (CXXConstructorDecl *Constructor
   5496       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
   5497     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
   5498     DiagnoseUninitializedFields(*this, Constructor);
   5499   }
   5500 }
   5501 
   5502 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
   5503   if (!getLangOpts().CPlusPlus)
   5504     return false;
   5505 
   5506   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
   5507   if (!RD)
   5508     return false;
   5509 
   5510   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
   5511   // class template specialization here, but doing so breaks a lot of code.
   5512 
   5513   // We can't answer whether something is abstract until it has a
   5514   // definition. If it's currently being defined, we'll walk back
   5515   // over all the declarations when we have a full definition.
   5516   const CXXRecordDecl *Def = RD->getDefinition();
   5517   if (!Def || Def->isBeingDefined())
   5518     return false;
   5519 
   5520   return RD->isAbstract();
   5521 }
   5522 
   5523 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
   5524                                   TypeDiagnoser &Diagnoser) {
   5525   if (!isAbstractType(Loc, T))
   5526     return false;
   5527 
   5528   T = Context.getBaseElementType(T);
   5529   Diagnoser.diagnose(*this, Loc, T);
   5530   DiagnoseAbstractType(T->getAsCXXRecordDecl());
   5531   return true;
   5532 }
   5533 
   5534 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
   5535   // Check if we've already emitted the list of pure virtual functions
   5536   // for this class.
   5537   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
   5538     return;
   5539 
   5540   // If the diagnostic is suppressed, don't emit the notes. We're only
   5541   // going to emit them once, so try to attach them to a diagnostic we're
   5542   // actually going to show.
   5543   if (Diags.isLastDiagnosticIgnored())
   5544     return;
   5545 
   5546   CXXFinalOverriderMap FinalOverriders;
   5547   RD->getFinalOverriders(FinalOverriders);
   5548 
   5549   // Keep a set of seen pure methods so we won't diagnose the same method
   5550   // more than once.
   5551   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
   5552 
   5553   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
   5554                                    MEnd = FinalOverriders.end();
   5555        M != MEnd;
   5556        ++M) {
   5557     for (OverridingMethods::iterator SO = M->second.begin(),
   5558                                   SOEnd = M->second.end();
   5559          SO != SOEnd; ++SO) {
   5560       // C++ [class.abstract]p4:
   5561       //   A class is abstract if it contains or inherits at least one
   5562       //   pure virtual function for which the final overrider is pure
   5563       //   virtual.
   5564 
   5565       //
   5566       if (SO->second.size() != 1)
   5567         continue;
   5568 
   5569       if (!SO->second.front().Method->isPure())
   5570         continue;
   5571 
   5572       if (!SeenPureMethods.insert(SO->second.front().Method).second)
   5573         continue;
   5574 
   5575       Diag(SO->second.front().Method->getLocation(),
   5576            diag::note_pure_virtual_function)
   5577         << SO->second.front().Method->getDeclName() << RD->getDeclName();
   5578     }
   5579   }
   5580 
   5581   if (!PureVirtualClassDiagSet)
   5582     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
   5583   PureVirtualClassDiagSet->insert(RD);
   5584 }
   5585 
   5586 namespace {
   5587 struct AbstractUsageInfo {
   5588   Sema &S;
   5589   CXXRecordDecl *Record;
   5590   CanQualType AbstractType;
   5591   bool Invalid;
   5592 
   5593   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
   5594     : S(S), Record(Record),
   5595       AbstractType(S.Context.getCanonicalType(
   5596                    S.Context.getTypeDeclType(Record))),
   5597       Invalid(false) {}
   5598 
   5599   void DiagnoseAbstractType() {
   5600     if (Invalid) return;
   5601     S.DiagnoseAbstractType(Record);
   5602     Invalid = true;
   5603   }
   5604 
   5605   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
   5606 };
   5607 
   5608 struct CheckAbstractUsage {
   5609   AbstractUsageInfo &Info;
   5610   const NamedDecl *Ctx;
   5611 
   5612   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
   5613     : Info(Info), Ctx(Ctx) {}
   5614 
   5615   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
   5616     switch (TL.getTypeLocClass()) {
   5617 #define ABSTRACT_TYPELOC(CLASS, PARENT)
   5618 #define TYPELOC(CLASS, PARENT) \
   5619     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
   5620 #include "clang/AST/TypeLocNodes.def"
   5621     }
   5622   }
   5623 
   5624   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
   5625     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
   5626     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
   5627       if (!TL.getParam(I))
   5628         continue;
   5629 
   5630       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
   5631       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
   5632     }
   5633   }
   5634 
   5635   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
   5636     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
   5637   }
   5638 
   5639   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
   5640     // Visit the type parameters from a permissive context.
   5641     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
   5642       TemplateArgumentLoc TAL = TL.getArgLoc(I);
   5643       if (TAL.getArgument().getKind() == TemplateArgument::Type)
   5644         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
   5645           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
   5646       // TODO: other template argument types?
   5647     }
   5648   }
   5649 
   5650   // Visit pointee types from a permissive context.
   5651 #define CheckPolymorphic(Type) \
   5652   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
   5653     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
   5654   }
   5655   CheckPolymorphic(PointerTypeLoc)
   5656   CheckPolymorphic(ReferenceTypeLoc)
   5657   CheckPolymorphic(MemberPointerTypeLoc)
   5658   CheckPolymorphic(BlockPointerTypeLoc)
   5659   CheckPolymorphic(AtomicTypeLoc)
   5660 
   5661   /// Handle all the types we haven't given a more specific
   5662   /// implementation for above.
   5663   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
   5664     // Every other kind of type that we haven't called out already
   5665     // that has an inner type is either (1) sugar or (2) contains that
   5666     // inner type in some way as a subobject.
   5667     if (TypeLoc Next = TL.getNextTypeLoc())
   5668       return Visit(Next, Sel);
   5669 
   5670     // If there's no inner type and we're in a permissive context,
   5671     // don't diagnose.
   5672     if (Sel == Sema::AbstractNone) return;
   5673 
   5674     // Check whether the type matches the abstract type.
   5675     QualType T = TL.getType();
   5676     if (T->isArrayType()) {
   5677       Sel = Sema::AbstractArrayType;
   5678       T = Info.S.Context.getBaseElementType(T);
   5679     }
   5680     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
   5681     if (CT != Info.AbstractType) return;
   5682 
   5683     // It matched; do some magic.
   5684     if (Sel == Sema::AbstractArrayType) {
   5685       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
   5686         << T << TL.getSourceRange();
   5687     } else {
   5688       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
   5689         << Sel << T << TL.getSourceRange();
   5690     }
   5691     Info.DiagnoseAbstractType();
   5692   }
   5693 };
   5694 
   5695 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
   5696                                   Sema::AbstractDiagSelID Sel) {
   5697   CheckAbstractUsage(*this, D).Visit(TL, Sel);
   5698 }
   5699 
   5700 }
   5701 
   5702 /// Check for invalid uses of an abstract type in a method declaration.
   5703 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
   5704                                     CXXMethodDecl *MD) {
   5705   // No need to do the check on definitions, which require that
   5706   // the return/param types be complete.
   5707   if (MD->doesThisDeclarationHaveABody())
   5708     return;
   5709 
   5710   // For safety's sake, just ignore it if we don't have type source
   5711   // information.  This should never happen for non-implicit methods,
   5712   // but...
   5713   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
   5714     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
   5715 }
   5716 
   5717 /// Check for invalid uses of an abstract type within a class definition.
   5718 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
   5719                                     CXXRecordDecl *RD) {
   5720   for (auto *D : RD->decls()) {
   5721     if (D->isImplicit()) continue;
   5722 
   5723     // Methods and method templates.
   5724     if (isa<CXXMethodDecl>(D)) {
   5725       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
   5726     } else if (isa<FunctionTemplateDecl>(D)) {
   5727       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
   5728       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
   5729 
   5730     // Fields and static variables.
   5731     } else if (isa<FieldDecl>(D)) {
   5732       FieldDecl *FD = cast<FieldDecl>(D);
   5733       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
   5734         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
   5735     } else if (isa<VarDecl>(D)) {
   5736       VarDecl *VD = cast<VarDecl>(D);
   5737       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
   5738         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
   5739 
   5740     // Nested classes and class templates.
   5741     } else if (isa<CXXRecordDecl>(D)) {
   5742       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
   5743     } else if (isa<ClassTemplateDecl>(D)) {
   5744       CheckAbstractClassUsage(Info,
   5745                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
   5746     }
   5747   }
   5748 }
   5749 
   5750 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
   5751   Attr *ClassAttr = getDLLAttr(Class);
   5752   if (!ClassAttr)
   5753     return;
   5754 
   5755   assert(ClassAttr->getKind() == attr::DLLExport);
   5756 
   5757   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
   5758 
   5759   if (TSK == TSK_ExplicitInstantiationDeclaration)
   5760     // Don't go any further if this is just an explicit instantiation
   5761     // declaration.
   5762     return;
   5763 
   5764   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
   5765     S.MarkVTableUsed(Class->getLocation(), Class, true);
   5766 
   5767   for (Decl *Member : Class->decls()) {
   5768     // Defined static variables that are members of an exported base
   5769     // class must be marked export too.
   5770     auto *VD = dyn_cast<VarDecl>(Member);
   5771     if (VD && Member->getAttr<DLLExportAttr>() &&
   5772         VD->getStorageClass() == SC_Static &&
   5773         TSK == TSK_ImplicitInstantiation)
   5774       S.MarkVariableReferenced(VD->getLocation(), VD);
   5775 
   5776     auto *MD = dyn_cast<CXXMethodDecl>(Member);
   5777     if (!MD)
   5778       continue;
   5779 
   5780     if (Member->getAttr<DLLExportAttr>()) {
   5781       if (MD->isUserProvided()) {
   5782         // Instantiate non-default class member functions ...
   5783 
   5784         // .. except for certain kinds of template specializations.
   5785         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
   5786           continue;
   5787 
   5788         S.MarkFunctionReferenced(Class->getLocation(), MD);
   5789 
   5790         // The function will be passed to the consumer when its definition is
   5791         // encountered.
   5792       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
   5793                  MD->isCopyAssignmentOperator() ||
   5794                  MD->isMoveAssignmentOperator()) {
   5795         // Synthesize and instantiate non-trivial implicit methods, explicitly
   5796         // defaulted methods, and the copy and move assignment operators. The
   5797         // latter are exported even if they are trivial, because the address of
   5798         // an operator can be taken and should compare equal across libraries.
   5799         DiagnosticErrorTrap Trap(S.Diags);
   5800         S.MarkFunctionReferenced(Class->getLocation(), MD);
   5801         if (Trap.hasErrorOccurred()) {
   5802           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
   5803               << Class << !S.getLangOpts().CPlusPlus11;
   5804           break;
   5805         }
   5806 
   5807         // There is no later point when we will see the definition of this
   5808         // function, so pass it to the consumer now.
   5809         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
   5810       }
   5811     }
   5812   }
   5813 }
   5814 
   5815 static void checkForMultipleExportedDefaultConstructors(Sema &S,
   5816                                                         CXXRecordDecl *Class) {
   5817   // Only the MS ABI has default constructor closures, so we don't need to do
   5818   // this semantic checking anywhere else.
   5819   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
   5820     return;
   5821 
   5822   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
   5823   for (Decl *Member : Class->decls()) {
   5824     // Look for exported default constructors.
   5825     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
   5826     if (!CD || !CD->isDefaultConstructor())
   5827       continue;
   5828     auto *Attr = CD->getAttr<DLLExportAttr>();
   5829     if (!Attr)
   5830       continue;
   5831 
   5832     // If the class is non-dependent, mark the default arguments as ODR-used so
   5833     // that we can properly codegen the constructor closure.
   5834     if (!Class->isDependentContext()) {
   5835       for (ParmVarDecl *PD : CD->parameters()) {
   5836         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
   5837         S.DiscardCleanupsInEvaluationContext();
   5838       }
   5839     }
   5840 
   5841     if (LastExportedDefaultCtor) {
   5842       S.Diag(LastExportedDefaultCtor->getLocation(),
   5843              diag::err_attribute_dll_ambiguous_default_ctor)
   5844           << Class;
   5845       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
   5846           << CD->getDeclName();
   5847       return;
   5848     }
   5849     LastExportedDefaultCtor = CD;
   5850   }
   5851 }
   5852 
   5853 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
   5854   // Mark any compiler-generated routines with the implicit code_seg attribute.
   5855   for (auto *Method : Class->methods()) {
   5856     if (Method->isUserProvided())
   5857       continue;
   5858     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
   5859       Method->addAttr(A);
   5860   }
   5861 }
   5862 
   5863 /// Check class-level dllimport/dllexport attribute.
   5864 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
   5865   Attr *ClassAttr = getDLLAttr(Class);
   5866 
   5867   // MSVC inherits DLL attributes to partial class template specializations.
   5868   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
   5869     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
   5870       if (Attr *TemplateAttr =
   5871               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
   5872         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
   5873         A->setInherited(true);
   5874         ClassAttr = A;
   5875       }
   5876     }
   5877   }
   5878 
   5879   if (!ClassAttr)
   5880     return;
   5881 
   5882   if (!Class->isExternallyVisible()) {
   5883     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
   5884         << Class << ClassAttr;
   5885     return;
   5886   }
   5887 
   5888   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   5889       !ClassAttr->isInherited()) {
   5890     // Diagnose dll attributes on members of class with dll attribute.
   5891     for (Decl *Member : Class->decls()) {
   5892       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
   5893         continue;
   5894       InheritableAttr *MemberAttr = getDLLAttr(Member);
   5895       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
   5896         continue;
   5897 
   5898       Diag(MemberAttr->getLocation(),
   5899              diag::err_attribute_dll_member_of_dll_class)
   5900           << MemberAttr << ClassAttr;
   5901       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
   5902       Member->setInvalidDecl();
   5903     }
   5904   }
   5905 
   5906   if (Class->getDescribedClassTemplate())
   5907     // Don't inherit dll attribute until the template is instantiated.
   5908     return;
   5909 
   5910   // The class is either imported or exported.
   5911   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
   5912 
   5913   // Check if this was a dllimport attribute propagated from a derived class to
   5914   // a base class template specialization. We don't apply these attributes to
   5915   // static data members.
   5916   const bool PropagatedImport =
   5917       !ClassExported &&
   5918       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
   5919 
   5920   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
   5921 
   5922   // Ignore explicit dllexport on explicit class template instantiation
   5923   // declarations, except in MinGW mode.
   5924   if (ClassExported && !ClassAttr->isInherited() &&
   5925       TSK == TSK_ExplicitInstantiationDeclaration &&
   5926       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
   5927     Class->dropAttr<DLLExportAttr>();
   5928     return;
   5929   }
   5930 
   5931   // Force declaration of implicit members so they can inherit the attribute.
   5932   ForceDeclarationOfImplicitMembers(Class);
   5933 
   5934   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
   5935   // seem to be true in practice?
   5936 
   5937   for (Decl *Member : Class->decls()) {
   5938     VarDecl *VD = dyn_cast<VarDecl>(Member);
   5939     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
   5940 
   5941     // Only methods and static fields inherit the attributes.
   5942     if (!VD && !MD)
   5943       continue;
   5944 
   5945     if (MD) {
   5946       // Don't process deleted methods.
   5947       if (MD->isDeleted())
   5948         continue;
   5949 
   5950       if (MD->isInlined()) {
   5951         // MinGW does not import or export inline methods. But do it for
   5952         // template instantiations.
   5953         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   5954             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
   5955             TSK != TSK_ExplicitInstantiationDeclaration &&
   5956             TSK != TSK_ExplicitInstantiationDefinition)
   5957           continue;
   5958 
   5959         // MSVC versions before 2015 don't export the move assignment operators
   5960         // and move constructor, so don't attempt to import/export them if
   5961         // we have a definition.
   5962         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
   5963         if ((MD->isMoveAssignmentOperator() ||
   5964              (Ctor && Ctor->isMoveConstructor())) &&
   5965             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
   5966           continue;
   5967 
   5968         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
   5969         // operator is exported anyway.
   5970         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
   5971             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
   5972           continue;
   5973       }
   5974     }
   5975 
   5976     // Don't apply dllimport attributes to static data members of class template
   5977     // instantiations when the attribute is propagated from a derived class.
   5978     if (VD && PropagatedImport)
   5979       continue;
   5980 
   5981     if (!cast<NamedDecl>(Member)->isExternallyVisible())
   5982       continue;
   5983 
   5984     if (!getDLLAttr(Member)) {
   5985       InheritableAttr *NewAttr = nullptr;
   5986 
   5987       // Do not export/import inline function when -fno-dllexport-inlines is
   5988       // passed. But add attribute for later local static var check.
   5989       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
   5990           TSK != TSK_ExplicitInstantiationDeclaration &&
   5991           TSK != TSK_ExplicitInstantiationDefinition) {
   5992         if (ClassExported) {
   5993           NewAttr = ::new (getASTContext())
   5994               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
   5995         } else {
   5996           NewAttr = ::new (getASTContext())
   5997               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
   5998         }
   5999       } else {
   6000         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
   6001       }
   6002 
   6003       NewAttr->setInherited(true);
   6004       Member->addAttr(NewAttr);
   6005 
   6006       if (MD) {
   6007         // Propagate DLLAttr to friend re-declarations of MD that have already
   6008         // been constructed.
   6009         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
   6010              FD = FD->getPreviousDecl()) {
   6011           if (FD->getFriendObjectKind() == Decl::FOK_None)
   6012             continue;
   6013           assert(!getDLLAttr(FD) &&
   6014                  "friend re-decl should not already have a DLLAttr");
   6015           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
   6016           NewAttr->setInherited(true);
   6017           FD->addAttr(NewAttr);
   6018         }
   6019       }
   6020     }
   6021   }
   6022 
   6023   if (ClassExported)
   6024     DelayedDllExportClasses.push_back(Class);
   6025 }
   6026 
   6027 /// Perform propagation of DLL attributes from a derived class to a
   6028 /// templated base class for MS compatibility.
   6029 void Sema::propagateDLLAttrToBaseClassTemplate(
   6030     CXXRecordDecl *Class, Attr *ClassAttr,
   6031     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
   6032   if (getDLLAttr(
   6033           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
   6034     // If the base class template has a DLL attribute, don't try to change it.
   6035     return;
   6036   }
   6037 
   6038   auto TSK = BaseTemplateSpec->getSpecializationKind();
   6039   if (!getDLLAttr(BaseTemplateSpec) &&
   6040       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
   6041        TSK == TSK_ImplicitInstantiation)) {
   6042     // The template hasn't been instantiated yet (or it has, but only as an
   6043     // explicit instantiation declaration or implicit instantiation, which means
   6044     // we haven't codegenned any members yet), so propagate the attribute.
   6045     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
   6046     NewAttr->setInherited(true);
   6047     BaseTemplateSpec->addAttr(NewAttr);
   6048 
   6049     // If this was an import, mark that we propagated it from a derived class to
   6050     // a base class template specialization.
   6051     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
   6052       ImportAttr->setPropagatedToBaseTemplate();
   6053 
   6054     // If the template is already instantiated, checkDLLAttributeRedeclaration()
   6055     // needs to be run again to work see the new attribute. Otherwise this will
   6056     // get run whenever the template is instantiated.
   6057     if (TSK != TSK_Undeclared)
   6058       checkClassLevelDLLAttribute(BaseTemplateSpec);
   6059 
   6060     return;
   6061   }
   6062 
   6063   if (getDLLAttr(BaseTemplateSpec)) {
   6064     // The template has already been specialized or instantiated with an
   6065     // attribute, explicitly or through propagation. We should not try to change
   6066     // it.
   6067     return;
   6068   }
   6069 
   6070   // The template was previously instantiated or explicitly specialized without
   6071   // a dll attribute, It's too late for us to add an attribute, so warn that
   6072   // this is unsupported.
   6073   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
   6074       << BaseTemplateSpec->isExplicitSpecialization();
   6075   Diag(ClassAttr->getLocation(), diag::note_attribute);
   6076   if (BaseTemplateSpec->isExplicitSpecialization()) {
   6077     Diag(BaseTemplateSpec->getLocation(),
   6078            diag::note_template_class_explicit_specialization_was_here)
   6079         << BaseTemplateSpec;
   6080   } else {
   6081     Diag(BaseTemplateSpec->getPointOfInstantiation(),
   6082            diag::note_template_class_instantiation_was_here)
   6083         << BaseTemplateSpec;
   6084   }
   6085 }
   6086 
   6087 /// Determine the kind of defaulting that would be done for a given function.
   6088 ///
   6089 /// If the function is both a default constructor and a copy / move constructor
   6090 /// (due to having a default argument for the first parameter), this picks
   6091 /// CXXDefaultConstructor.
   6092 ///
   6093 /// FIXME: Check that case is properly handled by all callers.
   6094 Sema::DefaultedFunctionKind
   6095 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
   6096   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
   6097     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
   6098       if (Ctor->isDefaultConstructor())
   6099         return Sema::CXXDefaultConstructor;
   6100 
   6101       if (Ctor->isCopyConstructor())
   6102         return Sema::CXXCopyConstructor;
   6103 
   6104       if (Ctor->isMoveConstructor())
   6105         return Sema::CXXMoveConstructor;
   6106     }
   6107 
   6108     if (MD->isCopyAssignmentOperator())
   6109       return Sema::CXXCopyAssignment;
   6110 
   6111     if (MD->isMoveAssignmentOperator())
   6112       return Sema::CXXMoveAssignment;
   6113 
   6114     if (isa<CXXDestructorDecl>(FD))
   6115       return Sema::CXXDestructor;
   6116   }
   6117 
   6118   switch (FD->getDeclName().getCXXOverloadedOperator()) {
   6119   case OO_EqualEqual:
   6120     return DefaultedComparisonKind::Equal;
   6121 
   6122   case OO_ExclaimEqual:
   6123     return DefaultedComparisonKind::NotEqual;
   6124 
   6125   case OO_Spaceship:
   6126     // No point allowing this if <=> doesn't exist in the current language mode.
   6127     if (!getLangOpts().CPlusPlus2a)
   6128       break;
   6129     return DefaultedComparisonKind::ThreeWay;
   6130 
   6131   case OO_Less:
   6132   case OO_LessEqual:
   6133   case OO_Greater:
   6134   case OO_GreaterEqual:
   6135     // No point allowing this if <=> doesn't exist in the current language mode.
   6136     if (!getLangOpts().CPlusPlus2a)
   6137       break;
   6138     return DefaultedComparisonKind::Relational;
   6139 
   6140   default:
   6141     break;
   6142   }
   6143 
   6144   // Not defaultable.
   6145   return DefaultedFunctionKind();
   6146 }
   6147 
   6148 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
   6149                                         SourceLocation DefaultLoc) {
   6150   switch (S.getSpecialMember(MD)) {
   6151   case Sema::CXXDefaultConstructor:
   6152     S.DefineImplicitDefaultConstructor(DefaultLoc,
   6153                                        cast<CXXConstructorDecl>(MD));
   6154     break;
   6155   case Sema::CXXCopyConstructor:
   6156     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
   6157     break;
   6158   case Sema::CXXCopyAssignment:
   6159     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
   6160     break;
   6161   case Sema::CXXDestructor:
   6162     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
   6163     break;
   6164   case Sema::CXXMoveConstructor:
   6165     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
   6166     break;
   6167   case Sema::CXXMoveAssignment:
   6168     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
   6169     break;
   6170   case Sema::CXXInvalid:
   6171     llvm_unreachable("Invalid special member.");
   6172   }
   6173 }
   6174 
   6175 /// Determine whether a type is permitted to be passed or returned in
   6176 /// registers, per C++ [class.temporary]p3.
   6177 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
   6178                                TargetInfo::CallingConvKind CCK) {
   6179   if (D->isDependentType() || D->isInvalidDecl())
   6180     return false;
   6181 
   6182   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
   6183   // The PS4 platform ABI follows the behavior of Clang 3.2.
   6184   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
   6185     return !D->hasNonTrivialDestructorForCall() &&
   6186            !D->hasNonTrivialCopyConstructorForCall();
   6187 
   6188   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
   6189     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
   6190     bool DtorIsTrivialForCall = false;
   6191 
   6192     // If a class has at least one non-deleted, trivial copy constructor, it
   6193     // is passed according to the C ABI. Otherwise, it is passed indirectly.
   6194     //
   6195     // Note: This permits classes with non-trivial copy or move ctors to be
   6196     // passed in registers, so long as they *also* have a trivial copy ctor,
   6197     // which is non-conforming.
   6198     if (D->needsImplicitCopyConstructor()) {
   6199       if (!D->defaultedCopyConstructorIsDeleted()) {
   6200         if (D->hasTrivialCopyConstructor())
   6201           CopyCtorIsTrivial = true;
   6202         if (D->hasTrivialCopyConstructorForCall())
   6203           CopyCtorIsTrivialForCall = true;
   6204       }
   6205     } else {
   6206       for (const CXXConstructorDecl *CD : D->ctors()) {
   6207         if (CD->isCopyConstructor() && !CD->isDeleted()) {
   6208           if (CD->isTrivial())
   6209             CopyCtorIsTrivial = true;
   6210           if (CD->isTrivialForCall())
   6211             CopyCtorIsTrivialForCall = true;
   6212         }
   6213       }
   6214     }
   6215 
   6216     if (D->needsImplicitDestructor()) {
   6217       if (!D->defaultedDestructorIsDeleted() &&
   6218           D->hasTrivialDestructorForCall())
   6219         DtorIsTrivialForCall = true;
   6220     } else if (const auto *DD = D->getDestructor()) {
   6221       if (!DD->isDeleted() && DD->isTrivialForCall())
   6222         DtorIsTrivialForCall = true;
   6223     }
   6224 
   6225     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
   6226     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
   6227       return true;
   6228 
   6229     // If a class has a destructor, we'd really like to pass it indirectly
   6230     // because it allows us to elide copies.  Unfortunately, MSVC makes that
   6231     // impossible for small types, which it will pass in a single register or
   6232     // stack slot. Most objects with dtors are large-ish, so handle that early.
   6233     // We can't call out all large objects as being indirect because there are
   6234     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
   6235     // how we pass large POD types.
   6236 
   6237     // Note: This permits small classes with nontrivial destructors to be
   6238     // passed in registers, which is non-conforming.
   6239     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
   6240     uint64_t TypeSize = isAArch64 ? 128 : 64;
   6241 
   6242     if (CopyCtorIsTrivial &&
   6243         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
   6244       return true;
   6245     return false;
   6246   }
   6247 
   6248   // Per C++ [class.temporary]p3, the relevant condition is:
   6249   //   each copy constructor, move constructor, and destructor of X is
   6250   //   either trivial or deleted, and X has at least one non-deleted copy
   6251   //   or move constructor
   6252   bool HasNonDeletedCopyOrMove = false;
   6253 
   6254   if (D->needsImplicitCopyConstructor() &&
   6255       !D->defaultedCopyConstructorIsDeleted()) {
   6256     if (!D->hasTrivialCopyConstructorForCall())
   6257       return false;
   6258     HasNonDeletedCopyOrMove = true;
   6259   }
   6260 
   6261   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
   6262       !D->defaultedMoveConstructorIsDeleted()) {
   6263     if (!D->hasTrivialMoveConstructorForCall())
   6264       return false;
   6265     HasNonDeletedCopyOrMove = true;
   6266   }
   6267 
   6268   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
   6269       !D->hasTrivialDestructorForCall())
   6270     return false;
   6271 
   6272   for (const CXXMethodDecl *MD : D->methods()) {
   6273     if (MD->isDeleted())
   6274       continue;
   6275 
   6276     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
   6277     if (CD && CD->isCopyOrMoveConstructor())
   6278       HasNonDeletedCopyOrMove = true;
   6279     else if (!isa<CXXDestructorDecl>(MD))
   6280       continue;
   6281 
   6282     if (!MD->isTrivialForCall())
   6283       return false;
   6284   }
   6285 
   6286   return HasNonDeletedCopyOrMove;
   6287 }
   6288 
   6289 /// Perform semantic checks on a class definition that has been
   6290 /// completing, introducing implicitly-declared members, checking for
   6291 /// abstract types, etc.
   6292 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
   6293   if (!Record)
   6294     return;
   6295 
   6296   if (Record->isAbstract() && !Record->isInvalidDecl()) {
   6297     AbstractUsageInfo Info(*this, Record);
   6298     CheckAbstractClassUsage(Info, Record);
   6299   }
   6300 
   6301   // If this is not an aggregate type and has no user-declared constructor,
   6302   // complain about any non-static data members of reference or const scalar
   6303   // type, since they will never get initializers.
   6304   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
   6305       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
   6306       !Record->isLambda()) {
   6307     bool Complained = false;
   6308     for (const auto *F : Record->fields()) {
   6309       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
   6310         continue;
   6311 
   6312       if (F->getType()->isReferenceType() ||
   6313           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
   6314         if (!Complained) {
   6315           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
   6316             << Record->getTagKind() << Record;
   6317           Complained = true;
   6318         }
   6319 
   6320         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
   6321           << F->getType()->isReferenceType()
   6322           << F->getDeclName();
   6323       }
   6324     }
   6325   }
   6326 
   6327   if (Record->getIdentifier()) {
   6328     // C++ [class.mem]p13:
   6329     //   If T is the name of a class, then each of the following shall have a
   6330     //   name different from T:
   6331     //     - every member of every anonymous union that is a member of class T.
   6332     //
   6333     // C++ [class.mem]p14:
   6334     //   In addition, if class T has a user-declared constructor (12.1), every
   6335     //   non-static data member of class T shall have a name different from T.
   6336     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
   6337     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
   6338          ++I) {
   6339       NamedDecl *D = (*I)->getUnderlyingDecl();
   6340       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
   6341            Record->hasUserDeclaredConstructor()) ||
   6342           isa<IndirectFieldDecl>(D)) {
   6343         Diag((*I)->getLocation(), diag::err_member_name_of_class)
   6344           << D->getDeclName();
   6345         break;
   6346       }
   6347     }
   6348   }
   6349 
   6350   // Warn if the class has virtual methods but non-virtual public destructor.
   6351   if (Record->isPolymorphic() && !Record->isDependentType()) {
   6352     CXXDestructorDecl *dtor = Record->getDestructor();
   6353     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
   6354         !Record->hasAttr<FinalAttr>())
   6355       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
   6356            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
   6357   }
   6358 
   6359   if (Record->isAbstract()) {
   6360     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
   6361       Diag(Record->getLocation(), diag::warn_abstract_final_class)
   6362         << FA->isSpelledAsSealed();
   6363       DiagnoseAbstractType(Record);
   6364     }
   6365   }
   6366 
   6367   // Warn if the class has a final destructor but is not itself marked final.
   6368   if (!Record->hasAttr<FinalAttr>()) {
   6369     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
   6370       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
   6371         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
   6372             << FA->isSpelledAsSealed()
   6373             << FixItHint::CreateInsertion(
   6374                    getLocForEndOfToken(Record->getLocation()),
   6375                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
   6376         Diag(Record->getLocation(),
   6377              diag::note_final_dtor_non_final_class_silence)
   6378             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
   6379       }
   6380     }
   6381   }
   6382 
   6383   // See if trivial_abi has to be dropped.
   6384   if (Record->hasAttr<TrivialABIAttr>())
   6385     checkIllFormedTrivialABIStruct(*Record);
   6386 
   6387   // Set HasTrivialSpecialMemberForCall if the record has attribute
   6388   // "trivial_abi".
   6389   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
   6390 
   6391   if (HasTrivialABI)
   6392     Record->setHasTrivialSpecialMemberForCall();
   6393 
   6394   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
   6395     // Check whether the explicitly-defaulted members are valid.
   6396     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
   6397       CheckExplicitlyDefaultedFunction(M);
   6398 
   6399     // For an explicitly defaulted or deleted special member, we defer
   6400     // determining triviality until the class is complete. That time is now!
   6401     CXXSpecialMember CSM = getSpecialMember(M);
   6402     if (!M->isImplicit() && !M->isUserProvided()) {
   6403       if (CSM != CXXInvalid) {
   6404         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
   6405         // Inform the class that we've finished declaring this member.
   6406         Record->finishedDefaultedOrDeletedMember(M);
   6407         M->setTrivialForCall(
   6408             HasTrivialABI ||
   6409             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
   6410         Record->setTrivialForCallFlags(M);
   6411       }
   6412     }
   6413 
   6414     // Set triviality for the purpose of calls if this is a user-provided
   6415     // copy/move constructor or destructor.
   6416     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
   6417          CSM == CXXDestructor) && M->isUserProvided()) {
   6418       M->setTrivialForCall(HasTrivialABI);
   6419       Record->setTrivialForCallFlags(M);
   6420     }
   6421 
   6422     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
   6423         M->hasAttr<DLLExportAttr>()) {
   6424       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
   6425           M->isTrivial() &&
   6426           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
   6427            CSM == CXXDestructor))
   6428         M->dropAttr<DLLExportAttr>();
   6429 
   6430       if (M->hasAttr<DLLExportAttr>()) {
   6431         // Define after any fields with in-class initializers have been parsed.
   6432         DelayedDllExportMemberFunctions.push_back(M);
   6433       }
   6434     }
   6435 
   6436     // Define defaulted constexpr virtual functions that override a base class
   6437     // function right away.
   6438     // FIXME: We can defer doing this until the vtable is marked as used.
   6439     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
   6440       DefineImplicitSpecialMember(*this, M, M->getLocation());
   6441   };
   6442 
   6443   bool HasMethodWithOverrideControl = false,
   6444        HasOverridingMethodWithoutOverrideControl = false;
   6445   if (!Record->isDependentType()) {
   6446     // Check the destructor before any other member function. We need to
   6447     // determine whether it's trivial in order to determine whether the claas
   6448     // type is a literal type, which is a prerequisite for determining whether
   6449     // other special member functions are valid and whether they're implicitly
   6450     // 'constexpr'.
   6451     if (CXXDestructorDecl *Dtor = Record->getDestructor())
   6452       CompleteMemberFunction(Dtor);
   6453 
   6454     for (auto *M : Record->methods()) {
   6455       // See if a method overloads virtual methods in a base
   6456       // class without overriding any.
   6457       if (!M->isStatic())
   6458         DiagnoseHiddenVirtualMethods(M);
   6459       if (M->hasAttr<OverrideAttr>())
   6460         HasMethodWithOverrideControl = true;
   6461       else if (M->size_overridden_methods() > 0)
   6462         HasOverridingMethodWithoutOverrideControl = true;
   6463 
   6464       if (!isa<CXXDestructorDecl>(M))
   6465         CompleteMemberFunction(M);
   6466     }
   6467   }
   6468 
   6469   if (HasMethodWithOverrideControl &&
   6470       HasOverridingMethodWithoutOverrideControl) {
   6471     // At least one method has the 'override' control declared.
   6472     // Diagnose all other overridden methods which do not have 'override' specified on them.
   6473     for (auto *M : Record->methods())
   6474       DiagnoseAbsenceOfOverrideControl(M);
   6475   }
   6476 
   6477   // Process any defaulted friends in the member-specification.
   6478   if (!Record->isDependentType()) {
   6479     for (FriendDecl *D : Record->friends()) {
   6480       auto *FD = dyn_cast_or_null<FunctionDecl>(D->getFriendDecl());
   6481       if (FD && !FD->isInvalidDecl() && FD->isExplicitlyDefaulted())
   6482         CheckExplicitlyDefaultedFunction(FD);
   6483     }
   6484   }
   6485 
   6486   // ms_struct is a request to use the same ABI rules as MSVC.  Check
   6487   // whether this class uses any C++ features that are implemented
   6488   // completely differently in MSVC, and if so, emit a diagnostic.
   6489   // That diagnostic defaults to an error, but we allow projects to
   6490   // map it down to a warning (or ignore it).  It's a fairly common
   6491   // practice among users of the ms_struct pragma to mass-annotate
   6492   // headers, sweeping up a bunch of types that the project doesn't
   6493   // really rely on MSVC-compatible layout for.  We must therefore
   6494   // support "ms_struct except for C++ stuff" as a secondary ABI.
   6495   if (Record->isMsStruct(Context) &&
   6496       (Record->isPolymorphic() || Record->getNumBases())) {
   6497     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
   6498   }
   6499 
   6500   checkClassLevelDLLAttribute(Record);
   6501   checkClassLevelCodeSegAttribute(Record);
   6502 
   6503   bool ClangABICompat4 =
   6504       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
   6505   TargetInfo::CallingConvKind CCK =
   6506       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
   6507   bool CanPass = canPassInRegisters(*this, Record, CCK);
   6508 
   6509   // Do not change ArgPassingRestrictions if it has already been set to
   6510   // APK_CanNeverPassInRegs.
   6511   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
   6512     Record->setArgPassingRestrictions(CanPass
   6513                                           ? RecordDecl::APK_CanPassInRegs
   6514                                           : RecordDecl::APK_CannotPassInRegs);
   6515 
   6516   // If canPassInRegisters returns true despite the record having a non-trivial
   6517   // destructor, the record is destructed in the callee. This happens only when
   6518   // the record or one of its subobjects has a field annotated with trivial_abi
   6519   // or a field qualified with ObjC __strong/__weak.
   6520   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
   6521     Record->setParamDestroyedInCallee(true);
   6522   else if (Record->hasNonTrivialDestructor())
   6523     Record->setParamDestroyedInCallee(CanPass);
   6524 
   6525   if (getLangOpts().ForceEmitVTables) {
   6526     // If we want to emit all the vtables, we need to mark it as used.  This
   6527     // is especially required for cases like vtable assumption loads.
   6528     MarkVTableUsed(Record->getInnerLocStart(), Record);
   6529   }
   6530 }
   6531 
   6532 /// Look up the special member function that would be called by a special
   6533 /// member function for a subobject of class type.
   6534 ///
   6535 /// \param Class The class type of the subobject.
   6536 /// \param CSM The kind of special member function.
   6537 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
   6538 /// \param ConstRHS True if this is a copy operation with a const object
   6539 ///        on its RHS, that is, if the argument to the outer special member
   6540 ///        function is 'const' and this is not a field marked 'mutable'.
   6541 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
   6542     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
   6543     unsigned FieldQuals, bool ConstRHS) {
   6544   unsigned LHSQuals = 0;
   6545   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
   6546     LHSQuals = FieldQuals;
   6547 
   6548   unsigned RHSQuals = FieldQuals;
   6549   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
   6550     RHSQuals = 0;
   6551   else if (ConstRHS)
   6552     RHSQuals |= Qualifiers::Const;
   6553 
   6554   return S.LookupSpecialMember(Class, CSM,
   6555                                RHSQuals & Qualifiers::Const,
   6556                                RHSQuals & Qualifiers::Volatile,
   6557                                false,
   6558                                LHSQuals & Qualifiers::Const,
   6559                                LHSQuals & Qualifiers::Volatile);
   6560 }
   6561 
   6562 class Sema::InheritedConstructorInfo {
   6563   Sema &S;
   6564   SourceLocation UseLoc;
   6565 
   6566   /// A mapping from the base classes through which the constructor was
   6567   /// inherited to the using shadow declaration in that base class (or a null
   6568   /// pointer if the constructor was declared in that base class).
   6569   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
   6570       InheritedFromBases;
   6571 
   6572 public:
   6573   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
   6574                            ConstructorUsingShadowDecl *Shadow)
   6575       : S(S), UseLoc(UseLoc) {
   6576     bool DiagnosedMultipleConstructedBases = false;
   6577     CXXRecordDecl *ConstructedBase = nullptr;
   6578     UsingDecl *ConstructedBaseUsing = nullptr;
   6579 
   6580     // Find the set of such base class subobjects and check that there's a
   6581     // unique constructed subobject.
   6582     for (auto *D : Shadow->redecls()) {
   6583       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
   6584       auto *DNominatedBase = DShadow->getNominatedBaseClass();
   6585       auto *DConstructedBase = DShadow->getConstructedBaseClass();
   6586 
   6587       InheritedFromBases.insert(
   6588           std::make_pair(DNominatedBase->getCanonicalDecl(),
   6589                          DShadow->getNominatedBaseClassShadowDecl()));
   6590       if (DShadow->constructsVirtualBase())
   6591         InheritedFromBases.insert(
   6592             std::make_pair(DConstructedBase->getCanonicalDecl(),
   6593                            DShadow->getConstructedBaseClassShadowDecl()));
   6594       else
   6595         assert(DNominatedBase == DConstructedBase);
   6596 
   6597       // [class.inhctor.init]p2:
   6598       //   If the constructor was inherited from multiple base class subobjects
   6599       //   of type B, the program is ill-formed.
   6600       if (!ConstructedBase) {
   6601         ConstructedBase = DConstructedBase;
   6602         ConstructedBaseUsing = D->getUsingDecl();
   6603       } else if (ConstructedBase != DConstructedBase &&
   6604                  !Shadow->isInvalidDecl()) {
   6605         if (!DiagnosedMultipleConstructedBases) {
   6606           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
   6607               << Shadow->getTargetDecl();
   6608           S.Diag(ConstructedBaseUsing->getLocation(),
   6609                diag::note_ambiguous_inherited_constructor_using)
   6610               << ConstructedBase;
   6611           DiagnosedMultipleConstructedBases = true;
   6612         }
   6613         S.Diag(D->getUsingDecl()->getLocation(),
   6614                diag::note_ambiguous_inherited_constructor_using)
   6615             << DConstructedBase;
   6616       }
   6617     }
   6618 
   6619     if (DiagnosedMultipleConstructedBases)
   6620       Shadow->setInvalidDecl();
   6621   }
   6622 
   6623   /// Find the constructor to use for inherited construction of a base class,
   6624   /// and whether that base class constructor inherits the constructor from a
   6625   /// virtual base class (in which case it won't actually invoke it).
   6626   std::pair<CXXConstructorDecl *, bool>
   6627   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
   6628     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
   6629     if (It == InheritedFromBases.end())
   6630       return std::make_pair(nullptr, false);
   6631 
   6632     // This is an intermediary class.
   6633     if (It->second)
   6634       return std::make_pair(
   6635           S.findInheritingConstructor(UseLoc, Ctor, It->second),
   6636           It->second->constructsVirtualBase());
   6637 
   6638     // This is the base class from which the constructor was inherited.
   6639     return std::make_pair(Ctor, false);
   6640   }
   6641 };
   6642 
   6643 /// Is the special member function which would be selected to perform the
   6644 /// specified operation on the specified class type a constexpr constructor?
   6645 static bool
   6646 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
   6647                          Sema::CXXSpecialMember CSM, unsigned Quals,
   6648                          bool ConstRHS,
   6649                          CXXConstructorDecl *InheritedCtor = nullptr,
   6650                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
   6651   // If we're inheriting a constructor, see if we need to call it for this base
   6652   // class.
   6653   if (InheritedCtor) {
   6654     assert(CSM == Sema::CXXDefaultConstructor);
   6655     auto BaseCtor =
   6656         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
   6657     if (BaseCtor)
   6658       return BaseCtor->isConstexpr();
   6659   }
   6660 
   6661   if (CSM == Sema::CXXDefaultConstructor)
   6662     return ClassDecl->hasConstexprDefaultConstructor();
   6663   if (CSM == Sema::CXXDestructor)
   6664     return ClassDecl->hasConstexprDestructor();
   6665 
   6666   Sema::SpecialMemberOverloadResult SMOR =
   6667       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
   6668   if (!SMOR.getMethod())
   6669     // A constructor we wouldn't select can't be "involved in initializing"
   6670     // anything.
   6671     return true;
   6672   return SMOR.getMethod()->isConstexpr();
   6673 }
   6674 
   6675 /// Determine whether the specified special member function would be constexpr
   6676 /// if it were implicitly defined.
   6677 static bool defaultedSpecialMemberIsConstexpr(
   6678     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
   6679     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
   6680     Sema::InheritedConstructorInfo *Inherited = nullptr) {
   6681   if (!S.getLangOpts().CPlusPlus11)
   6682     return false;
   6683 
   6684   // C++11 [dcl.constexpr]p4:
   6685   // In the definition of a constexpr constructor [...]
   6686   bool Ctor = true;
   6687   switch (CSM) {
   6688   case Sema::CXXDefaultConstructor:
   6689     if (Inherited)
   6690       break;
   6691     // Since default constructor lookup is essentially trivial (and cannot
   6692     // involve, for instance, template instantiation), we compute whether a
   6693     // defaulted default constructor is constexpr directly within CXXRecordDecl.
   6694     //
   6695     // This is important for performance; we need to know whether the default
   6696     // constructor is constexpr to determine whether the type is a literal type.
   6697     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
   6698 
   6699   case Sema::CXXCopyConstructor:
   6700   case Sema::CXXMoveConstructor:
   6701     // For copy or move constructors, we need to perform overload resolution.
   6702     break;
   6703 
   6704   case Sema::CXXCopyAssignment:
   6705   case Sema::CXXMoveAssignment:
   6706     if (!S.getLangOpts().CPlusPlus14)
   6707       return false;
   6708     // In C++1y, we need to perform overload resolution.
   6709     Ctor = false;
   6710     break;
   6711 
   6712   case Sema::CXXDestructor:
   6713     return ClassDecl->defaultedDestructorIsConstexpr();
   6714 
   6715   case Sema::CXXInvalid:
   6716     return false;
   6717   }
   6718 
   6719   //   -- if the class is a non-empty union, or for each non-empty anonymous
   6720   //      union member of a non-union class, exactly one non-static data member
   6721   //      shall be initialized; [DR1359]
   6722   //
   6723   // If we squint, this is guaranteed, since exactly one non-static data member
   6724   // will be initialized (if the constructor isn't deleted), we just don't know
   6725   // which one.
   6726   if (Ctor && ClassDecl->isUnion())
   6727     return CSM == Sema::CXXDefaultConstructor
   6728                ? ClassDecl->hasInClassInitializer() ||
   6729                      !ClassDecl->hasVariantMembers()
   6730                : true;
   6731 
   6732   //   -- the class shall not have any virtual base classes;
   6733   if (Ctor && ClassDecl->getNumVBases())
   6734     return false;
   6735 
   6736   // C++1y [class.copy]p26:
   6737   //   -- [the class] is a literal type, and
   6738   if (!Ctor && !ClassDecl->isLiteral())
   6739     return false;
   6740 
   6741   //   -- every constructor involved in initializing [...] base class
   6742   //      sub-objects shall be a constexpr constructor;
   6743   //   -- the assignment operator selected to copy/move each direct base
   6744   //      class is a constexpr function, and
   6745   for (const auto &B : ClassDecl->bases()) {
   6746     const RecordType *BaseType = B.getType()->getAs<RecordType>();
   6747     if (!BaseType) continue;
   6748 
   6749     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   6750     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
   6751                                   InheritedCtor, Inherited))
   6752       return false;
   6753   }
   6754 
   6755   //   -- every constructor involved in initializing non-static data members
   6756   //      [...] shall be a constexpr constructor;
   6757   //   -- every non-static data member and base class sub-object shall be
   6758   //      initialized
   6759   //   -- for each non-static data member of X that is of class type (or array
   6760   //      thereof), the assignment operator selected to copy/move that member is
   6761   //      a constexpr function
   6762   for (const auto *F : ClassDecl->fields()) {
   6763     if (F->isInvalidDecl())
   6764       continue;
   6765     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
   6766       continue;
   6767     QualType BaseType = S.Context.getBaseElementType(F->getType());
   6768     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
   6769       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
   6770       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
   6771                                     BaseType.getCVRQualifiers(),
   6772                                     ConstArg && !F->isMutable()))
   6773         return false;
   6774     } else if (CSM == Sema::CXXDefaultConstructor) {
   6775       return false;
   6776     }
   6777   }
   6778 
   6779   // All OK, it's constexpr!
   6780   return true;
   6781 }
   6782 
   6783 static Sema::ImplicitExceptionSpecification
   6784 ComputeDefaultedSpecialMemberExceptionSpec(
   6785     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
   6786     Sema::InheritedConstructorInfo *ICI);
   6787 
   6788 static Sema::ImplicitExceptionSpecification
   6789 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
   6790   auto CSM = S.getSpecialMember(MD);
   6791   if (CSM != Sema::CXXInvalid)
   6792     return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
   6793 
   6794   auto *CD = cast<CXXConstructorDecl>(MD);
   6795   assert(CD->getInheritedConstructor() &&
   6796          "only special members have implicit exception specs");
   6797   Sema::InheritedConstructorInfo ICI(
   6798       S, Loc, CD->getInheritedConstructor().getShadowDecl());
   6799   return ComputeDefaultedSpecialMemberExceptionSpec(
   6800       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
   6801 }
   6802 
   6803 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
   6804                                                             CXXMethodDecl *MD) {
   6805   FunctionProtoType::ExtProtoInfo EPI;
   6806 
   6807   // Build an exception specification pointing back at this member.
   6808   EPI.ExceptionSpec.Type = EST_Unevaluated;
   6809   EPI.ExceptionSpec.SourceDecl = MD;
   6810 
   6811   // Set the calling convention to the default for C++ instance methods.
   6812   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
   6813       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
   6814                                             /*IsCXXMethod=*/true));
   6815   return EPI;
   6816 }
   6817 
   6818 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
   6819   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
   6820   if (FPT->getExceptionSpecType() != EST_Unevaluated)
   6821     return;
   6822 
   6823   // Evaluate the exception specification.
   6824   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
   6825   auto ESI = IES.getExceptionSpec();
   6826 
   6827   // Update the type of the special member to use it.
   6828   UpdateExceptionSpec(MD, ESI);
   6829 
   6830   // A user-provided destructor can be defined outside the class. When that
   6831   // happens, be sure to update the exception specification on both
   6832   // declarations.
   6833   const FunctionProtoType *CanonicalFPT =
   6834     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
   6835   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
   6836     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
   6837 }
   6838 
   6839 void Sema::CheckExplicitlyDefaultedFunction(FunctionDecl *FD) {
   6840   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
   6841 
   6842   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
   6843   assert(DefKind && "not a defaultable function");
   6844 
   6845   if (DefKind.isSpecialMember()
   6846           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
   6847                                                   DefKind.asSpecialMember())
   6848           : CheckExplicitlyDefaultedComparison(FD, DefKind.asComparison()))
   6849     FD->setInvalidDecl();
   6850 }
   6851 
   6852 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
   6853                                                  CXXSpecialMember CSM) {
   6854   CXXRecordDecl *RD = MD->getParent();
   6855 
   6856   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
   6857          "not an explicitly-defaulted special member");
   6858 
   6859   // Whether this was the first-declared instance of the constructor.
   6860   // This affects whether we implicitly add an exception spec and constexpr.
   6861   bool First = MD == MD->getCanonicalDecl();
   6862 
   6863   bool HadError = false;
   6864 
   6865   // C++11 [dcl.fct.def.default]p1:
   6866   //   A function that is explicitly defaulted shall
   6867   //     -- be a special member function [...] (checked elsewhere),
   6868   //     -- have the same type (except for ref-qualifiers, and except that a
   6869   //        copy operation can take a non-const reference) as an implicit
   6870   //        declaration, and
   6871   //     -- not have default arguments.
   6872   // C++2a changes the second bullet to instead delete the function if it's
   6873   // defaulted on its first declaration, unless it's "an assignment operator,
   6874   // and its return type differs or its parameter type is not a reference".
   6875   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
   6876   bool ShouldDeleteForTypeMismatch = false;
   6877   unsigned ExpectedParams = 1;
   6878   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
   6879     ExpectedParams = 0;
   6880   if (MD->getNumParams() != ExpectedParams) {
   6881     // This checks for default arguments: a copy or move constructor with a
   6882     // default argument is classified as a default constructor, and assignment
   6883     // operations and destructors can't have default arguments.
   6884     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
   6885       << CSM << MD->getSourceRange();
   6886     HadError = true;
   6887   } else if (MD->isVariadic()) {
   6888     if (DeleteOnTypeMismatch)
   6889       ShouldDeleteForTypeMismatch = true;
   6890     else {
   6891       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
   6892         << CSM << MD->getSourceRange();
   6893       HadError = true;
   6894     }
   6895   }
   6896 
   6897   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
   6898 
   6899   bool CanHaveConstParam = false;
   6900   if (CSM == CXXCopyConstructor)
   6901     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
   6902   else if (CSM == CXXCopyAssignment)
   6903     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
   6904 
   6905   QualType ReturnType = Context.VoidTy;
   6906   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
   6907     // Check for return type matching.
   6908     ReturnType = Type->getReturnType();
   6909 
   6910     QualType DeclType = Context.getTypeDeclType(RD);
   6911     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
   6912     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
   6913 
   6914     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
   6915       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
   6916         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
   6917       HadError = true;
   6918     }
   6919 
   6920     // A defaulted special member cannot have cv-qualifiers.
   6921     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
   6922       if (DeleteOnTypeMismatch)
   6923         ShouldDeleteForTypeMismatch = true;
   6924       else {
   6925         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
   6926           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
   6927         HadError = true;
   6928       }
   6929     }
   6930   }
   6931 
   6932   // Check for parameter type matching.
   6933   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
   6934   bool HasConstParam = false;
   6935   if (ExpectedParams && ArgType->isReferenceType()) {
   6936     // Argument must be reference to possibly-const T.
   6937     QualType ReferentType = ArgType->getPointeeType();
   6938     HasConstParam = ReferentType.isConstQualified();
   6939 
   6940     if (ReferentType.isVolatileQualified()) {
   6941       if (DeleteOnTypeMismatch)
   6942         ShouldDeleteForTypeMismatch = true;
   6943       else {
   6944         Diag(MD->getLocation(),
   6945              diag::err_defaulted_special_member_volatile_param) << CSM;
   6946         HadError = true;
   6947       }
   6948     }
   6949 
   6950     if (HasConstParam && !CanHaveConstParam) {
   6951       if (DeleteOnTypeMismatch)
   6952         ShouldDeleteForTypeMismatch = true;
   6953       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
   6954         Diag(MD->getLocation(),
   6955              diag::err_defaulted_special_member_copy_const_param)
   6956           << (CSM == CXXCopyAssignment);
   6957         // FIXME: Explain why this special member can't be const.
   6958         HadError = true;
   6959       } else {
   6960         Diag(MD->getLocation(),
   6961              diag::err_defaulted_special_member_move_const_param)
   6962           << (CSM == CXXMoveAssignment);
   6963         HadError = true;
   6964       }
   6965     }
   6966   } else if (ExpectedParams) {
   6967     // A copy assignment operator can take its argument by value, but a
   6968     // defaulted one cannot.
   6969     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
   6970     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
   6971     HadError = true;
   6972   }
   6973 
   6974   // C++11 [dcl.fct.def.default]p2:
   6975   //   An explicitly-defaulted function may be declared constexpr only if it
   6976   //   would have been implicitly declared as constexpr,
   6977   // Do not apply this rule to members of class templates, since core issue 1358
   6978   // makes such functions always instantiate to constexpr functions. For
   6979   // functions which cannot be constexpr (for non-constructors in C++11 and for
   6980   // destructors in C++14 and C++17), this is checked elsewhere.
   6981   //
   6982   // FIXME: This should not apply if the member is deleted.
   6983   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
   6984                                                      HasConstParam);
   6985   if ((getLangOpts().CPlusPlus2a ||
   6986        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
   6987                                   : isa<CXXConstructorDecl>(MD))) &&
   6988       MD->isConstexpr() && !Constexpr &&
   6989       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
   6990     Diag(MD->getBeginLoc(), MD->isConsteval()
   6991                                 ? diag::err_incorrect_defaulted_consteval
   6992                                 : diag::err_incorrect_defaulted_constexpr)
   6993         << CSM;
   6994     // FIXME: Explain why the special member can't be constexpr.
   6995     HadError = true;
   6996   }
   6997 
   6998   if (First) {
   6999     // C++2a [dcl.fct.def.default]p3:
   7000     //   If a function is explicitly defaulted on its first declaration, it is
   7001     //   implicitly considered to be constexpr if the implicit declaration
   7002     //   would be.
   7003     MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
   7004 
   7005     if (!Type->hasExceptionSpec()) {
   7006       // C++2a [except.spec]p3:
   7007       //   If a declaration of a function does not have a noexcept-specifier
   7008       //   [and] is defaulted on its first declaration, [...] the exception
   7009       //   specification is as specified below
   7010       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
   7011       EPI.ExceptionSpec.Type = EST_Unevaluated;
   7012       EPI.ExceptionSpec.SourceDecl = MD;
   7013       MD->setType(Context.getFunctionType(ReturnType,
   7014                                           llvm::makeArrayRef(&ArgType,
   7015                                                              ExpectedParams),
   7016                                           EPI));
   7017     }
   7018   }
   7019 
   7020   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
   7021     if (First) {
   7022       SetDeclDeleted(MD, MD->getLocation());
   7023       if (!inTemplateInstantiation() && !HadError) {
   7024         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
   7025         if (ShouldDeleteForTypeMismatch) {
   7026           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
   7027         } else {
   7028           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
   7029         }
   7030       }
   7031       if (ShouldDeleteForTypeMismatch && !HadError) {
   7032         Diag(MD->getLocation(),
   7033              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
   7034       }
   7035     } else {
   7036       // C++11 [dcl.fct.def.default]p4:
   7037       //   [For a] user-provided explicitly-defaulted function [...] if such a
   7038       //   function is implicitly defined as deleted, the program is ill-formed.
   7039       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
   7040       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
   7041       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
   7042       HadError = true;
   7043     }
   7044   }
   7045 
   7046   return HadError;
   7047 }
   7048 
   7049 bool Sema::CheckExplicitlyDefaultedComparison(FunctionDecl *FD,
   7050                                               DefaultedComparisonKind DCK) {
   7051   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
   7052 
   7053   // C++2a [class.compare.default]p1:
   7054   //   A defaulted comparison operator function for some class C shall be a
   7055   //   non-template function declared in the member-specification of C that is
   7056   //    -- a non-static const member of C having one parameter of type
   7057   //       const C&, or
   7058   //    -- a friend of C having two parameters of type const C&.
   7059   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
   7060   assert(RD && "defaulted comparison is not defaulted in a class");
   7061 
   7062   QualType ExpectedParmType =
   7063       Context.getLValueReferenceType(Context.getRecordType(RD).withConst());
   7064   for (const ParmVarDecl *Param : FD->parameters()) {
   7065     if (!Context.hasSameType(Param->getType(), ExpectedParmType)) {
   7066       Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
   7067           << (int)DCK << Param->getType() << ExpectedParmType
   7068           << Param->getSourceRange();
   7069       return true;
   7070     }
   7071   }
   7072 
   7073   // ... non-static const member ...
   7074   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
   7075     assert(!MD->isStatic() && "comparison function cannot be a static member");
   7076     if (!MD->isConst()) {
   7077       SourceLocation InsertLoc;
   7078       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
   7079         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
   7080       Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
   7081         << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
   7082 
   7083       // Add the 'const' to the type to recover.
   7084       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
   7085       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
   7086       EPI.TypeQuals.addConst();
   7087       MD->setType(Context.getFunctionType(FPT->getReturnType(),
   7088                                           FPT->getParamTypes(), EPI));
   7089     }
   7090   } else {
   7091     // A non-member function declared in a class must be a friend.
   7092     assert(FD->getFriendObjectKind() && "expected a friend declaration");
   7093   }
   7094 
   7095   // C++2a [class.compare.default]p2:
   7096   //   A defaulted comparison operator function for class C is defined as
   7097   //   deleted if any non-static data member of C is of reference type or C is
   7098   //   a union-like class.
   7099   llvm::SmallVector<CXXRecordDecl*, 4> Classes(1, RD);
   7100   FieldDecl *ReferenceMember = nullptr;
   7101   bool UnionLike = RD->isUnion();
   7102   while (!Classes.empty()) {
   7103     if (Classes.back()->isUnion())
   7104       UnionLike = true;
   7105     for (FieldDecl *FD : Classes.pop_back_val()->fields()) {
   7106       if (FD->getType()->isReferenceType())
   7107         ReferenceMember = FD;
   7108       if (FD->isAnonymousStructOrUnion())
   7109         Classes.push_back(FD->getType()->getAsCXXRecordDecl());
   7110     }
   7111   }
   7112   // For non-memberwise comparisons, this rule is unjustified, so we permit
   7113   // those cases as an extension.
   7114   bool Memberwise = DCK == DefaultedComparisonKind::Equal ||
   7115                     DCK == DefaultedComparisonKind::ThreeWay;
   7116   if (ReferenceMember) {
   7117     Diag(FD->getLocation(),
   7118          Memberwise ? diag::err_defaulted_comparison_reference_member
   7119                     : diag::ext_defaulted_comparison_reference_member)
   7120         << FD << RD;
   7121     Diag(ReferenceMember->getLocation(), diag::note_reference_member)
   7122         << ReferenceMember;
   7123   } else if (UnionLike) {
   7124     // If the class actually has no variant members, this rule similarly
   7125     // is unjustified, so we permit those cases too.
   7126     Diag(FD->getLocation(),
   7127          !Memberwise ? diag::ext_defaulted_comparison_union
   7128                      : !RD->hasVariantMembers()
   7129                            ? diag::ext_defaulted_comparison_empty_union
   7130                            : diag::err_defaulted_comparison_union)
   7131         << FD << RD->isUnion() << RD;
   7132   }
   7133 
   7134   // C++2a [class.eq]p1, [class.rel]p1:
   7135   //   A [defaulted comparison other than <=>] shall have a declared return
   7136   //   type bool.
   7137   if (DCK != DefaultedComparisonKind::ThreeWay &&
   7138       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
   7139     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
   7140         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
   7141         << FD->getReturnTypeSourceRange();
   7142     return true;
   7143   }
   7144 
   7145   // FIXME: Determine whether the function should be defined as deleted.
   7146 
   7147   // C++2a [dcl.fct.def.default]p3:
   7148   //   An explicitly-defaulted function [..] may be declared constexpr or
   7149   //   consteval only if it would have been implicitly declared constexpr.
   7150   // FIXME: There are no rules governing when these should be constexpr,
   7151   // except for the special case of the injected operator==, for which
   7152   // C++2a [class.compare.default]p3 says:
   7153   //   The operator is a constexpr function if its definition would satisfy
   7154   //   the requirements for a constexpr function.
   7155   // FIXME: Apply this rule to all defaulted comparisons. The only way this
   7156   // can fail is if the return type of a defaulted operator<=> is not a literal
   7157   // type. We should additionally consider whether any of the operations
   7158   // performed by the comparison invokes a non-constexpr function.
   7159   return false;
   7160 }
   7161 
   7162 void Sema::CheckDelayedMemberExceptionSpecs() {
   7163   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
   7164   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
   7165 
   7166   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
   7167   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
   7168 
   7169   // Perform any deferred checking of exception specifications for virtual
   7170   // destructors.
   7171   for (auto &Check : Overriding)
   7172     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
   7173 
   7174   // Perform any deferred checking of exception specifications for befriended
   7175   // special members.
   7176   for (auto &Check : Equivalent)
   7177     CheckEquivalentExceptionSpec(Check.second, Check.first);
   7178 }
   7179 
   7180 namespace {
   7181 /// CRTP base class for visiting operations performed by a special member
   7182 /// function (or inherited constructor).
   7183 template<typename Derived>
   7184 struct SpecialMemberVisitor {
   7185   Sema &S;
   7186   CXXMethodDecl *MD;
   7187   Sema::CXXSpecialMember CSM;
   7188   Sema::InheritedConstructorInfo *ICI;
   7189 
   7190   // Properties of the special member, computed for convenience.
   7191   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
   7192 
   7193   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
   7194                        Sema::InheritedConstructorInfo *ICI)
   7195       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
   7196     switch (CSM) {
   7197     case Sema::CXXDefaultConstructor:
   7198     case Sema::CXXCopyConstructor:
   7199     case Sema::CXXMoveConstructor:
   7200       IsConstructor = true;
   7201       break;
   7202     case Sema::CXXCopyAssignment:
   7203     case Sema::CXXMoveAssignment:
   7204       IsAssignment = true;
   7205       break;
   7206     case Sema::CXXDestructor:
   7207       break;
   7208     case Sema::CXXInvalid:
   7209       llvm_unreachable("invalid special member kind");
   7210     }
   7211 
   7212     if (MD->getNumParams()) {
   7213       if (const ReferenceType *RT =
   7214               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
   7215         ConstArg = RT->getPointeeType().isConstQualified();
   7216     }
   7217   }
   7218 
   7219   Derived &getDerived() { return static_cast<Derived&>(*this); }
   7220 
   7221   /// Is this a "move" special member?
   7222   bool isMove() const {
   7223     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
   7224   }
   7225 
   7226   /// Look up the corresponding special member in the given class.
   7227   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
   7228                                              unsigned Quals, bool IsMutable) {
   7229     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
   7230                                        ConstArg && !IsMutable);
   7231   }
   7232 
   7233   /// Look up the constructor for the specified base class to see if it's
   7234   /// overridden due to this being an inherited constructor.
   7235   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
   7236     if (!ICI)
   7237       return {};
   7238     assert(CSM == Sema::CXXDefaultConstructor);
   7239     auto *BaseCtor =
   7240       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
   7241     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
   7242       return MD;
   7243     return {};
   7244   }
   7245 
   7246   /// A base or member subobject.
   7247   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
   7248 
   7249   /// Get the location to use for a subobject in diagnostics.
   7250   static SourceLocation getSubobjectLoc(Subobject Subobj) {
   7251     // FIXME: For an indirect virtual base, the direct base leading to
   7252     // the indirect virtual base would be a more useful choice.
   7253     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
   7254       return B->getBaseTypeLoc();
   7255     else
   7256       return Subobj.get<FieldDecl*>()->getLocation();
   7257   }
   7258 
   7259   enum BasesToVisit {
   7260     /// Visit all non-virtual (direct) bases.
   7261     VisitNonVirtualBases,
   7262     /// Visit all direct bases, virtual or not.
   7263     VisitDirectBases,
   7264     /// Visit all non-virtual bases, and all virtual bases if the class
   7265     /// is not abstract.
   7266     VisitPotentiallyConstructedBases,
   7267     /// Visit all direct or virtual bases.
   7268     VisitAllBases
   7269   };
   7270 
   7271   // Visit the bases and members of the class.
   7272   bool visit(BasesToVisit Bases) {
   7273     CXXRecordDecl *RD = MD->getParent();
   7274 
   7275     if (Bases == VisitPotentiallyConstructedBases)
   7276       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
   7277 
   7278     for (auto &B : RD->bases())
   7279       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
   7280           getDerived().visitBase(&B))
   7281         return true;
   7282 
   7283     if (Bases == VisitAllBases)
   7284       for (auto &B : RD->vbases())
   7285         if (getDerived().visitBase(&B))
   7286           return true;
   7287 
   7288     for (auto *F : RD->fields())
   7289       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
   7290           getDerived().visitField(F))
   7291         return true;
   7292 
   7293     return false;
   7294   }
   7295 };
   7296 }
   7297 
   7298 namespace {
   7299 struct SpecialMemberDeletionInfo
   7300     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
   7301   bool Diagnose;
   7302 
   7303   SourceLocation Loc;
   7304 
   7305   bool AllFieldsAreConst;
   7306 
   7307   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
   7308                             Sema::CXXSpecialMember CSM,
   7309                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
   7310       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
   7311         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
   7312 
   7313   bool inUnion() const { return MD->getParent()->isUnion(); }
   7314 
   7315   Sema::CXXSpecialMember getEffectiveCSM() {
   7316     return ICI ? Sema::CXXInvalid : CSM;
   7317   }
   7318 
   7319   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
   7320 
   7321   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
   7322   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
   7323 
   7324   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
   7325   bool shouldDeleteForField(FieldDecl *FD);
   7326   bool shouldDeleteForAllConstMembers();
   7327 
   7328   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
   7329                                      unsigned Quals);
   7330   bool shouldDeleteForSubobjectCall(Subobject Subobj,
   7331                                     Sema::SpecialMemberOverloadResult SMOR,
   7332                                     bool IsDtorCallInCtor);
   7333 
   7334   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
   7335 };
   7336 }
   7337 
   7338 /// Is the given special member inaccessible when used on the given
   7339 /// sub-object.
   7340 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
   7341                                              CXXMethodDecl *target) {
   7342   /// If we're operating on a base class, the object type is the
   7343   /// type of this special member.
   7344   QualType objectTy;
   7345   AccessSpecifier access = target->getAccess();
   7346   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
   7347     objectTy = S.Context.getTypeDeclType(MD->getParent());
   7348     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
   7349 
   7350   // If we're operating on a field, the object type is the type of the field.
   7351   } else {
   7352     objectTy = S.Context.getTypeDeclType(target->getParent());
   7353   }
   7354 
   7355   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
   7356 }
   7357 
   7358 /// Check whether we should delete a special member due to the implicit
   7359 /// definition containing a call to a special member of a subobject.
   7360 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
   7361     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
   7362     bool IsDtorCallInCtor) {
   7363   CXXMethodDecl *Decl = SMOR.getMethod();
   7364   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
   7365 
   7366   int DiagKind = -1;
   7367 
   7368   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
   7369     DiagKind = !Decl ? 0 : 1;
   7370   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
   7371     DiagKind = 2;
   7372   else if (!isAccessible(Subobj, Decl))
   7373     DiagKind = 3;
   7374   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
   7375            !Decl->isTrivial()) {
   7376     // A member of a union must have a trivial corresponding special member.
   7377     // As a weird special case, a destructor call from a union's constructor
   7378     // must be accessible and non-deleted, but need not be trivial. Such a
   7379     // destructor is never actually called, but is semantically checked as
   7380     // if it were.
   7381     DiagKind = 4;
   7382   }
   7383 
   7384   if (DiagKind == -1)
   7385     return false;
   7386 
   7387   if (Diagnose) {
   7388     if (Field) {
   7389       S.Diag(Field->getLocation(),
   7390              diag::note_deleted_special_member_class_subobject)
   7391         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
   7392         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
   7393     } else {
   7394       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
   7395       S.Diag(Base->getBeginLoc(),
   7396              diag::note_deleted_special_member_class_subobject)
   7397           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
   7398           << Base->getType() << DiagKind << IsDtorCallInCtor
   7399           << /*IsObjCPtr*/false;
   7400     }
   7401 
   7402     if (DiagKind == 1)
   7403       S.NoteDeletedFunction(Decl);
   7404     // FIXME: Explain inaccessibility if DiagKind == 3.
   7405   }
   7406 
   7407   return true;
   7408 }
   7409 
   7410 /// Check whether we should delete a special member function due to having a
   7411 /// direct or virtual base class or non-static data member of class type M.
   7412 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
   7413     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
   7414   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
   7415   bool IsMutable = Field && Field->isMutable();
   7416 
   7417   // C++11 [class.ctor]p5:
   7418   // -- any direct or virtual base class, or non-static data member with no
   7419   //    brace-or-equal-initializer, has class type M (or array thereof) and
   7420   //    either M has no default constructor or overload resolution as applied
   7421   //    to M's default constructor results in an ambiguity or in a function
   7422   //    that is deleted or inaccessible
   7423   // C++11 [class.copy]p11, C++11 [class.copy]p23:
   7424   // -- a direct or virtual base class B that cannot be copied/moved because
   7425   //    overload resolution, as applied to B's corresponding special member,
   7426   //    results in an ambiguity or a function that is deleted or inaccessible
   7427   //    from the defaulted special member
   7428   // C++11 [class.dtor]p5:
   7429   // -- any direct or virtual base class [...] has a type with a destructor
   7430   //    that is deleted or inaccessible
   7431   if (!(CSM == Sema::CXXDefaultConstructor &&
   7432         Field && Field->hasInClassInitializer()) &&
   7433       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
   7434                                    false))
   7435     return true;
   7436 
   7437   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
   7438   // -- any direct or virtual base class or non-static data member has a
   7439   //    type with a destructor that is deleted or inaccessible
   7440   if (IsConstructor) {
   7441     Sema::SpecialMemberOverloadResult SMOR =
   7442         S.LookupSpecialMember(Class, Sema::CXXDestructor,
   7443                               false, false, false, false, false);
   7444     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
   7445       return true;
   7446   }
   7447 
   7448   return false;
   7449 }
   7450 
   7451 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
   7452     FieldDecl *FD, QualType FieldType) {
   7453   // The defaulted special functions are defined as deleted if this is a variant
   7454   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
   7455   // type under ARC.
   7456   if (!FieldType.hasNonTrivialObjCLifetime())
   7457     return false;
   7458 
   7459   // Don't make the defaulted default constructor defined as deleted if the
   7460   // member has an in-class initializer.
   7461   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
   7462     return false;
   7463 
   7464   if (Diagnose) {
   7465     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
   7466     S.Diag(FD->getLocation(),
   7467            diag::note_deleted_special_member_class_subobject)
   7468         << getEffectiveCSM() << ParentClass << /*IsField*/true
   7469         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
   7470   }
   7471 
   7472   return true;
   7473 }
   7474 
   7475 /// Check whether we should delete a special member function due to the class
   7476 /// having a particular direct or virtual base class.
   7477 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
   7478   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
   7479   // If program is correct, BaseClass cannot be null, but if it is, the error
   7480   // must be reported elsewhere.
   7481   if (!BaseClass)
   7482     return false;
   7483   // If we have an inheriting constructor, check whether we're calling an
   7484   // inherited constructor instead of a default constructor.
   7485   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
   7486   if (auto *BaseCtor = SMOR.getMethod()) {
   7487     // Note that we do not check access along this path; other than that,
   7488     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
   7489     // FIXME: Check that the base has a usable destructor! Sink this into
   7490     // shouldDeleteForClassSubobject.
   7491     if (BaseCtor->isDeleted() && Diagnose) {
   7492       S.Diag(Base->getBeginLoc(),
   7493              diag::note_deleted_special_member_class_subobject)
   7494           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
   7495           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
   7496           << /*IsObjCPtr*/false;
   7497       S.NoteDeletedFunction(BaseCtor);
   7498     }
   7499     return BaseCtor->isDeleted();
   7500   }
   7501   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
   7502 }
   7503 
   7504 /// Check whether we should delete a special member function due to the class
   7505 /// having a particular non-static data member.
   7506 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
   7507   QualType FieldType = S.Context.getBaseElementType(FD->getType());
   7508   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
   7509 
   7510   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
   7511     return true;
   7512 
   7513   if (CSM == Sema::CXXDefaultConstructor) {
   7514     // For a default constructor, all references must be initialized in-class
   7515     // and, if a union, it must have a non-const member.
   7516     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
   7517       if (Diagnose)
   7518         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
   7519           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
   7520       return true;
   7521     }
   7522     // C++11 [class.ctor]p5: any non-variant non-static data member of
   7523     // const-qualified type (or array thereof) with no
   7524     // brace-or-equal-initializer does not have a user-provided default
   7525     // constructor.
   7526     if (!inUnion() && FieldType.isConstQualified() &&
   7527         !FD->hasInClassInitializer() &&
   7528         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
   7529       if (Diagnose)
   7530         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
   7531           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
   7532       return true;
   7533     }
   7534 
   7535     if (inUnion() && !FieldType.isConstQualified())
   7536       AllFieldsAreConst = false;
   7537   } else if (CSM == Sema::CXXCopyConstructor) {
   7538     // For a copy constructor, data members must not be of rvalue reference
   7539     // type.
   7540     if (FieldType->isRValueReferenceType()) {
   7541       if (Diagnose)
   7542         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
   7543           << MD->getParent() << FD << FieldType;
   7544       return true;
   7545     }
   7546   } else if (IsAssignment) {
   7547     // For an assignment operator, data members must not be of reference type.
   7548     if (FieldType->isReferenceType()) {
   7549       if (Diagnose)
   7550         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
   7551           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
   7552       return true;
   7553     }
   7554     if (!FieldRecord && FieldType.isConstQualified()) {
   7555       // C++11 [class.copy]p23:
   7556       // -- a non-static data member of const non-class type (or array thereof)
   7557       if (Diagnose)
   7558         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
   7559           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
   7560       return true;
   7561     }
   7562   }
   7563 
   7564   if (FieldRecord) {
   7565     // Some additional restrictions exist on the variant members.
   7566     if (!inUnion() && FieldRecord->isUnion() &&
   7567         FieldRecord->isAnonymousStructOrUnion()) {
   7568       bool AllVariantFieldsAreConst = true;
   7569 
   7570       // FIXME: Handle anonymous unions declared within anonymous unions.
   7571       for (auto *UI : FieldRecord->fields()) {
   7572         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
   7573 
   7574         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
   7575           return true;
   7576 
   7577         if (!UnionFieldType.isConstQualified())
   7578           AllVariantFieldsAreConst = false;
   7579 
   7580         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
   7581         if (UnionFieldRecord &&
   7582             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
   7583                                           UnionFieldType.getCVRQualifiers()))
   7584           return true;
   7585       }
   7586 
   7587       // At least one member in each anonymous union must be non-const
   7588       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
   7589           !FieldRecord->field_empty()) {
   7590         if (Diagnose)
   7591           S.Diag(FieldRecord->getLocation(),
   7592                  diag::note_deleted_default_ctor_all_const)
   7593             << !!ICI << MD->getParent() << /*anonymous union*/1;
   7594         return true;
   7595       }
   7596 
   7597       // Don't check the implicit member of the anonymous union type.
   7598       // This is technically non-conformant, but sanity demands it.
   7599       return false;
   7600     }
   7601 
   7602     if (shouldDeleteForClassSubobject(FieldRecord, FD,
   7603                                       FieldType.getCVRQualifiers()))
   7604       return true;
   7605   }
   7606 
   7607   return false;
   7608 }
   7609 
   7610 /// C++11 [class.ctor] p5:
   7611 ///   A defaulted default constructor for a class X is defined as deleted if
   7612 /// X is a union and all of its variant members are of const-qualified type.
   7613 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
   7614   // This is a silly definition, because it gives an empty union a deleted
   7615   // default constructor. Don't do that.
   7616   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
   7617     bool AnyFields = false;
   7618     for (auto *F : MD->getParent()->fields())
   7619       if ((AnyFields = !F->isUnnamedBitfield()))
   7620         break;
   7621     if (!AnyFields)
   7622       return false;
   7623     if (Diagnose)
   7624       S.Diag(MD->getParent()->getLocation(),
   7625              diag::note_deleted_default_ctor_all_const)
   7626         << !!ICI << MD->getParent() << /*not anonymous union*/0;
   7627     return true;
   7628   }
   7629   return false;
   7630 }
   7631 
   7632 /// Determine whether a defaulted special member function should be defined as
   7633 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
   7634 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
   7635 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
   7636                                      InheritedConstructorInfo *ICI,
   7637                                      bool Diagnose) {
   7638   if (MD->isInvalidDecl())
   7639     return false;
   7640   CXXRecordDecl *RD = MD->getParent();
   7641   assert(!RD->isDependentType() && "do deletion after instantiation");
   7642   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
   7643     return false;
   7644 
   7645   // C++11 [expr.lambda.prim]p19:
   7646   //   The closure type associated with a lambda-expression has a
   7647   //   deleted (8.4.3) default constructor and a deleted copy
   7648   //   assignment operator.
   7649   // C++2a adds back these operators if the lambda has no lambda-capture.
   7650   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
   7651       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
   7652     if (Diagnose)
   7653       Diag(RD->getLocation(), diag::note_lambda_decl);
   7654     return true;
   7655   }
   7656 
   7657   // For an anonymous struct or union, the copy and assignment special members
   7658   // will never be used, so skip the check. For an anonymous union declared at
   7659   // namespace scope, the constructor and destructor are used.
   7660   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
   7661       RD->isAnonymousStructOrUnion())
   7662     return false;
   7663 
   7664   // C++11 [class.copy]p7, p18:
   7665   //   If the class definition declares a move constructor or move assignment
   7666   //   operator, an implicitly declared copy constructor or copy assignment
   7667   //   operator is defined as deleted.
   7668   if (MD->isImplicit() &&
   7669       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
   7670     CXXMethodDecl *UserDeclaredMove = nullptr;
   7671 
   7672     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
   7673     // deletion of the corresponding copy operation, not both copy operations.
   7674     // MSVC 2015 has adopted the standards conforming behavior.
   7675     bool DeletesOnlyMatchingCopy =
   7676         getLangOpts().MSVCCompat &&
   7677         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
   7678 
   7679     if (RD->hasUserDeclaredMoveConstructor() &&
   7680         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
   7681       if (!Diagnose) return true;
   7682 
   7683       // Find any user-declared move constructor.
   7684       for (auto *I : RD->ctors()) {
   7685         if (I->isMoveConstructor()) {
   7686           UserDeclaredMove = I;
   7687           break;
   7688         }
   7689       }
   7690       assert(UserDeclaredMove);
   7691     } else if (RD->hasUserDeclaredMoveAssignment() &&
   7692                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
   7693       if (!Diagnose) return true;
   7694 
   7695       // Find any user-declared move assignment operator.
   7696       for (auto *I : RD->methods()) {
   7697         if (I->isMoveAssignmentOperator()) {
   7698           UserDeclaredMove = I;
   7699           break;
   7700         }
   7701       }
   7702       assert(UserDeclaredMove);
   7703     }
   7704 
   7705     if (UserDeclaredMove) {
   7706       Diag(UserDeclaredMove->getLocation(),
   7707            diag::note_deleted_copy_user_declared_move)
   7708         << (CSM == CXXCopyAssignment) << RD
   7709         << UserDeclaredMove->isMoveAssignmentOperator();
   7710       return true;
   7711     }
   7712   }
   7713 
   7714   // Do access control from the special member function
   7715   ContextRAII MethodContext(*this, MD);
   7716 
   7717   // C++11 [class.dtor]p5:
   7718   // -- for a virtual destructor, lookup of the non-array deallocation function
   7719   //    results in an ambiguity or in a function that is deleted or inaccessible
   7720   if (CSM == CXXDestructor && MD->isVirtual()) {
   7721     FunctionDecl *OperatorDelete = nullptr;
   7722     DeclarationName Name =
   7723       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
   7724     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
   7725                                  OperatorDelete, /*Diagnose*/false)) {
   7726       if (Diagnose)
   7727         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
   7728       return true;
   7729     }
   7730   }
   7731 
   7732   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
   7733 
   7734   // Per DR1611, do not consider virtual bases of constructors of abstract
   7735   // classes, since we are not going to construct them.
   7736   // Per DR1658, do not consider virtual bases of destructors of abstract
   7737   // classes either.
   7738   // Per DR2180, for assignment operators we only assign (and thus only
   7739   // consider) direct bases.
   7740   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
   7741                                  : SMI.VisitPotentiallyConstructedBases))
   7742     return true;
   7743 
   7744   if (SMI.shouldDeleteForAllConstMembers())
   7745     return true;
   7746 
   7747   if (getLangOpts().CUDA) {
   7748     // We should delete the special member in CUDA mode if target inference
   7749     // failed.
   7750     // For inherited constructors (non-null ICI), CSM may be passed so that MD
   7751     // is treated as certain special member, which may not reflect what special
   7752     // member MD really is. However inferCUDATargetForImplicitSpecialMember
   7753     // expects CSM to match MD, therefore recalculate CSM.
   7754     assert(ICI || CSM == getSpecialMember(MD));
   7755     auto RealCSM = CSM;
   7756     if (ICI)
   7757       RealCSM = getSpecialMember(MD);
   7758 
   7759     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
   7760                                                    SMI.ConstArg, Diagnose);
   7761   }
   7762 
   7763   return false;
   7764 }
   7765 
   7766 /// Perform lookup for a special member of the specified kind, and determine
   7767 /// whether it is trivial. If the triviality can be determined without the
   7768 /// lookup, skip it. This is intended for use when determining whether a
   7769 /// special member of a containing object is trivial, and thus does not ever
   7770 /// perform overload resolution for default constructors.
   7771 ///
   7772 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
   7773 /// member that was most likely to be intended to be trivial, if any.
   7774 ///
   7775 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
   7776 /// determine whether the special member is trivial.
   7777 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
   7778                                      Sema::CXXSpecialMember CSM, unsigned Quals,
   7779                                      bool ConstRHS,
   7780                                      Sema::TrivialABIHandling TAH,
   7781                                      CXXMethodDecl **Selected) {
   7782   if (Selected)
   7783     *Selected = nullptr;
   7784 
   7785   switch (CSM) {
   7786   case Sema::CXXInvalid:
   7787     llvm_unreachable("not a special member");
   7788 
   7789   case Sema::CXXDefaultConstructor:
   7790     // C++11 [class.ctor]p5:
   7791     //   A default constructor is trivial if:
   7792     //    - all the [direct subobjects] have trivial default constructors
   7793     //
   7794     // Note, no overload resolution is performed in this case.
   7795     if (RD->hasTrivialDefaultConstructor())
   7796       return true;
   7797 
   7798     if (Selected) {
   7799       // If there's a default constructor which could have been trivial, dig it
   7800       // out. Otherwise, if there's any user-provided default constructor, point
   7801       // to that as an example of why there's not a trivial one.
   7802       CXXConstructorDecl *DefCtor = nullptr;
   7803       if (RD->needsImplicitDefaultConstructor())
   7804         S.DeclareImplicitDefaultConstructor(RD);
   7805       for (auto *CI : RD->ctors()) {
   7806         if (!CI->isDefaultConstructor())
   7807           continue;
   7808         DefCtor = CI;
   7809         if (!DefCtor->isUserProvided())
   7810           break;
   7811       }
   7812 
   7813       *Selected = DefCtor;
   7814     }
   7815 
   7816     return false;
   7817 
   7818   case Sema::CXXDestructor:
   7819     // C++11 [class.dtor]p5:
   7820     //   A destructor is trivial if:
   7821     //    - all the direct [subobjects] have trivial destructors
   7822     if (RD->hasTrivialDestructor() ||
   7823         (TAH == Sema::TAH_ConsiderTrivialABI &&
   7824          RD->hasTrivialDestructorForCall()))
   7825       return true;
   7826 
   7827     if (Selected) {
   7828       if (RD->needsImplicitDestructor())
   7829         S.DeclareImplicitDestructor(RD);
   7830       *Selected = RD->getDestructor();
   7831     }
   7832 
   7833     return false;
   7834 
   7835   case Sema::CXXCopyConstructor:
   7836     // C++11 [class.copy]p12:
   7837     //   A copy constructor is trivial if:
   7838     //    - the constructor selected to copy each direct [subobject] is trivial
   7839     if (RD->hasTrivialCopyConstructor() ||
   7840         (TAH == Sema::TAH_ConsiderTrivialABI &&
   7841          RD->hasTrivialCopyConstructorForCall())) {
   7842       if (Quals == Qualifiers::Const)
   7843         // We must either select the trivial copy constructor or reach an
   7844         // ambiguity; no need to actually perform overload resolution.
   7845         return true;
   7846     } else if (!Selected) {
   7847       return false;
   7848     }
   7849     // In C++98, we are not supposed to perform overload resolution here, but we
   7850     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
   7851     // cases like B as having a non-trivial copy constructor:
   7852     //   struct A { template<typename T> A(T&); };
   7853     //   struct B { mutable A a; };
   7854     goto NeedOverloadResolution;
   7855 
   7856   case Sema::CXXCopyAssignment:
   7857     // C++11 [class.copy]p25:
   7858     //   A copy assignment operator is trivial if:
   7859     //    - the assignment operator selected to copy each direct [subobject] is
   7860     //      trivial
   7861     if (RD->hasTrivialCopyAssignment()) {
   7862       if (Quals == Qualifiers::Const)
   7863         return true;
   7864     } else if (!Selected) {
   7865       return false;
   7866     }
   7867     // In C++98, we are not supposed to perform overload resolution here, but we
   7868     // treat that as a language defect.
   7869     goto NeedOverloadResolution;
   7870 
   7871   case Sema::CXXMoveConstructor:
   7872   case Sema::CXXMoveAssignment:
   7873   NeedOverloadResolution:
   7874     Sema::SpecialMemberOverloadResult SMOR =
   7875         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
   7876 
   7877     // The standard doesn't describe how to behave if the lookup is ambiguous.
   7878     // We treat it as not making the member non-trivial, just like the standard
   7879     // mandates for the default constructor. This should rarely matter, because
   7880     // the member will also be deleted.
   7881     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
   7882       return true;
   7883 
   7884     if (!SMOR.getMethod()) {
   7885       assert(SMOR.getKind() ==
   7886              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
   7887       return false;
   7888     }
   7889 
   7890     // We deliberately don't check if we found a deleted special member. We're
   7891     // not supposed to!
   7892     if (Selected)
   7893       *Selected = SMOR.getMethod();
   7894 
   7895     if (TAH == Sema::TAH_ConsiderTrivialABI &&
   7896         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
   7897       return SMOR.getMethod()->isTrivialForCall();
   7898     return SMOR.getMethod()->isTrivial();
   7899   }
   7900 
   7901   llvm_unreachable("unknown special method kind");
   7902 }
   7903 
   7904 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
   7905   for (auto *CI : RD->ctors())
   7906     if (!CI->isImplicit())
   7907       return CI;
   7908 
   7909   // Look for constructor templates.
   7910   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
   7911   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
   7912     if (CXXConstructorDecl *CD =
   7913           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
   7914       return CD;
   7915   }
   7916 
   7917   return nullptr;
   7918 }
   7919 
   7920 /// The kind of subobject we are checking for triviality. The values of this
   7921 /// enumeration are used in diagnostics.
   7922 enum TrivialSubobjectKind {
   7923   /// The subobject is a base class.
   7924   TSK_BaseClass,
   7925   /// The subobject is a non-static data member.
   7926   TSK_Field,
   7927   /// The object is actually the complete object.
   7928   TSK_CompleteObject
   7929 };
   7930 
   7931 /// Check whether the special member selected for a given type would be trivial.
   7932 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
   7933                                       QualType SubType, bool ConstRHS,
   7934                                       Sema::CXXSpecialMember CSM,
   7935                                       TrivialSubobjectKind Kind,
   7936                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
   7937   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
   7938   if (!SubRD)
   7939     return true;
   7940 
   7941   CXXMethodDecl *Selected;
   7942   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
   7943                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
   7944     return true;
   7945 
   7946   if (Diagnose) {
   7947     if (ConstRHS)
   7948       SubType.addConst();
   7949 
   7950     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
   7951       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
   7952         << Kind << SubType.getUnqualifiedType();
   7953       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
   7954         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
   7955     } else if (!Selected)
   7956       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
   7957         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
   7958     else if (Selected->isUserProvided()) {
   7959       if (Kind == TSK_CompleteObject)
   7960         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
   7961           << Kind << SubType.getUnqualifiedType() << CSM;
   7962       else {
   7963         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
   7964           << Kind << SubType.getUnqualifiedType() << CSM;
   7965         S.Diag(Selected->getLocation(), diag::note_declared_at);
   7966       }
   7967     } else {
   7968       if (Kind != TSK_CompleteObject)
   7969         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
   7970           << Kind << SubType.getUnqualifiedType() << CSM;
   7971 
   7972       // Explain why the defaulted or deleted special member isn't trivial.
   7973       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
   7974                                Diagnose);
   7975     }
   7976   }
   7977 
   7978   return false;
   7979 }
   7980 
   7981 /// Check whether the members of a class type allow a special member to be
   7982 /// trivial.
   7983 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
   7984                                      Sema::CXXSpecialMember CSM,
   7985                                      bool ConstArg,
   7986                                      Sema::TrivialABIHandling TAH,
   7987                                      bool Diagnose) {
   7988   for (const auto *FI : RD->fields()) {
   7989     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
   7990       continue;
   7991 
   7992     QualType FieldType = S.Context.getBaseElementType(FI->getType());
   7993 
   7994     // Pretend anonymous struct or union members are members of this class.
   7995     if (FI->isAnonymousStructOrUnion()) {
   7996       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
   7997                                     CSM, ConstArg, TAH, Diagnose))
   7998         return false;
   7999       continue;
   8000     }
   8001 
   8002     // C++11 [class.ctor]p5:
   8003     //   A default constructor is trivial if [...]
   8004     //    -- no non-static data member of its class has a
   8005     //       brace-or-equal-initializer
   8006     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
   8007       if (Diagnose)
   8008         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
   8009       return false;
   8010     }
   8011 
   8012     // Objective C ARC 4.3.5:
   8013     //   [...] nontrivally ownership-qualified types are [...] not trivially
   8014     //   default constructible, copy constructible, move constructible, copy
   8015     //   assignable, move assignable, or destructible [...]
   8016     if (FieldType.hasNonTrivialObjCLifetime()) {
   8017       if (Diagnose)
   8018         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
   8019           << RD << FieldType.getObjCLifetime();
   8020       return false;
   8021     }
   8022 
   8023     bool ConstRHS = ConstArg && !FI->isMutable();
   8024     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
   8025                                    CSM, TSK_Field, TAH, Diagnose))
   8026       return false;
   8027   }
   8028 
   8029   return true;
   8030 }
   8031 
   8032 /// Diagnose why the specified class does not have a trivial special member of
   8033 /// the given kind.
   8034 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
   8035   QualType Ty = Context.getRecordType(RD);
   8036 
   8037   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
   8038   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
   8039                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
   8040                             /*Diagnose*/true);
   8041 }
   8042 
   8043 /// Determine whether a defaulted or deleted special member function is trivial,
   8044 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
   8045 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
   8046 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
   8047                                   TrivialABIHandling TAH, bool Diagnose) {
   8048   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
   8049 
   8050   CXXRecordDecl *RD = MD->getParent();
   8051 
   8052   bool ConstArg = false;
   8053 
   8054   // C++11 [class.copy]p12, p25: [DR1593]
   8055   //   A [special member] is trivial if [...] its parameter-type-list is
   8056   //   equivalent to the parameter-type-list of an implicit declaration [...]
   8057   switch (CSM) {
   8058   case CXXDefaultConstructor:
   8059   case CXXDestructor:
   8060     // Trivial default constructors and destructors cannot have parameters.
   8061     break;
   8062 
   8063   case CXXCopyConstructor:
   8064   case CXXCopyAssignment: {
   8065     // Trivial copy operations always have const, non-volatile parameter types.
   8066     ConstArg = true;
   8067     const ParmVarDecl *Param0 = MD->getParamDecl(0);
   8068     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
   8069     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
   8070       if (Diagnose)
   8071         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
   8072           << Param0->getSourceRange() << Param0->getType()
   8073           << Context.getLValueReferenceType(
   8074                Context.getRecordType(RD).withConst());
   8075       return false;
   8076     }
   8077     break;
   8078   }
   8079 
   8080   case CXXMoveConstructor:
   8081   case CXXMoveAssignment: {
   8082     // Trivial move operations always have non-cv-qualified parameters.
   8083     const ParmVarDecl *Param0 = MD->getParamDecl(0);
   8084     const RValueReferenceType *RT =
   8085       Param0->getType()->getAs<RValueReferenceType>();
   8086     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
   8087       if (Diagnose)
   8088         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
   8089           << Param0->getSourceRange() << Param0->getType()
   8090           << Context.getRValueReferenceType(Context.getRecordType(RD));
   8091       return false;
   8092     }
   8093     break;
   8094   }
   8095 
   8096   case CXXInvalid:
   8097     llvm_unreachable("not a special member");
   8098   }
   8099 
   8100   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
   8101     if (Diagnose)
   8102       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
   8103            diag::note_nontrivial_default_arg)
   8104         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
   8105     return false;
   8106   }
   8107   if (MD->isVariadic()) {
   8108     if (Diagnose)
   8109       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
   8110     return false;
   8111   }
   8112 
   8113   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
   8114   //   A copy/move [constructor or assignment operator] is trivial if
   8115   //    -- the [member] selected to copy/move each direct base class subobject
   8116   //       is trivial
   8117   //
   8118   // C++11 [class.copy]p12, C++11 [class.copy]p25:
   8119   //   A [default constructor or destructor] is trivial if
   8120   //    -- all the direct base classes have trivial [default constructors or
   8121   //       destructors]
   8122   for (const auto &BI : RD->bases())
   8123     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
   8124                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
   8125       return false;
   8126 
   8127   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
   8128   //   A copy/move [constructor or assignment operator] for a class X is
   8129   //   trivial if
   8130   //    -- for each non-static data member of X that is of class type (or array
   8131   //       thereof), the constructor selected to copy/move that member is
   8132   //       trivial
   8133   //
   8134   // C++11 [class.copy]p12, C++11 [class.copy]p25:
   8135   //   A [default constructor or destructor] is trivial if
   8136   //    -- for all of the non-static data members of its class that are of class
   8137   //       type (or array thereof), each such class has a trivial [default
   8138   //       constructor or destructor]
   8139   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
   8140     return false;
   8141 
   8142   // C++11 [class.dtor]p5:
   8143   //   A destructor is trivial if [...]
   8144   //    -- the destructor is not virtual
   8145   if (CSM == CXXDestructor && MD->isVirtual()) {
   8146     if (Diagnose)
   8147       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
   8148     return false;
   8149   }
   8150 
   8151   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
   8152   //   A [special member] for class X is trivial if [...]
   8153   //    -- class X has no virtual functions and no virtual base classes
   8154   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
   8155     if (!Diagnose)
   8156       return false;
   8157 
   8158     if (RD->getNumVBases()) {
   8159       // Check for virtual bases. We already know that the corresponding
   8160       // member in all bases is trivial, so vbases must all be direct.
   8161       CXXBaseSpecifier &BS = *RD->vbases_begin();
   8162       assert(BS.isVirtual());
   8163       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
   8164       return false;
   8165     }
   8166 
   8167     // Must have a virtual method.
   8168     for (const auto *MI : RD->methods()) {
   8169       if (MI->isVirtual()) {
   8170         SourceLocation MLoc = MI->getBeginLoc();
   8171         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
   8172         return false;
   8173       }
   8174     }
   8175 
   8176     llvm_unreachable("dynamic class with no vbases and no virtual functions");
   8177   }
   8178 
   8179   // Looks like it's trivial!
   8180   return true;
   8181 }
   8182 
   8183 namespace {
   8184 struct FindHiddenVirtualMethod {
   8185   Sema *S;
   8186   CXXMethodDecl *Method;
   8187   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
   8188   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
   8189 
   8190 private:
   8191   /// Check whether any most overridden method from MD in Methods
   8192   static bool CheckMostOverridenMethods(
   8193       const CXXMethodDecl *MD,
   8194       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
   8195     if (MD->size_overridden_methods() == 0)
   8196       return Methods.count(MD->getCanonicalDecl());
   8197     for (const CXXMethodDecl *O : MD->overridden_methods())
   8198       if (CheckMostOverridenMethods(O, Methods))
   8199         return true;
   8200     return false;
   8201   }
   8202 
   8203 public:
   8204   /// Member lookup function that determines whether a given C++
   8205   /// method overloads virtual methods in a base class without overriding any,
   8206   /// to be used with CXXRecordDecl::lookupInBases().
   8207   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
   8208     RecordDecl *BaseRecord =
   8209         Specifier->getType()->castAs<RecordType>()->getDecl();
   8210 
   8211     DeclarationName Name = Method->getDeclName();
   8212     assert(Name.getNameKind() == DeclarationName::Identifier);
   8213 
   8214     bool foundSameNameMethod = false;
   8215     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
   8216     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
   8217          Path.Decls = Path.Decls.slice(1)) {
   8218       NamedDecl *D = Path.Decls.front();
   8219       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
   8220         MD = MD->getCanonicalDecl();
   8221         foundSameNameMethod = true;
   8222         // Interested only in hidden virtual methods.
   8223         if (!MD->isVirtual())
   8224           continue;
   8225         // If the method we are checking overrides a method from its base
   8226         // don't warn about the other overloaded methods. Clang deviates from
   8227         // GCC by only diagnosing overloads of inherited virtual functions that
   8228         // do not override any other virtual functions in the base. GCC's
   8229         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
   8230         // function from a base class. These cases may be better served by a
   8231         // warning (not specific to virtual functions) on call sites when the
   8232         // call would select a different function from the base class, were it
   8233         // visible.
   8234         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
   8235         if (!S->IsOverload(Method, MD, false))
   8236           return true;
   8237         // Collect the overload only if its hidden.
   8238         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
   8239           overloadedMethods.push_back(MD);
   8240       }
   8241     }
   8242 
   8243     if (foundSameNameMethod)
   8244       OverloadedMethods.append(overloadedMethods.begin(),
   8245                                overloadedMethods.end());
   8246     return foundSameNameMethod;
   8247   }
   8248 };
   8249 } // end anonymous namespace
   8250 
   8251 /// Add the most overriden methods from MD to Methods
   8252 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
   8253                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
   8254   if (MD->size_overridden_methods() == 0)
   8255     Methods.insert(MD->getCanonicalDecl());
   8256   else
   8257     for (const CXXMethodDecl *O : MD->overridden_methods())
   8258       AddMostOverridenMethods(O, Methods);
   8259 }
   8260 
   8261 /// Check if a method overloads virtual methods in a base class without
   8262 /// overriding any.
   8263 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
   8264                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
   8265   if (!MD->getDeclName().isIdentifier())
   8266     return;
   8267 
   8268   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
   8269                      /*bool RecordPaths=*/false,
   8270                      /*bool DetectVirtual=*/false);
   8271   FindHiddenVirtualMethod FHVM;
   8272   FHVM.Method = MD;
   8273   FHVM.S = this;
   8274 
   8275   // Keep the base methods that were overridden or introduced in the subclass
   8276   // by 'using' in a set. A base method not in this set is hidden.
   8277   CXXRecordDecl *DC = MD->getParent();
   8278   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
   8279   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
   8280     NamedDecl *ND = *I;
   8281     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
   8282       ND = shad->getTargetDecl();
   8283     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
   8284       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
   8285   }
   8286 
   8287   if (DC->lookupInBases(FHVM, Paths))
   8288     OverloadedMethods = FHVM.OverloadedMethods;
   8289 }
   8290 
   8291 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
   8292                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
   8293   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
   8294     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
   8295     PartialDiagnostic PD = PDiag(
   8296          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
   8297     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
   8298     Diag(overloadedMD->getLocation(), PD);
   8299   }
   8300 }
   8301 
   8302 /// Diagnose methods which overload virtual methods in a base class
   8303 /// without overriding any.
   8304 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
   8305   if (MD->isInvalidDecl())
   8306     return;
   8307 
   8308   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
   8309     return;
   8310 
   8311   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
   8312   FindHiddenVirtualMethods(MD, OverloadedMethods);
   8313   if (!OverloadedMethods.empty()) {
   8314     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
   8315       << MD << (OverloadedMethods.size() > 1);
   8316 
   8317     NoteHiddenVirtualMethods(MD, OverloadedMethods);
   8318   }
   8319 }
   8320 
   8321 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
   8322   auto PrintDiagAndRemoveAttr = [&]() {
   8323     // No diagnostics if this is a template instantiation.
   8324     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
   8325       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
   8326            diag::ext_cannot_use_trivial_abi) << &RD;
   8327     RD.dropAttr<TrivialABIAttr>();
   8328   };
   8329 
   8330   // Ill-formed if the struct has virtual functions.
   8331   if (RD.isPolymorphic()) {
   8332     PrintDiagAndRemoveAttr();
   8333     return;
   8334   }
   8335 
   8336   for (const auto &B : RD.bases()) {
   8337     // Ill-formed if the base class is non-trivial for the purpose of calls or a
   8338     // virtual base.
   8339     if ((!B.getType()->isDependentType() &&
   8340          !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
   8341         B.isVirtual()) {
   8342       PrintDiagAndRemoveAttr();
   8343       return;
   8344     }
   8345   }
   8346 
   8347   for (const auto *FD : RD.fields()) {
   8348     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
   8349     // non-trivial for the purpose of calls.
   8350     QualType FT = FD->getType();
   8351     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
   8352       PrintDiagAndRemoveAttr();
   8353       return;
   8354     }
   8355 
   8356     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
   8357       if (!RT->isDependentType() &&
   8358           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
   8359         PrintDiagAndRemoveAttr();
   8360         return;
   8361       }
   8362   }
   8363 }
   8364 
   8365 void Sema::ActOnFinishCXXMemberSpecification(
   8366     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
   8367     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
   8368   if (!TagDecl)
   8369     return;
   8370 
   8371   AdjustDeclIfTemplate(TagDecl);
   8372 
   8373   for (const ParsedAttr &AL : AttrList) {
   8374     if (AL.getKind() != ParsedAttr::AT_Visibility)
   8375       continue;
   8376     AL.setInvalid();
   8377     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
   8378   }
   8379 
   8380   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
   8381               // strict aliasing violation!
   8382               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
   8383               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
   8384 
   8385   CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
   8386 }
   8387 
   8388 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
   8389 /// special functions, such as the default constructor, copy
   8390 /// constructor, or destructor, to the given C++ class (C++
   8391 /// [special]p1).  This routine can only be executed just before the
   8392 /// definition of the class is complete.
   8393 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
   8394   if (ClassDecl->needsImplicitDefaultConstructor()) {
   8395     ++getASTContext().NumImplicitDefaultConstructors;
   8396 
   8397     if (ClassDecl->hasInheritedConstructor())
   8398       DeclareImplicitDefaultConstructor(ClassDecl);
   8399   }
   8400 
   8401   if (ClassDecl->needsImplicitCopyConstructor()) {
   8402     ++getASTContext().NumImplicitCopyConstructors;
   8403 
   8404     // If the properties or semantics of the copy constructor couldn't be
   8405     // determined while the class was being declared, force a declaration
   8406     // of it now.
   8407     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
   8408         ClassDecl->hasInheritedConstructor())
   8409       DeclareImplicitCopyConstructor(ClassDecl);
   8410     // For the MS ABI we need to know whether the copy ctor is deleted. A
   8411     // prerequisite for deleting the implicit copy ctor is that the class has a
   8412     // move ctor or move assignment that is either user-declared or whose
   8413     // semantics are inherited from a subobject. FIXME: We should provide a more
   8414     // direct way for CodeGen to ask whether the constructor was deleted.
   8415     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   8416              (ClassDecl->hasUserDeclaredMoveConstructor() ||
   8417               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
   8418               ClassDecl->hasUserDeclaredMoveAssignment() ||
   8419               ClassDecl->needsOverloadResolutionForMoveAssignment()))
   8420       DeclareImplicitCopyConstructor(ClassDecl);
   8421   }
   8422 
   8423   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
   8424     ++getASTContext().NumImplicitMoveConstructors;
   8425 
   8426     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
   8427         ClassDecl->hasInheritedConstructor())
   8428       DeclareImplicitMoveConstructor(ClassDecl);
   8429   }
   8430 
   8431   if (ClassDecl->needsImplicitCopyAssignment()) {
   8432     ++getASTContext().NumImplicitCopyAssignmentOperators;
   8433 
   8434     // If we have a dynamic class, then the copy assignment operator may be
   8435     // virtual, so we have to declare it immediately. This ensures that, e.g.,
   8436     // it shows up in the right place in the vtable and that we diagnose
   8437     // problems with the implicit exception specification.
   8438     if (ClassDecl->isDynamicClass() ||
   8439         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
   8440         ClassDecl->hasInheritedAssignment())
   8441       DeclareImplicitCopyAssignment(ClassDecl);
   8442   }
   8443 
   8444   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
   8445     ++getASTContext().NumImplicitMoveAssignmentOperators;
   8446 
   8447     // Likewise for the move assignment operator.
   8448     if (ClassDecl->isDynamicClass() ||
   8449         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
   8450         ClassDecl->hasInheritedAssignment())
   8451       DeclareImplicitMoveAssignment(ClassDecl);
   8452   }
   8453 
   8454   if (ClassDecl->needsImplicitDestructor()) {
   8455     ++getASTContext().NumImplicitDestructors;
   8456 
   8457     // If we have a dynamic class, then the destructor may be virtual, so we
   8458     // have to declare the destructor immediately. This ensures that, e.g., it
   8459     // shows up in the right place in the vtable and that we diagnose problems
   8460     // with the implicit exception specification.
   8461     if (ClassDecl->isDynamicClass() ||
   8462         ClassDecl->needsOverloadResolutionForDestructor())
   8463       DeclareImplicitDestructor(ClassDecl);
   8464   }
   8465 }
   8466 
   8467 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
   8468   if (!D)
   8469     return 0;
   8470 
   8471   // The order of template parameters is not important here. All names
   8472   // get added to the same scope.
   8473   SmallVector<TemplateParameterList *, 4> ParameterLists;
   8474 
   8475   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
   8476     D = TD->getTemplatedDecl();
   8477 
   8478   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
   8479     ParameterLists.push_back(PSD->getTemplateParameters());
   8480 
   8481   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
   8482     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
   8483       ParameterLists.push_back(DD->getTemplateParameterList(i));
   8484 
   8485     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   8486       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
   8487         ParameterLists.push_back(FTD->getTemplateParameters());
   8488     }
   8489   }
   8490 
   8491   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
   8492     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
   8493       ParameterLists.push_back(TD->getTemplateParameterList(i));
   8494 
   8495     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
   8496       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
   8497         ParameterLists.push_back(CTD->getTemplateParameters());
   8498     }
   8499   }
   8500 
   8501   unsigned Count = 0;
   8502   for (TemplateParameterList *Params : ParameterLists) {
   8503     if (Params->size() > 0)
   8504       // Ignore explicit specializations; they don't contribute to the template
   8505       // depth.
   8506       ++Count;
   8507     for (NamedDecl *Param : *Params) {
   8508       if (Param->getDeclName()) {
   8509         S->AddDecl(Param);
   8510         IdResolver.AddDecl(Param);
   8511       }
   8512     }
   8513   }
   8514 
   8515   return Count;
   8516 }
   8517 
   8518 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
   8519   if (!RecordD) return;
   8520   AdjustDeclIfTemplate(RecordD);
   8521   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
   8522   PushDeclContext(S, Record);
   8523 }
   8524 
   8525 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
   8526   if (!RecordD) return;
   8527   PopDeclContext();
   8528 }
   8529 
   8530 /// This is used to implement the constant expression evaluation part of the
   8531 /// attribute enable_if extension. There is nothing in standard C++ which would
   8532 /// require reentering parameters.
   8533 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
   8534   if (!Param)
   8535     return;
   8536 
   8537   S->AddDecl(Param);
   8538   if (Param->getDeclName())
   8539     IdResolver.AddDecl(Param);
   8540 }
   8541 
   8542 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
   8543 /// parsing a top-level (non-nested) C++ class, and we are now
   8544 /// parsing those parts of the given Method declaration that could
   8545 /// not be parsed earlier (C++ [class.mem]p2), such as default
   8546 /// arguments. This action should enter the scope of the given
   8547 /// Method declaration as if we had just parsed the qualified method
   8548 /// name. However, it should not bring the parameters into scope;
   8549 /// that will be performed by ActOnDelayedCXXMethodParameter.
   8550 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
   8551 }
   8552 
   8553 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
   8554 /// C++ method declaration. We're (re-)introducing the given
   8555 /// function parameter into scope for use in parsing later parts of
   8556 /// the method declaration. For example, we could see an
   8557 /// ActOnParamDefaultArgument event for this parameter.
   8558 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
   8559   if (!ParamD)
   8560     return;
   8561 
   8562   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
   8563 
   8564   // If this parameter has an unparsed default argument, clear it out
   8565   // to make way for the parsed default argument.
   8566   if (Param->hasUnparsedDefaultArg())
   8567     Param->setDefaultArg(nullptr);
   8568 
   8569   S->AddDecl(Param);
   8570   if (Param->getDeclName())
   8571     IdResolver.AddDecl(Param);
   8572 }
   8573 
   8574 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
   8575 /// processing the delayed method declaration for Method. The method
   8576 /// declaration is now considered finished. There may be a separate
   8577 /// ActOnStartOfFunctionDef action later (not necessarily
   8578 /// immediately!) for this method, if it was also defined inside the
   8579 /// class body.
   8580 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
   8581   if (!MethodD)
   8582     return;
   8583 
   8584   AdjustDeclIfTemplate(MethodD);
   8585 
   8586   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
   8587 
   8588   // Now that we have our default arguments, check the constructor
   8589   // again. It could produce additional diagnostics or affect whether
   8590   // the class has implicitly-declared destructors, among other
   8591   // things.
   8592   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
   8593     CheckConstructor(Constructor);
   8594 
   8595   // Check the default arguments, which we may have added.
   8596   if (!Method->isInvalidDecl())
   8597     CheckCXXDefaultArguments(Method);
   8598 }
   8599 
   8600 // Emit the given diagnostic for each non-address-space qualifier.
   8601 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
   8602 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
   8603   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
   8604   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
   8605     bool DiagOccured = false;
   8606     FTI.MethodQualifiers->forEachQualifier(
   8607         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
   8608                                    SourceLocation SL) {
   8609           // This diagnostic should be emitted on any qualifier except an addr
   8610           // space qualifier. However, forEachQualifier currently doesn't visit
   8611           // addr space qualifiers, so there's no way to write this condition
   8612           // right now; we just diagnose on everything.
   8613           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
   8614           DiagOccured = true;
   8615         });
   8616     if (DiagOccured)
   8617       D.setInvalidType();
   8618   }
   8619 }
   8620 
   8621 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
   8622 /// the well-formedness of the constructor declarator @p D with type @p
   8623 /// R. If there are any errors in the declarator, this routine will
   8624 /// emit diagnostics and set the invalid bit to true.  In any case, the type
   8625 /// will be updated to reflect a well-formed type for the constructor and
   8626 /// returned.
   8627 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
   8628                                           StorageClass &SC) {
   8629   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
   8630 
   8631   // C++ [class.ctor]p3:
   8632   //   A constructor shall not be virtual (10.3) or static (9.4). A
   8633   //   constructor can be invoked for a const, volatile or const
   8634   //   volatile object. A constructor shall not be declared const,
   8635   //   volatile, or const volatile (9.3.2).
   8636   if (isVirtual) {
   8637     if (!D.isInvalidType())
   8638       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
   8639         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
   8640         << SourceRange(D.getIdentifierLoc());
   8641     D.setInvalidType();
   8642   }
   8643   if (SC == SC_Static) {
   8644     if (!D.isInvalidType())
   8645       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
   8646         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
   8647         << SourceRange(D.getIdentifierLoc());
   8648     D.setInvalidType();
   8649     SC = SC_None;
   8650   }
   8651 
   8652   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
   8653     diagnoseIgnoredQualifiers(
   8654         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
   8655         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
   8656         D.getDeclSpec().getRestrictSpecLoc(),
   8657         D.getDeclSpec().getAtomicSpecLoc());
   8658     D.setInvalidType();
   8659   }
   8660 
   8661   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
   8662 
   8663   // C++0x [class.ctor]p4:
   8664   //   A constructor shall not be declared with a ref-qualifier.
   8665   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
   8666   if (FTI.hasRefQualifier()) {
   8667     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
   8668       << FTI.RefQualifierIsLValueRef
   8669       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
   8670     D.setInvalidType();
   8671   }
   8672 
   8673   // Rebuild the function type "R" without any type qualifiers (in
   8674   // case any of the errors above fired) and with "void" as the
   8675   // return type, since constructors don't have return types.
   8676   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
   8677   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
   8678     return R;
   8679 
   8680   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
   8681   EPI.TypeQuals = Qualifiers();
   8682   EPI.RefQualifier = RQ_None;
   8683 
   8684   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
   8685 }
   8686 
   8687 /// CheckConstructor - Checks a fully-formed constructor for
   8688 /// well-formedness, issuing any diagnostics required. Returns true if
   8689 /// the constructor declarator is invalid.
   8690 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
   8691   CXXRecordDecl *ClassDecl
   8692     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
   8693   if (!ClassDecl)
   8694     return Constructor->setInvalidDecl();
   8695 
   8696   // C++ [class.copy]p3:
   8697   //   A declaration of a constructor for a class X is ill-formed if
   8698   //   its first parameter is of type (optionally cv-qualified) X and
   8699   //   either there are no other parameters or else all other
   8700   //   parameters have default arguments.
   8701   if (!Constructor->isInvalidDecl() &&
   8702       ((Constructor->getNumParams() == 1) ||
   8703        (Constructor->getNumParams() > 1 &&
   8704         Constructor->getParamDecl(1)->hasDefaultArg())) &&
   8705       Constructor->getTemplateSpecializationKind()
   8706                                               != TSK_ImplicitInstantiation) {
   8707     QualType ParamType = Constructor->getParamDecl(0)->getType();
   8708     QualType ClassTy = Context.getTagDeclType(ClassDecl);
   8709     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
   8710       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
   8711       const char *ConstRef
   8712         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
   8713                                                         : " const &";
   8714       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
   8715         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
   8716 
   8717       // FIXME: Rather that making the constructor invalid, we should endeavor
   8718       // to fix the type.
   8719       Constructor->setInvalidDecl();
   8720     }
   8721   }
   8722 }
   8723 
   8724 /// CheckDestructor - Checks a fully-formed destructor definition for
   8725 /// well-formedness, issuing any diagnostics required.  Returns true
   8726 /// on error.
   8727 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
   8728   CXXRecordDecl *RD = Destructor->getParent();
   8729 
   8730   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
   8731     SourceLocation Loc;
   8732 
   8733     if (!Destructor->isImplicit())
   8734       Loc = Destructor->getLocation();
   8735     else
   8736       Loc = RD->getLocation();
   8737 
   8738     // If we have a virtual destructor, look up the deallocation function
   8739     if (FunctionDecl *OperatorDelete =
   8740             FindDeallocationFunctionForDestructor(Loc, RD)) {
   8741       Expr *ThisArg = nullptr;
   8742 
   8743       // If the notional 'delete this' expression requires a non-trivial
   8744       // conversion from 'this' to the type of a destroying operator delete's
   8745       // first parameter, perform that conversion now.
   8746       if (OperatorDelete->isDestroyingOperatorDelete()) {
   8747         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
   8748         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
   8749           // C++ [class.dtor]p13:
   8750           //   ... as if for the expression 'delete this' appearing in a
   8751           //   non-virtual destructor of the destructor's class.
   8752           ContextRAII SwitchContext(*this, Destructor);
   8753           ExprResult This =
   8754               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
   8755           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
   8756           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
   8757           if (This.isInvalid()) {
   8758             // FIXME: Register this as a context note so that it comes out
   8759             // in the right order.
   8760             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
   8761             return true;
   8762           }
   8763           ThisArg = This.get();
   8764         }
   8765       }
   8766 
   8767       DiagnoseUseOfDecl(OperatorDelete, Loc);
   8768       MarkFunctionReferenced(Loc, OperatorDelete);
   8769       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
   8770     }
   8771   }
   8772 
   8773   return false;
   8774 }
   8775 
   8776 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
   8777 /// the well-formednes of the destructor declarator @p D with type @p
   8778 /// R. If there are any errors in the declarator, this routine will
   8779 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
   8780 /// will be updated to reflect a well-formed type for the destructor and
   8781 /// returned.
   8782 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
   8783                                          StorageClass& SC) {
   8784   // C++ [class.dtor]p1:
   8785   //   [...] A typedef-name that names a class is a class-name
   8786   //   (7.1.3); however, a typedef-name that names a class shall not
   8787   //   be used as the identifier in the declarator for a destructor
   8788   //   declaration.
   8789   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
   8790   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
   8791     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
   8792       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
   8793   else if (const TemplateSpecializationType *TST =
   8794              DeclaratorType->getAs<TemplateSpecializationType>())
   8795     if (TST->isTypeAlias())
   8796       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
   8797         << DeclaratorType << 1;
   8798 
   8799   // C++ [class.dtor]p2:
   8800   //   A destructor is used to destroy objects of its class type. A
   8801   //   destructor takes no parameters, and no return type can be
   8802   //   specified for it (not even void). The address of a destructor
   8803   //   shall not be taken. A destructor shall not be static. A
   8804   //   destructor can be invoked for a const, volatile or const
   8805   //   volatile object. A destructor shall not be declared const,
   8806   //   volatile or const volatile (9.3.2).
   8807   if (SC == SC_Static) {
   8808     if (!D.isInvalidType())
   8809       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
   8810         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
   8811         << SourceRange(D.getIdentifierLoc())
   8812         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
   8813 
   8814     SC = SC_None;
   8815   }
   8816   if (!D.isInvalidType()) {
   8817     // Destructors don't have return types, but the parser will
   8818     // happily parse something like:
   8819     //
   8820     //   class X {
   8821     //     float ~X();
   8822     //   };
   8823     //
   8824     // The return type will be eliminated later.
   8825     if (D.getDeclSpec().hasTypeSpecifier())
   8826       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
   8827         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
   8828         << SourceRange(D.getIdentifierLoc());
   8829     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
   8830       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
   8831                                 SourceLocation(),
   8832                                 D.getDeclSpec().getConstSpecLoc(),
   8833                                 D.getDeclSpec().getVolatileSpecLoc(),
   8834                                 D.getDeclSpec().getRestrictSpecLoc(),
   8835                                 D.getDeclSpec().getAtomicSpecLoc());
   8836       D.setInvalidType();
   8837     }
   8838   }
   8839 
   8840   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
   8841 
   8842   // C++0x [class.dtor]p2:
   8843   //   A destructor shall not be declared with a ref-qualifier.
   8844   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
   8845   if (FTI.hasRefQualifier()) {
   8846     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
   8847       << FTI.RefQualifierIsLValueRef
   8848       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
   8849     D.setInvalidType();
   8850   }
   8851 
   8852   // Make sure we don't have any parameters.
   8853   if (FTIHasNonVoidParameters(FTI)) {
   8854     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
   8855 
   8856     // Delete the parameters.
   8857     FTI.freeParams();
   8858     D.setInvalidType();
   8859   }
   8860 
   8861   // Make sure the destructor isn't variadic.
   8862   if (FTI.isVariadic) {
   8863     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
   8864     D.setInvalidType();
   8865   }
   8866 
   8867   // Rebuild the function type "R" without any type qualifiers or
   8868   // parameters (in case any of the errors above fired) and with
   8869   // "void" as the return type, since destructors don't have return
   8870   // types.
   8871   if (!D.isInvalidType())
   8872     return R;
   8873 
   8874   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
   8875   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
   8876   EPI.Variadic = false;
   8877   EPI.TypeQuals = Qualifiers();
   8878   EPI.RefQualifier = RQ_None;
   8879   return Context.getFunctionType(Context.VoidTy, None, EPI);
   8880 }
   8881 
   8882 static void extendLeft(SourceRange &R, SourceRange Before) {
   8883   if (Before.isInvalid())
   8884     return;
   8885   R.setBegin(Before.getBegin());
   8886   if (R.getEnd().isInvalid())
   8887     R.setEnd(Before.getEnd());
   8888 }
   8889 
   8890 static void extendRight(SourceRange &R, SourceRange After) {
   8891   if (After.isInvalid())
   8892     return;
   8893   if (R.getBegin().isInvalid())
   8894     R.setBegin(After.getBegin());
   8895   R.setEnd(After.getEnd());
   8896 }
   8897 
   8898 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
   8899 /// well-formednes of the conversion function declarator @p D with
   8900 /// type @p R. If there are any errors in the declarator, this routine
   8901 /// will emit diagnostics and return true. Otherwise, it will return
   8902 /// false. Either way, the type @p R will be updated to reflect a
   8903 /// well-formed type for the conversion operator.
   8904 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
   8905                                      StorageClass& SC) {
   8906   // C++ [class.conv.fct]p1:
   8907   //   Neither parameter types nor return type can be specified. The
   8908   //   type of a conversion function (8.3.5) is "function taking no
   8909   //   parameter returning conversion-type-id."
   8910   if (SC == SC_Static) {
   8911     if (!D.isInvalidType())
   8912       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
   8913         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
   8914         << D.getName().getSourceRange();
   8915     D.setInvalidType();
   8916     SC = SC_None;
   8917   }
   8918 
   8919   TypeSourceInfo *ConvTSI = nullptr;
   8920   QualType ConvType =
   8921       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
   8922 
   8923   const DeclSpec &DS = D.getDeclSpec();
   8924   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
   8925     // Conversion functions don't have return types, but the parser will
   8926     // happily parse something like:
   8927     //
   8928     //   class X {
   8929     //     float operator bool();
   8930     //   };
   8931     //
   8932     // The return type will be changed later anyway.
   8933     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
   8934       << SourceRange(DS.getTypeSpecTypeLoc())
   8935       << SourceRange(D.getIdentifierLoc());
   8936     D.setInvalidType();
   8937   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
   8938     // It's also plausible that the user writes type qualifiers in the wrong
   8939     // place, such as:
   8940     //   struct S { const operator int(); };
   8941     // FIXME: we could provide a fixit to move the qualifiers onto the
   8942     // conversion type.
   8943     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
   8944         << SourceRange(D.getIdentifierLoc()) << 0;
   8945     D.setInvalidType();
   8946   }
   8947 
   8948   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
   8949 
   8950   // Make sure we don't have any parameters.
   8951   if (Proto->getNumParams() > 0) {
   8952     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
   8953 
   8954     // Delete the parameters.
   8955     D.getFunctionTypeInfo().freeParams();
   8956     D.setInvalidType();
   8957   } else if (Proto->isVariadic()) {
   8958     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
   8959     D.setInvalidType();
   8960   }
   8961 
   8962   // Diagnose "&operator bool()" and other such nonsense.  This
   8963   // is actually a gcc extension which we don't support.
   8964   if (Proto->getReturnType() != ConvType) {
   8965     bool NeedsTypedef = false;
   8966     SourceRange Before, After;
   8967 
   8968     // Walk the chunks and extract information on them for our diagnostic.
   8969     bool PastFunctionChunk = false;
   8970     for (auto &Chunk : D.type_objects()) {
   8971       switch (Chunk.Kind) {
   8972       case DeclaratorChunk::Function:
   8973         if (!PastFunctionChunk) {
   8974           if (Chunk.Fun.HasTrailingReturnType) {
   8975             TypeSourceInfo *TRT = nullptr;
   8976             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
   8977             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
   8978           }
   8979           PastFunctionChunk = true;
   8980           break;
   8981         }
   8982         LLVM_FALLTHROUGH;
   8983       case DeclaratorChunk::Array:
   8984         NeedsTypedef = true;
   8985         extendRight(After, Chunk.getSourceRange());
   8986         break;
   8987 
   8988       case DeclaratorChunk::Pointer:
   8989       case DeclaratorChunk::BlockPointer:
   8990       case DeclaratorChunk::Reference:
   8991       case DeclaratorChunk::MemberPointer:
   8992       case DeclaratorChunk::Pipe:
   8993         extendLeft(Before, Chunk.getSourceRange());
   8994         break;
   8995 
   8996       case DeclaratorChunk::Paren:
   8997         extendLeft(Before, Chunk.Loc);
   8998         extendRight(After, Chunk.EndLoc);
   8999         break;
   9000       }
   9001     }
   9002 
   9003     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
   9004                          After.isValid()  ? After.getBegin() :
   9005                                             D.getIdentifierLoc();
   9006     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
   9007     DB << Before << After;
   9008 
   9009     if (!NeedsTypedef) {
   9010       DB << /*don't need a typedef*/0;
   9011 
   9012       // If we can provide a correct fix-it hint, do so.
   9013       if (After.isInvalid() && ConvTSI) {
   9014         SourceLocation InsertLoc =
   9015             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
   9016         DB << FixItHint::CreateInsertion(InsertLoc, " ")
   9017            << FixItHint::CreateInsertionFromRange(
   9018                   InsertLoc, CharSourceRange::getTokenRange(Before))
   9019            << FixItHint::CreateRemoval(Before);
   9020       }
   9021     } else if (!Proto->getReturnType()->isDependentType()) {
   9022       DB << /*typedef*/1 << Proto->getReturnType();
   9023     } else if (getLangOpts().CPlusPlus11) {
   9024       DB << /*alias template*/2 << Proto->getReturnType();
   9025     } else {
   9026       DB << /*might not be fixable*/3;
   9027     }
   9028 
   9029     // Recover by incorporating the other type chunks into the result type.
   9030     // Note, this does *not* change the name of the function. This is compatible
   9031     // with the GCC extension:
   9032     //   struct S { &operator int(); } s;
   9033     //   int &r = s.operator int(); // ok in GCC
   9034     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
   9035     ConvType = Proto->getReturnType();
   9036   }
   9037 
   9038   // C++ [class.conv.fct]p4:
   9039   //   The conversion-type-id shall not represent a function type nor
   9040   //   an array type.
   9041   if (ConvType->isArrayType()) {
   9042     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
   9043     ConvType = Context.getPointerType(ConvType);
   9044     D.setInvalidType();
   9045   } else if (ConvType->isFunctionType()) {
   9046     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
   9047     ConvType = Context.getPointerType(ConvType);
   9048     D.setInvalidType();
   9049   }
   9050 
   9051   // Rebuild the function type "R" without any parameters (in case any
   9052   // of the errors above fired) and with the conversion type as the
   9053   // return type.
   9054   if (D.isInvalidType())
   9055     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
   9056 
   9057   // C++0x explicit conversion operators.
   9058   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
   9059     Diag(DS.getExplicitSpecLoc(),
   9060          getLangOpts().CPlusPlus11
   9061              ? diag::warn_cxx98_compat_explicit_conversion_functions
   9062              : diag::ext_explicit_conversion_functions)
   9063         << SourceRange(DS.getExplicitSpecRange());
   9064 }
   9065 
   9066 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
   9067 /// the declaration of the given C++ conversion function. This routine
   9068 /// is responsible for recording the conversion function in the C++
   9069 /// class, if possible.
   9070 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
   9071   assert(Conversion && "Expected to receive a conversion function declaration");
   9072 
   9073   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
   9074 
   9075   // Make sure we aren't redeclaring the conversion function.
   9076   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
   9077 
   9078   // C++ [class.conv.fct]p1:
   9079   //   [...] A conversion function is never used to convert a
   9080   //   (possibly cv-qualified) object to the (possibly cv-qualified)
   9081   //   same object type (or a reference to it), to a (possibly
   9082   //   cv-qualified) base class of that type (or a reference to it),
   9083   //   or to (possibly cv-qualified) void.
   9084   // FIXME: Suppress this warning if the conversion function ends up being a
   9085   // virtual function that overrides a virtual function in a base class.
   9086   QualType ClassType
   9087     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
   9088   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
   9089     ConvType = ConvTypeRef->getPointeeType();
   9090   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
   9091       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
   9092     /* Suppress diagnostics for instantiations. */;
   9093   else if (ConvType->isRecordType()) {
   9094     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
   9095     if (ConvType == ClassType)
   9096       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
   9097         << ClassType;
   9098     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
   9099       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
   9100         <<  ClassType << ConvType;
   9101   } else if (ConvType->isVoidType()) {
   9102     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
   9103       << ClassType << ConvType;
   9104   }
   9105 
   9106   if (FunctionTemplateDecl *ConversionTemplate
   9107                                 = Conversion->getDescribedFunctionTemplate())
   9108     return ConversionTemplate;
   9109 
   9110   return Conversion;
   9111 }
   9112 
   9113 namespace {
   9114 /// Utility class to accumulate and print a diagnostic listing the invalid
   9115 /// specifier(s) on a declaration.
   9116 struct BadSpecifierDiagnoser {
   9117   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
   9118       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
   9119   ~BadSpecifierDiagnoser() {
   9120     Diagnostic << Specifiers;
   9121   }
   9122 
   9123   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
   9124     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
   9125   }
   9126   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
   9127     return check(SpecLoc,
   9128                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
   9129   }
   9130   void check(SourceLocation SpecLoc, const char *Spec) {
   9131     if (SpecLoc.isInvalid()) return;
   9132     Diagnostic << SourceRange(SpecLoc, SpecLoc);
   9133     if (!Specifiers.empty()) Specifiers += " ";
   9134     Specifiers += Spec;
   9135   }
   9136 
   9137   Sema &S;
   9138   Sema::SemaDiagnosticBuilder Diagnostic;
   9139   std::string Specifiers;
   9140 };
   9141 }
   9142 
   9143 /// Check the validity of a declarator that we parsed for a deduction-guide.
   9144 /// These aren't actually declarators in the grammar, so we need to check that
   9145 /// the user didn't specify any pieces that are not part of the deduction-guide
   9146 /// grammar.
   9147 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
   9148                                          StorageClass &SC) {
   9149   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
   9150   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
   9151   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
   9152 
   9153   // C++ [temp.deduct.guide]p3:
   9154   //   A deduction-gide shall be declared in the same scope as the
   9155   //   corresponding class template.
   9156   if (!CurContext->getRedeclContext()->Equals(
   9157           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
   9158     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
   9159       << GuidedTemplateDecl;
   9160     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
   9161   }
   9162 
   9163   auto &DS = D.getMutableDeclSpec();
   9164   // We leave 'friend' and 'virtual' to be rejected in the normal way.
   9165   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
   9166       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
   9167       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
   9168     BadSpecifierDiagnoser Diagnoser(
   9169         *this, D.getIdentifierLoc(),
   9170         diag::err_deduction_guide_invalid_specifier);
   9171 
   9172     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
   9173     DS.ClearStorageClassSpecs();
   9174     SC = SC_None;
   9175 
   9176     // 'explicit' is permitted.
   9177     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
   9178     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
   9179     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
   9180     DS.ClearConstexprSpec();
   9181 
   9182     Diagnoser.check(DS.getConstSpecLoc(), "const");
   9183     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
   9184     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
   9185     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
   9186     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
   9187     DS.ClearTypeQualifiers();
   9188 
   9189     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
   9190     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
   9191     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
   9192     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
   9193     DS.ClearTypeSpecType();
   9194   }
   9195 
   9196   if (D.isInvalidType())
   9197     return;
   9198 
   9199   // Check the declarator is simple enough.
   9200   bool FoundFunction = false;
   9201   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
   9202     if (Chunk.Kind == DeclaratorChunk::Paren)
   9203       continue;
   9204     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
   9205       Diag(D.getDeclSpec().getBeginLoc(),
   9206            diag::err_deduction_guide_with_complex_decl)
   9207           << D.getSourceRange();
   9208       break;
   9209     }
   9210     if (!Chunk.Fun.hasTrailingReturnType()) {
   9211       Diag(D.getName().getBeginLoc(),
   9212            diag::err_deduction_guide_no_trailing_return_type);
   9213       break;
   9214     }
   9215 
   9216     // Check that the return type is written as a specialization of
   9217     // the template specified as the deduction-guide's name.
   9218     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
   9219     TypeSourceInfo *TSI = nullptr;
   9220     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
   9221     assert(TSI && "deduction guide has valid type but invalid return type?");
   9222     bool AcceptableReturnType = false;
   9223     bool MightInstantiateToSpecialization = false;
   9224     if (auto RetTST =
   9225             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
   9226       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
   9227       bool TemplateMatches =
   9228           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
   9229       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
   9230         AcceptableReturnType = true;
   9231       else {
   9232         // This could still instantiate to the right type, unless we know it
   9233         // names the wrong class template.
   9234         auto *TD = SpecifiedName.getAsTemplateDecl();
   9235         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
   9236                                              !TemplateMatches);
   9237       }
   9238     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
   9239       MightInstantiateToSpecialization = true;
   9240     }
   9241 
   9242     if (!AcceptableReturnType) {
   9243       Diag(TSI->getTypeLoc().getBeginLoc(),
   9244            diag::err_deduction_guide_bad_trailing_return_type)
   9245           << GuidedTemplate << TSI->getType()
   9246           << MightInstantiateToSpecialization
   9247           << TSI->getTypeLoc().getSourceRange();
   9248     }
   9249 
   9250     // Keep going to check that we don't have any inner declarator pieces (we
   9251     // could still have a function returning a pointer to a function).
   9252     FoundFunction = true;
   9253   }
   9254 
   9255   if (D.isFunctionDefinition())
   9256     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
   9257 }
   9258 
   9259 //===----------------------------------------------------------------------===//
   9260 // Namespace Handling
   9261 //===----------------------------------------------------------------------===//
   9262 
   9263 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
   9264 /// reopened.
   9265 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
   9266                                             SourceLocation Loc,
   9267                                             IdentifierInfo *II, bool *IsInline,
   9268                                             NamespaceDecl *PrevNS) {
   9269   assert(*IsInline != PrevNS->isInline());
   9270 
   9271   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
   9272   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
   9273   // inline namespaces, with the intention of bringing names into namespace std.
   9274   //
   9275   // We support this just well enough to get that case working; this is not
   9276   // sufficient to support reopening namespaces as inline in general.
   9277   if (*IsInline && II && II->getName().startswith("__atomic") &&
   9278       S.getSourceManager().isInSystemHeader(Loc)) {
   9279     // Mark all prior declarations of the namespace as inline.
   9280     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
   9281          NS = NS->getPreviousDecl())
   9282       NS->setInline(*IsInline);
   9283     // Patch up the lookup table for the containing namespace. This isn't really
   9284     // correct, but it's good enough for this particular case.
   9285     for (auto *I : PrevNS->decls())
   9286       if (auto *ND = dyn_cast<NamedDecl>(I))
   9287         PrevNS->getParent()->makeDeclVisibleInContext(ND);
   9288     return;
   9289   }
   9290 
   9291   if (PrevNS->isInline())
   9292     // The user probably just forgot the 'inline', so suggest that it
   9293     // be added back.
   9294     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
   9295       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
   9296   else
   9297     S.Diag(Loc, diag::err_inline_namespace_mismatch);
   9298 
   9299   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
   9300   *IsInline = PrevNS->isInline();
   9301 }
   9302 
   9303 /// ActOnStartNamespaceDef - This is called at the start of a namespace
   9304 /// definition.
   9305 Decl *Sema::ActOnStartNamespaceDef(
   9306     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
   9307     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
   9308     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
   9309   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
   9310   // For anonymous namespace, take the location of the left brace.
   9311   SourceLocation Loc = II ? IdentLoc : LBrace;
   9312   bool IsInline = InlineLoc.isValid();
   9313   bool IsInvalid = false;
   9314   bool IsStd = false;
   9315   bool AddToKnown = false;
   9316   Scope *DeclRegionScope = NamespcScope->getParent();
   9317 
   9318   NamespaceDecl *PrevNS = nullptr;
   9319   if (II) {
   9320     // C++ [namespace.def]p2:
   9321     //   The identifier in an original-namespace-definition shall not
   9322     //   have been previously defined in the declarative region in
   9323     //   which the original-namespace-definition appears. The
   9324     //   identifier in an original-namespace-definition is the name of
   9325     //   the namespace. Subsequently in that declarative region, it is
   9326     //   treated as an original-namespace-name.
   9327     //
   9328     // Since namespace names are unique in their scope, and we don't
   9329     // look through using directives, just look for any ordinary names
   9330     // as if by qualified name lookup.
   9331     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
   9332                    ForExternalRedeclaration);
   9333     LookupQualifiedName(R, CurContext->getRedeclContext());
   9334     NamedDecl *PrevDecl =
   9335         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
   9336     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
   9337 
   9338     if (PrevNS) {
   9339       // This is an extended namespace definition.
   9340       if (IsInline != PrevNS->isInline())
   9341         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
   9342                                         &IsInline, PrevNS);
   9343     } else if (PrevDecl) {
   9344       // This is an invalid name redefinition.
   9345       Diag(Loc, diag::err_redefinition_different_kind)
   9346         << II;
   9347       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   9348       IsInvalid = true;
   9349       // Continue on to push Namespc as current DeclContext and return it.
   9350     } else if (II->isStr("std") &&
   9351                CurContext->getRedeclContext()->isTranslationUnit()) {
   9352       // This is the first "real" definition of the namespace "std", so update
   9353       // our cache of the "std" namespace to point at this definition.
   9354       PrevNS = getStdNamespace();
   9355       IsStd = true;
   9356       AddToKnown = !IsInline;
   9357     } else {
   9358       // We've seen this namespace for the first time.
   9359       AddToKnown = !IsInline;
   9360     }
   9361   } else {
   9362     // Anonymous namespaces.
   9363 
   9364     // Determine whether the parent already has an anonymous namespace.
   9365     DeclContext *Parent = CurContext->getRedeclContext();
   9366     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
   9367       PrevNS = TU->getAnonymousNamespace();
   9368     } else {
   9369       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
   9370       PrevNS = ND->getAnonymousNamespace();
   9371     }
   9372 
   9373     if (PrevNS && IsInline != PrevNS->isInline())
   9374       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
   9375                                       &IsInline, PrevNS);
   9376   }
   9377 
   9378   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
   9379                                                  StartLoc, Loc, II, PrevNS);
   9380   if (IsInvalid)
   9381     Namespc->setInvalidDecl();
   9382 
   9383   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
   9384   AddPragmaAttributes(DeclRegionScope, Namespc);
   9385 
   9386   // FIXME: Should we be merging attributes?
   9387   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
   9388     PushNamespaceVisibilityAttr(Attr, Loc);
   9389 
   9390   if (IsStd)
   9391     StdNamespace = Namespc;
   9392   if (AddToKnown)
   9393     KnownNamespaces[Namespc] = false;
   9394 
   9395   if (II) {
   9396     PushOnScopeChains(Namespc, DeclRegionScope);
   9397   } else {
   9398     // Link the anonymous namespace into its parent.
   9399     DeclContext *Parent = CurContext->getRedeclContext();
   9400     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
   9401       TU->setAnonymousNamespace(Namespc);
   9402     } else {
   9403       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
   9404     }
   9405 
   9406     CurContext->addDecl(Namespc);
   9407 
   9408     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
   9409     //   behaves as if it were replaced by
   9410     //     namespace unique { /* empty body */ }
   9411     //     using namespace unique;
   9412     //     namespace unique { namespace-body }
   9413     //   where all occurrences of 'unique' in a translation unit are
   9414     //   replaced by the same identifier and this identifier differs
   9415     //   from all other identifiers in the entire program.
   9416 
   9417     // We just create the namespace with an empty name and then add an
   9418     // implicit using declaration, just like the standard suggests.
   9419     //
   9420     // CodeGen enforces the "universally unique" aspect by giving all
   9421     // declarations semantically contained within an anonymous
   9422     // namespace internal linkage.
   9423 
   9424     if (!PrevNS) {
   9425       UD = UsingDirectiveDecl::Create(Context, Parent,
   9426                                       /* 'using' */ LBrace,
   9427                                       /* 'namespace' */ SourceLocation(),
   9428                                       /* qualifier */ NestedNameSpecifierLoc(),
   9429                                       /* identifier */ SourceLocation(),
   9430                                       Namespc,
   9431                                       /* Ancestor */ Parent);
   9432       UD->setImplicit();
   9433       Parent->addDecl(UD);
   9434     }
   9435   }
   9436 
   9437   ActOnDocumentableDecl(Namespc);
   9438 
   9439   // Although we could have an invalid decl (i.e. the namespace name is a
   9440   // redefinition), push it as current DeclContext and try to continue parsing.
   9441   // FIXME: We should be able to push Namespc here, so that the each DeclContext
   9442   // for the namespace has the declarations that showed up in that particular
   9443   // namespace definition.
   9444   PushDeclContext(NamespcScope, Namespc);
   9445   return Namespc;
   9446 }
   9447 
   9448 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
   9449 /// is a namespace alias, returns the namespace it points to.
   9450 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
   9451   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
   9452     return AD->getNamespace();
   9453   return dyn_cast_or_null<NamespaceDecl>(D);
   9454 }
   9455 
   9456 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
   9457 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
   9458 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
   9459   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
   9460   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
   9461   Namespc->setRBraceLoc(RBrace);
   9462   PopDeclContext();
   9463   if (Namespc->hasAttr<VisibilityAttr>())
   9464     PopPragmaVisibility(true, RBrace);
   9465   // If this namespace contains an export-declaration, export it now.
   9466   if (DeferredExportedNamespaces.erase(Namespc))
   9467     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
   9468 }
   9469 
   9470 CXXRecordDecl *Sema::getStdBadAlloc() const {
   9471   return cast_or_null<CXXRecordDecl>(
   9472                                   StdBadAlloc.get(Context.getExternalSource()));
   9473 }
   9474 
   9475 EnumDecl *Sema::getStdAlignValT() const {
   9476   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
   9477 }
   9478 
   9479 NamespaceDecl *Sema::getStdNamespace() const {
   9480   return cast_or_null<NamespaceDecl>(
   9481                                  StdNamespace.get(Context.getExternalSource()));
   9482 }
   9483 
   9484 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
   9485   if (!StdExperimentalNamespaceCache) {
   9486     if (auto Std = getStdNamespace()) {
   9487       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
   9488                           SourceLocation(), LookupNamespaceName);
   9489       if (!LookupQualifiedName(Result, Std) ||
   9490           !(StdExperimentalNamespaceCache =
   9491                 Result.getAsSingle<NamespaceDecl>()))
   9492         Result.suppressDiagnostics();
   9493     }
   9494   }
   9495   return StdExperimentalNamespaceCache;
   9496 }
   9497 
   9498 namespace {
   9499 
   9500 enum UnsupportedSTLSelect {
   9501   USS_InvalidMember,
   9502   USS_MissingMember,
   9503   USS_NonTrivial,
   9504   USS_Other
   9505 };
   9506 
   9507 struct InvalidSTLDiagnoser {
   9508   Sema &S;
   9509   SourceLocation Loc;
   9510   QualType TyForDiags;
   9511 
   9512   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
   9513                       const VarDecl *VD = nullptr) {
   9514     {
   9515       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
   9516                << TyForDiags << ((int)Sel);
   9517       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
   9518         assert(!Name.empty());
   9519         D << Name;
   9520       }
   9521     }
   9522     if (Sel == USS_InvalidMember) {
   9523       S.Diag(VD->getLocation(), diag::note_var_declared_here)
   9524           << VD << VD->getSourceRange();
   9525     }
   9526     return QualType();
   9527   }
   9528 };
   9529 } // namespace
   9530 
   9531 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
   9532                                            SourceLocation Loc) {
   9533   assert(getLangOpts().CPlusPlus &&
   9534          "Looking for comparison category type outside of C++.");
   9535 
   9536   // Check if we've already successfully checked the comparison category type
   9537   // before. If so, skip checking it again.
   9538   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
   9539   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
   9540     return Info->getType();
   9541 
   9542   // If lookup failed
   9543   if (!Info) {
   9544     std::string NameForDiags = "std::";
   9545     NameForDiags += ComparisonCategories::getCategoryString(Kind);
   9546     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
   9547         << NameForDiags;
   9548     return QualType();
   9549   }
   9550 
   9551   assert(Info->Kind == Kind);
   9552   assert(Info->Record);
   9553 
   9554   // Update the Record decl in case we encountered a forward declaration on our
   9555   // first pass. FIXME: This is a bit of a hack.
   9556   if (Info->Record->hasDefinition())
   9557     Info->Record = Info->Record->getDefinition();
   9558 
   9559   // Use an elaborated type for diagnostics which has a name containing the
   9560   // prepended 'std' namespace but not any inline namespace names.
   9561   QualType TyForDiags = [&]() {
   9562     auto *NNS =
   9563         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
   9564     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
   9565   }();
   9566 
   9567   if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
   9568     return QualType();
   9569 
   9570   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
   9571 
   9572   if (!Info->Record->isTriviallyCopyable())
   9573     return UnsupportedSTLError(USS_NonTrivial);
   9574 
   9575   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
   9576     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
   9577     // Tolerate empty base classes.
   9578     if (Base->isEmpty())
   9579       continue;
   9580     // Reject STL implementations which have at least one non-empty base.
   9581     return UnsupportedSTLError();
   9582   }
   9583 
   9584   // Check that the STL has implemented the types using a single integer field.
   9585   // This expectation allows better codegen for builtin operators. We require:
   9586   //   (1) The class has exactly one field.
   9587   //   (2) The field is an integral or enumeration type.
   9588   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
   9589   if (std::distance(FIt, FEnd) != 1 ||
   9590       !FIt->getType()->isIntegralOrEnumerationType()) {
   9591     return UnsupportedSTLError();
   9592   }
   9593 
   9594   // Build each of the require values and store them in Info.
   9595   for (ComparisonCategoryResult CCR :
   9596        ComparisonCategories::getPossibleResultsForType(Kind)) {
   9597     StringRef MemName = ComparisonCategories::getResultString(CCR);
   9598     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
   9599 
   9600     if (!ValInfo)
   9601       return UnsupportedSTLError(USS_MissingMember, MemName);
   9602 
   9603     VarDecl *VD = ValInfo->VD;
   9604     assert(VD && "should not be null!");
   9605 
   9606     // Attempt to diagnose reasons why the STL definition of this type
   9607     // might be foobar, including it failing to be a constant expression.
   9608     // TODO Handle more ways the lookup or result can be invalid.
   9609     if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
   9610         !VD->checkInitIsICE())
   9611       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
   9612 
   9613     // Attempt to evaluate the var decl as a constant expression and extract
   9614     // the value of its first field as a ICE. If this fails, the STL
   9615     // implementation is not supported.
   9616     if (!ValInfo->hasValidIntValue())
   9617       return UnsupportedSTLError();
   9618 
   9619     MarkVariableReferenced(Loc, VD);
   9620   }
   9621 
   9622   // We've successfully built the required types and expressions. Update
   9623   // the cache and return the newly cached value.
   9624   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
   9625   return Info->getType();
   9626 }
   9627 
   9628 /// Retrieve the special "std" namespace, which may require us to
   9629 /// implicitly define the namespace.
   9630 NamespaceDecl *Sema::getOrCreateStdNamespace() {
   9631   if (!StdNamespace) {
   9632     // The "std" namespace has not yet been defined, so build one implicitly.
   9633     StdNamespace = NamespaceDecl::Create(Context,
   9634                                          Context.getTranslationUnitDecl(),
   9635                                          /*Inline=*/false,
   9636                                          SourceLocation(), SourceLocation(),
   9637                                          &PP.getIdentifierTable().get("std"),
   9638                                          /*PrevDecl=*/nullptr);
   9639     getStdNamespace()->setImplicit(true);
   9640   }
   9641 
   9642   return getStdNamespace();
   9643 }
   9644 
   9645 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
   9646   assert(getLangOpts().CPlusPlus &&
   9647          "Looking for std::initializer_list outside of C++.");
   9648 
   9649   // We're looking for implicit instantiations of
   9650   // template <typename E> class std::initializer_list.
   9651 
   9652   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
   9653     return false;
   9654 
   9655   ClassTemplateDecl *Template = nullptr;
   9656   const TemplateArgument *Arguments = nullptr;
   9657 
   9658   if (const RecordType *RT = Ty->getAs<RecordType>()) {
   9659 
   9660     ClassTemplateSpecializationDecl *Specialization =
   9661         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
   9662     if (!Specialization)
   9663       return false;
   9664 
   9665     Template = Specialization->getSpecializedTemplate();
   9666     Arguments = Specialization->getTemplateArgs().data();
   9667   } else if (const TemplateSpecializationType *TST =
   9668                  Ty->getAs<TemplateSpecializationType>()) {
   9669     Template = dyn_cast_or_null<ClassTemplateDecl>(
   9670         TST->getTemplateName().getAsTemplateDecl());
   9671     Arguments = TST->getArgs();
   9672   }
   9673   if (!Template)
   9674     return false;
   9675 
   9676   if (!StdInitializerList) {
   9677     // Haven't recognized std::initializer_list yet, maybe this is it.
   9678     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
   9679     if (TemplateClass->getIdentifier() !=
   9680             &PP.getIdentifierTable().get("initializer_list") ||
   9681         !getStdNamespace()->InEnclosingNamespaceSetOf(
   9682             TemplateClass->getDeclContext()))
   9683       return false;
   9684     // This is a template called std::initializer_list, but is it the right
   9685     // template?
   9686     TemplateParameterList *Params = Template->getTemplateParameters();
   9687     if (Params->getMinRequiredArguments() != 1)
   9688       return false;
   9689     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
   9690       return false;
   9691 
   9692     // It's the right template.
   9693     StdInitializerList = Template;
   9694   }
   9695 
   9696   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
   9697     return false;
   9698 
   9699   // This is an instance of std::initializer_list. Find the argument type.
   9700   if (Element)
   9701     *Element = Arguments[0].getAsType();
   9702   return true;
   9703 }
   9704 
   9705 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
   9706   NamespaceDecl *Std = S.getStdNamespace();
   9707   if (!Std) {
   9708     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
   9709     return nullptr;
   9710   }
   9711 
   9712   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
   9713                       Loc, Sema::LookupOrdinaryName);
   9714   if (!S.LookupQualifiedName(Result, Std)) {
   9715     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
   9716     return nullptr;
   9717   }
   9718   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
   9719   if (!Template) {
   9720     Result.suppressDiagnostics();
   9721     // We found something weird. Complain about the first thing we found.
   9722     NamedDecl *Found = *Result.begin();
   9723     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
   9724     return nullptr;
   9725   }
   9726 
   9727   // We found some template called std::initializer_list. Now verify that it's
   9728   // correct.
   9729   TemplateParameterList *Params = Template->getTemplateParameters();
   9730   if (Params->getMinRequiredArguments() != 1 ||
   9731       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
   9732     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
   9733     return nullptr;
   9734   }
   9735 
   9736   return Template;
   9737 }
   9738 
   9739 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
   9740   if (!StdInitializerList) {
   9741     StdInitializerList = LookupStdInitializerList(*this, Loc);
   9742     if (!StdInitializerList)
   9743       return QualType();
   9744   }
   9745 
   9746   TemplateArgumentListInfo Args(Loc, Loc);
   9747   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
   9748                                        Context.getTrivialTypeSourceInfo(Element,
   9749                                                                         Loc)));
   9750   return Context.getCanonicalType(
   9751       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
   9752 }
   9753 
   9754 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
   9755   // C++ [dcl.init.list]p2:
   9756   //   A constructor is an initializer-list constructor if its first parameter
   9757   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
   9758   //   std::initializer_list<E> for some type E, and either there are no other
   9759   //   parameters or else all other parameters have default arguments.
   9760   if (Ctor->getNumParams() < 1 ||
   9761       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
   9762     return false;
   9763 
   9764   QualType ArgType = Ctor->getParamDecl(0)->getType();
   9765   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
   9766     ArgType = RT->getPointeeType().getUnqualifiedType();
   9767 
   9768   return isStdInitializerList(ArgType, nullptr);
   9769 }
   9770 
   9771 /// Determine whether a using statement is in a context where it will be
   9772 /// apply in all contexts.
   9773 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
   9774   switch (CurContext->getDeclKind()) {
   9775     case Decl::TranslationUnit:
   9776       return true;
   9777     case Decl::LinkageSpec:
   9778       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
   9779     default:
   9780       return false;
   9781   }
   9782 }
   9783 
   9784 namespace {
   9785 
   9786 // Callback to only accept typo corrections that are namespaces.
   9787 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
   9788 public:
   9789   bool ValidateCandidate(const TypoCorrection &candidate) override {
   9790     if (NamedDecl *ND = candidate.getCorrectionDecl())
   9791       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
   9792     return false;
   9793   }
   9794 
   9795   std::unique_ptr<CorrectionCandidateCallback> clone() override {
   9796     return std::make_unique<NamespaceValidatorCCC>(*this);
   9797   }
   9798 };
   9799 
   9800 }
   9801 
   9802 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
   9803                                        CXXScopeSpec &SS,
   9804                                        SourceLocation IdentLoc,
   9805                                        IdentifierInfo *Ident) {
   9806   R.clear();
   9807   NamespaceValidatorCCC CCC{};
   9808   if (TypoCorrection Corrected =
   9809           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
   9810                         Sema::CTK_ErrorRecovery)) {
   9811     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
   9812       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
   9813       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
   9814                               Ident->getName().equals(CorrectedStr);
   9815       S.diagnoseTypo(Corrected,
   9816                      S.PDiag(diag::err_using_directive_member_suggest)
   9817                        << Ident << DC << DroppedSpecifier << SS.getRange(),
   9818                      S.PDiag(diag::note_namespace_defined_here));
   9819     } else {
   9820       S.diagnoseTypo(Corrected,
   9821                      S.PDiag(diag::err_using_directive_suggest) << Ident,
   9822                      S.PDiag(diag::note_namespace_defined_here));
   9823     }
   9824     R.addDecl(Corrected.getFoundDecl());
   9825     return true;
   9826   }
   9827   return false;
   9828 }
   9829 
   9830 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
   9831                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
   9832                                 SourceLocation IdentLoc,
   9833                                 IdentifierInfo *NamespcName,
   9834                                 const ParsedAttributesView &AttrList) {
   9835   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
   9836   assert(NamespcName && "Invalid NamespcName.");
   9837   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
   9838 
   9839   // This can only happen along a recovery path.
   9840   while (S->isTemplateParamScope())
   9841     S = S->getParent();
   9842   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
   9843 
   9844   UsingDirectiveDecl *UDir = nullptr;
   9845   NestedNameSpecifier *Qualifier = nullptr;
   9846   if (SS.isSet())
   9847     Qualifier = SS.getScopeRep();
   9848 
   9849   // Lookup namespace name.
   9850   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
   9851   LookupParsedName(R, S, &SS);
   9852   if (R.isAmbiguous())
   9853     return nullptr;
   9854 
   9855   if (R.empty()) {
   9856     R.clear();
   9857     // Allow "using namespace std;" or "using namespace ::std;" even if
   9858     // "std" hasn't been defined yet, for GCC compatibility.
   9859     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
   9860         NamespcName->isStr("std")) {
   9861       Diag(IdentLoc, diag::ext_using_undefined_std);
   9862       R.addDecl(getOrCreateStdNamespace());
   9863       R.resolveKind();
   9864     }
   9865     // Otherwise, attempt typo correction.
   9866     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
   9867   }
   9868 
   9869   if (!R.empty()) {
   9870     NamedDecl *Named = R.getRepresentativeDecl();
   9871     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
   9872     assert(NS && "expected namespace decl");
   9873 
   9874     // The use of a nested name specifier may trigger deprecation warnings.
   9875     DiagnoseUseOfDecl(Named, IdentLoc);
   9876 
   9877     // C++ [namespace.udir]p1:
   9878     //   A using-directive specifies that the names in the nominated
   9879     //   namespace can be used in the scope in which the
   9880     //   using-directive appears after the using-directive. During
   9881     //   unqualified name lookup (3.4.1), the names appear as if they
   9882     //   were declared in the nearest enclosing namespace which
   9883     //   contains both the using-directive and the nominated
   9884     //   namespace. [Note: in this context, "contains" means "contains
   9885     //   directly or indirectly". ]
   9886 
   9887     // Find enclosing context containing both using-directive and
   9888     // nominated namespace.
   9889     DeclContext *CommonAncestor = NS;
   9890     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
   9891       CommonAncestor = CommonAncestor->getParent();
   9892 
   9893     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
   9894                                       SS.getWithLocInContext(Context),
   9895                                       IdentLoc, Named, CommonAncestor);
   9896 
   9897     if (IsUsingDirectiveInToplevelContext(CurContext) &&
   9898         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
   9899       Diag(IdentLoc, diag::warn_using_directive_in_header);
   9900     }
   9901 
   9902     PushUsingDirective(S, UDir);
   9903   } else {
   9904     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
   9905   }
   9906 
   9907   if (UDir)
   9908     ProcessDeclAttributeList(S, UDir, AttrList);
   9909 
   9910   return UDir;
   9911 }
   9912 
   9913 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
   9914   // If the scope has an associated entity and the using directive is at
   9915   // namespace or translation unit scope, add the UsingDirectiveDecl into
   9916   // its lookup structure so qualified name lookup can find it.
   9917   DeclContext *Ctx = S->getEntity();
   9918   if (Ctx && !Ctx->isFunctionOrMethod())
   9919     Ctx->addDecl(UDir);
   9920   else
   9921     // Otherwise, it is at block scope. The using-directives will affect lookup
   9922     // only to the end of the scope.
   9923     S->PushUsingDirective(UDir);
   9924 }
   9925 
   9926 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
   9927                                   SourceLocation UsingLoc,
   9928                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
   9929                                   UnqualifiedId &Name,
   9930                                   SourceLocation EllipsisLoc,
   9931                                   const ParsedAttributesView &AttrList) {
   9932   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
   9933 
   9934   if (SS.isEmpty()) {
   9935     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
   9936     return nullptr;
   9937   }
   9938 
   9939   switch (Name.getKind()) {
   9940   case UnqualifiedIdKind::IK_ImplicitSelfParam:
   9941   case UnqualifiedIdKind::IK_Identifier:
   9942   case UnqualifiedIdKind::IK_OperatorFunctionId:
   9943   case UnqualifiedIdKind::IK_LiteralOperatorId:
   9944   case UnqualifiedIdKind::IK_ConversionFunctionId:
   9945     break;
   9946 
   9947   case UnqualifiedIdKind::IK_ConstructorName:
   9948   case UnqualifiedIdKind::IK_ConstructorTemplateId:
   9949     // C++11 inheriting constructors.
   9950     Diag(Name.getBeginLoc(),
   9951          getLangOpts().CPlusPlus11
   9952              ? diag::warn_cxx98_compat_using_decl_constructor
   9953              : diag::err_using_decl_constructor)
   9954         << SS.getRange();
   9955 
   9956     if (getLangOpts().CPlusPlus11) break;
   9957 
   9958     return nullptr;
   9959 
   9960   case UnqualifiedIdKind::IK_DestructorName:
   9961     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
   9962     return nullptr;
   9963 
   9964   case UnqualifiedIdKind::IK_TemplateId:
   9965     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
   9966         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
   9967     return nullptr;
   9968 
   9969   case UnqualifiedIdKind::IK_DeductionGuideName:
   9970     llvm_unreachable("cannot parse qualified deduction guide name");
   9971   }
   9972 
   9973   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
   9974   DeclarationName TargetName = TargetNameInfo.getName();
   9975   if (!TargetName)
   9976     return nullptr;
   9977 
   9978   // Warn about access declarations.
   9979   if (UsingLoc.isInvalid()) {
   9980     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
   9981                                  ? diag::err_access_decl
   9982                                  : diag::warn_access_decl_deprecated)
   9983         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
   9984   }
   9985 
   9986   if (EllipsisLoc.isInvalid()) {
   9987     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
   9988         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
   9989       return nullptr;
   9990   } else {
   9991     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
   9992         !TargetNameInfo.containsUnexpandedParameterPack()) {
   9993       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
   9994         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
   9995       EllipsisLoc = SourceLocation();
   9996     }
   9997   }
   9998 
   9999   NamedDecl *UD =
   10000       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
   10001                             SS, TargetNameInfo, EllipsisLoc, AttrList,
   10002                             /*IsInstantiation*/false);
   10003   if (UD)
   10004     PushOnScopeChains(UD, S, /*AddToContext*/ false);
   10005 
   10006   return UD;
   10007 }
   10008 
   10009 /// Determine whether a using declaration considers the given
   10010 /// declarations as "equivalent", e.g., if they are redeclarations of
   10011 /// the same entity or are both typedefs of the same type.
   10012 static bool
   10013 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
   10014   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
   10015     return true;
   10016 
   10017   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
   10018     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
   10019       return Context.hasSameType(TD1->getUnderlyingType(),
   10020                                  TD2->getUnderlyingType());
   10021 
   10022   return false;
   10023 }
   10024 
   10025 
   10026 /// Determines whether to create a using shadow decl for a particular
   10027 /// decl, given the set of decls existing prior to this using lookup.
   10028 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
   10029                                 const LookupResult &Previous,
   10030                                 UsingShadowDecl *&PrevShadow) {
   10031   // Diagnose finding a decl which is not from a base class of the
   10032   // current class.  We do this now because there are cases where this
   10033   // function will silently decide not to build a shadow decl, which
   10034   // will pre-empt further diagnostics.
   10035   //
   10036   // We don't need to do this in C++11 because we do the check once on
   10037   // the qualifier.
   10038   //
   10039   // FIXME: diagnose the following if we care enough:
   10040   //   struct A { int foo; };
   10041   //   struct B : A { using A::foo; };
   10042   //   template <class T> struct C : A {};
   10043   //   template <class T> struct D : C<T> { using B::foo; } // <---
   10044   // This is invalid (during instantiation) in C++03 because B::foo
   10045   // resolves to the using decl in B, which is not a base class of D<T>.
   10046   // We can't diagnose it immediately because C<T> is an unknown
   10047   // specialization.  The UsingShadowDecl in D<T> then points directly
   10048   // to A::foo, which will look well-formed when we instantiate.
   10049   // The right solution is to not collapse the shadow-decl chain.
   10050   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
   10051     DeclContext *OrigDC = Orig->getDeclContext();
   10052 
   10053     // Handle enums and anonymous structs.
   10054     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
   10055     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
   10056     while (OrigRec->isAnonymousStructOrUnion())
   10057       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
   10058 
   10059     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
   10060       if (OrigDC == CurContext) {
   10061         Diag(Using->getLocation(),
   10062              diag::err_using_decl_nested_name_specifier_is_current_class)
   10063           << Using->getQualifierLoc().getSourceRange();
   10064         Diag(Orig->getLocation(), diag::note_using_decl_target);
   10065         Using->setInvalidDecl();
   10066         return true;
   10067       }
   10068 
   10069       Diag(Using->getQualifierLoc().getBeginLoc(),
   10070            diag::err_using_decl_nested_name_specifier_is_not_base_class)
   10071         << Using->getQualifier()
   10072         << cast<CXXRecordDecl>(CurContext)
   10073         << Using->getQualifierLoc().getSourceRange();
   10074       Diag(Orig->getLocation(), diag::note_using_decl_target);
   10075       Using->setInvalidDecl();
   10076       return true;
   10077     }
   10078   }
   10079 
   10080   if (Previous.empty()) return false;
   10081 
   10082   NamedDecl *Target = Orig;
   10083   if (isa<UsingShadowDecl>(Target))
   10084     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
   10085 
   10086   // If the target happens to be one of the previous declarations, we
   10087   // don't have a conflict.
   10088   //
   10089   // FIXME: but we might be increasing its access, in which case we
   10090   // should redeclare it.
   10091   NamedDecl *NonTag = nullptr, *Tag = nullptr;
   10092   bool FoundEquivalentDecl = false;
   10093   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
   10094          I != E; ++I) {
   10095     NamedDecl *D = (*I)->getUnderlyingDecl();
   10096     // We can have UsingDecls in our Previous results because we use the same
   10097     // LookupResult for checking whether the UsingDecl itself is a valid
   10098     // redeclaration.
   10099     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
   10100       continue;
   10101 
   10102     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
   10103       // C++ [class.mem]p19:
   10104       //   If T is the name of a class, then [every named member other than
   10105       //   a non-static data member] shall have a name different from T
   10106       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
   10107           !isa<IndirectFieldDecl>(Target) &&
   10108           !isa<UnresolvedUsingValueDecl>(Target) &&
   10109           DiagnoseClassNameShadow(
   10110               CurContext,
   10111               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
   10112         return true;
   10113     }
   10114 
   10115     if (IsEquivalentForUsingDecl(Context, D, Target)) {
   10116       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
   10117         PrevShadow = Shadow;
   10118       FoundEquivalentDecl = true;
   10119     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
   10120       // We don't conflict with an existing using shadow decl of an equivalent
   10121       // declaration, but we're not a redeclaration of it.
   10122       FoundEquivalentDecl = true;
   10123     }
   10124 
   10125     if (isVisible(D))
   10126       (isa<TagDecl>(D) ? Tag : NonTag) = D;
   10127   }
   10128 
   10129   if (FoundEquivalentDecl)
   10130     return false;
   10131 
   10132   if (FunctionDecl *FD = Target->getAsFunction()) {
   10133     NamedDecl *OldDecl = nullptr;
   10134     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
   10135                           /*IsForUsingDecl*/ true)) {
   10136     case Ovl_Overload:
   10137       return false;
   10138 
   10139     case Ovl_NonFunction:
   10140       Diag(Using->getLocation(), diag::err_using_decl_conflict);
   10141       break;
   10142 
   10143     // We found a decl with the exact signature.
   10144     case Ovl_Match:
   10145       // If we're in a record, we want to hide the target, so we
   10146       // return true (without a diagnostic) to tell the caller not to
   10147       // build a shadow decl.
   10148       if (CurContext->isRecord())
   10149         return true;
   10150 
   10151       // If we're not in a record, this is an error.
   10152       Diag(Using->getLocation(), diag::err_using_decl_conflict);
   10153       break;
   10154     }
   10155 
   10156     Diag(Target->getLocation(), diag::note_using_decl_target);
   10157     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
   10158     Using->setInvalidDecl();
   10159     return true;
   10160   }
   10161 
   10162   // Target is not a function.
   10163 
   10164   if (isa<TagDecl>(Target)) {
   10165     // No conflict between a tag and a non-tag.
   10166     if (!Tag) return false;
   10167 
   10168     Diag(Using->getLocation(), diag::err_using_decl_conflict);
   10169     Diag(Target->getLocation(), diag::note_using_decl_target);
   10170     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
   10171     Using->setInvalidDecl();
   10172     return true;
   10173   }
   10174 
   10175   // No conflict between a tag and a non-tag.
   10176   if (!NonTag) return false;
   10177 
   10178   Diag(Using->getLocation(), diag::err_using_decl_conflict);
   10179   Diag(Target->getLocation(), diag::note_using_decl_target);
   10180   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
   10181   Using->setInvalidDecl();
   10182   return true;
   10183 }
   10184 
   10185 /// Determine whether a direct base class is a virtual base class.
   10186 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
   10187   if (!Derived->getNumVBases())
   10188     return false;
   10189   for (auto &B : Derived->bases())
   10190     if (B.getType()->getAsCXXRecordDecl() == Base)
   10191       return B.isVirtual();
   10192   llvm_unreachable("not a direct base class");
   10193 }
   10194 
   10195 /// Builds a shadow declaration corresponding to a 'using' declaration.
   10196 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
   10197                                             UsingDecl *UD,
   10198                                             NamedDecl *Orig,
   10199                                             UsingShadowDecl *PrevDecl) {
   10200   // If we resolved to another shadow declaration, just coalesce them.
   10201   NamedDecl *Target = Orig;
   10202   if (isa<UsingShadowDecl>(Target)) {
   10203     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
   10204     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
   10205   }
   10206 
   10207   NamedDecl *NonTemplateTarget = Target;
   10208   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
   10209     NonTemplateTarget = TargetTD->getTemplatedDecl();
   10210 
   10211   UsingShadowDecl *Shadow;
   10212   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
   10213     bool IsVirtualBase =
   10214         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
   10215                             UD->getQualifier()->getAsRecordDecl());
   10216     Shadow = ConstructorUsingShadowDecl::Create(
   10217         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
   10218   } else {
   10219     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
   10220                                      Target);
   10221   }
   10222   UD->addShadowDecl(Shadow);
   10223 
   10224   Shadow->setAccess(UD->getAccess());
   10225   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
   10226     Shadow->setInvalidDecl();
   10227 
   10228   Shadow->setPreviousDecl(PrevDecl);
   10229 
   10230   if (S)
   10231     PushOnScopeChains(Shadow, S);
   10232   else
   10233     CurContext->addDecl(Shadow);
   10234 
   10235 
   10236   return Shadow;
   10237 }
   10238 
   10239 /// Hides a using shadow declaration.  This is required by the current
   10240 /// using-decl implementation when a resolvable using declaration in a
   10241 /// class is followed by a declaration which would hide or override
   10242 /// one or more of the using decl's targets; for example:
   10243 ///
   10244 ///   struct Base { void foo(int); };
   10245 ///   struct Derived : Base {
   10246 ///     using Base::foo;
   10247 ///     void foo(int);
   10248 ///   };
   10249 ///
   10250 /// The governing language is C++03 [namespace.udecl]p12:
   10251 ///
   10252 ///   When a using-declaration brings names from a base class into a
   10253 ///   derived class scope, member functions in the derived class
   10254 ///   override and/or hide member functions with the same name and
   10255 ///   parameter types in a base class (rather than conflicting).
   10256 ///
   10257 /// There are two ways to implement this:
   10258 ///   (1) optimistically create shadow decls when they're not hidden
   10259 ///       by existing declarations, or
   10260 ///   (2) don't create any shadow decls (or at least don't make them
   10261 ///       visible) until we've fully parsed/instantiated the class.
   10262 /// The problem with (1) is that we might have to retroactively remove
   10263 /// a shadow decl, which requires several O(n) operations because the
   10264 /// decl structures are (very reasonably) not designed for removal.
   10265 /// (2) avoids this but is very fiddly and phase-dependent.
   10266 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
   10267   if (Shadow->getDeclName().getNameKind() ==
   10268         DeclarationName::CXXConversionFunctionName)
   10269     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
   10270 
   10271   // Remove it from the DeclContext...
   10272   Shadow->getDeclContext()->removeDecl(Shadow);
   10273 
   10274   // ...and the scope, if applicable...
   10275   if (S) {
   10276     S->RemoveDecl(Shadow);
   10277     IdResolver.RemoveDecl(Shadow);
   10278   }
   10279 
   10280   // ...and the using decl.
   10281   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
   10282 
   10283   // TODO: complain somehow if Shadow was used.  It shouldn't
   10284   // be possible for this to happen, because...?
   10285 }
   10286 
   10287 /// Find the base specifier for a base class with the given type.
   10288 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
   10289                                                 QualType DesiredBase,
   10290                                                 bool &AnyDependentBases) {
   10291   // Check whether the named type is a direct base class.
   10292   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
   10293     .getUnqualifiedType();
   10294   for (auto &Base : Derived->bases()) {
   10295     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
   10296     if (CanonicalDesiredBase == BaseType)
   10297       return &Base;
   10298     if (BaseType->isDependentType())
   10299       AnyDependentBases = true;
   10300   }
   10301   return nullptr;
   10302 }
   10303 
   10304 namespace {
   10305 class UsingValidatorCCC final : public CorrectionCandidateCallback {
   10306 public:
   10307   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
   10308                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
   10309       : HasTypenameKeyword(HasTypenameKeyword),
   10310         IsInstantiation(IsInstantiation), OldNNS(NNS),
   10311         RequireMemberOf(RequireMemberOf) {}
   10312 
   10313   bool ValidateCandidate(const TypoCorrection &Candidate) override {
   10314     NamedDecl *ND = Candidate.getCorrectionDecl();
   10315 
   10316     // Keywords are not valid here.
   10317     if (!ND || isa<NamespaceDecl>(ND))
   10318       return false;
   10319 
   10320     // Completely unqualified names are invalid for a 'using' declaration.
   10321     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
   10322       return false;
   10323 
   10324     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
   10325     // reject.
   10326 
   10327     if (RequireMemberOf) {
   10328       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
   10329       if (FoundRecord && FoundRecord->isInjectedClassName()) {
   10330         // No-one ever wants a using-declaration to name an injected-class-name
   10331         // of a base class, unless they're declaring an inheriting constructor.
   10332         ASTContext &Ctx = ND->getASTContext();
   10333         if (!Ctx.getLangOpts().CPlusPlus11)
   10334           return false;
   10335         QualType FoundType = Ctx.getRecordType(FoundRecord);
   10336 
   10337         // Check that the injected-class-name is named as a member of its own
   10338         // type; we don't want to suggest 'using Derived::Base;', since that
   10339         // means something else.
   10340         NestedNameSpecifier *Specifier =
   10341             Candidate.WillReplaceSpecifier()
   10342                 ? Candidate.getCorrectionSpecifier()
   10343                 : OldNNS;
   10344         if (!Specifier->getAsType() ||
   10345             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
   10346           return false;
   10347 
   10348         // Check that this inheriting constructor declaration actually names a
   10349         // direct base class of the current class.
   10350         bool AnyDependentBases = false;
   10351         if (!findDirectBaseWithType(RequireMemberOf,
   10352                                     Ctx.getRecordType(FoundRecord),
   10353                                     AnyDependentBases) &&
   10354             !AnyDependentBases)
   10355           return false;
   10356       } else {
   10357         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
   10358         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
   10359           return false;
   10360 
   10361         // FIXME: Check that the base class member is accessible?
   10362       }
   10363     } else {
   10364       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
   10365       if (FoundRecord && FoundRecord->isInjectedClassName())
   10366         return false;
   10367     }
   10368 
   10369     if (isa<TypeDecl>(ND))
   10370       return HasTypenameKeyword || !IsInstantiation;
   10371 
   10372     return !HasTypenameKeyword;
   10373   }
   10374 
   10375   std::unique_ptr<CorrectionCandidateCallback> clone() override {
   10376     return std::make_unique<UsingValidatorCCC>(*this);
   10377   }
   10378 
   10379 private:
   10380   bool HasTypenameKeyword;
   10381   bool IsInstantiation;
   10382   NestedNameSpecifier *OldNNS;
   10383   CXXRecordDecl *RequireMemberOf;
   10384 };
   10385 } // end anonymous namespace
   10386 
   10387 /// Builds a using declaration.
   10388 ///
   10389 /// \param IsInstantiation - Whether this call arises from an
   10390 ///   instantiation of an unresolved using declaration.  We treat
   10391 ///   the lookup differently for these declarations.
   10392 NamedDecl *Sema::BuildUsingDeclaration(
   10393     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
   10394     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
   10395     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
   10396     const ParsedAttributesView &AttrList, bool IsInstantiation) {
   10397   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
   10398   SourceLocation IdentLoc = NameInfo.getLoc();
   10399   assert(IdentLoc.isValid() && "Invalid TargetName location.");
   10400 
   10401   // FIXME: We ignore attributes for now.
   10402 
   10403   // For an inheriting constructor declaration, the name of the using
   10404   // declaration is the name of a constructor in this class, not in the
   10405   // base class.
   10406   DeclarationNameInfo UsingName = NameInfo;
   10407   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
   10408     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
   10409       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
   10410           Context.getCanonicalType(Context.getRecordType(RD))));
   10411 
   10412   // Do the redeclaration lookup in the current scope.
   10413   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
   10414                         ForVisibleRedeclaration);
   10415   Previous.setHideTags(false);
   10416   if (S) {
   10417     LookupName(Previous, S);
   10418 
   10419     // It is really dumb that we have to do this.
   10420     LookupResult::Filter F = Previous.makeFilter();
   10421     while (F.hasNext()) {
   10422       NamedDecl *D = F.next();
   10423       if (!isDeclInScope(D, CurContext, S))
   10424         F.erase();
   10425       // If we found a local extern declaration that's not ordinarily visible,
   10426       // and this declaration is being added to a non-block scope, ignore it.
   10427       // We're only checking for scope conflicts here, not also for violations
   10428       // of the linkage rules.
   10429       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
   10430                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
   10431         F.erase();
   10432     }
   10433     F.done();
   10434   } else {
   10435     assert(IsInstantiation && "no scope in non-instantiation");
   10436     if (CurContext->isRecord())
   10437       LookupQualifiedName(Previous, CurContext);
   10438     else {
   10439       // No redeclaration check is needed here; in non-member contexts we
   10440       // diagnosed all possible conflicts with other using-declarations when
   10441       // building the template:
   10442       //
   10443       // For a dependent non-type using declaration, the only valid case is
   10444       // if we instantiate to a single enumerator. We check for conflicts
   10445       // between shadow declarations we introduce, and we check in the template
   10446       // definition for conflicts between a non-type using declaration and any
   10447       // other declaration, which together covers all cases.
   10448       //
   10449       // A dependent typename using declaration will never successfully
   10450       // instantiate, since it will always name a class member, so we reject
   10451       // that in the template definition.
   10452     }
   10453   }
   10454 
   10455   // Check for invalid redeclarations.
   10456   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
   10457                                   SS, IdentLoc, Previous))
   10458     return nullptr;
   10459 
   10460   // Check for bad qualifiers.
   10461   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
   10462                               IdentLoc))
   10463     return nullptr;
   10464 
   10465   DeclContext *LookupContext = computeDeclContext(SS);
   10466   NamedDecl *D;
   10467   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
   10468   if (!LookupContext || EllipsisLoc.isValid()) {
   10469     if (HasTypenameKeyword) {
   10470       // FIXME: not all declaration name kinds are legal here
   10471       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
   10472                                               UsingLoc, TypenameLoc,
   10473                                               QualifierLoc,
   10474                                               IdentLoc, NameInfo.getName(),
   10475                                               EllipsisLoc);
   10476     } else {
   10477       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
   10478                                            QualifierLoc, NameInfo, EllipsisLoc);
   10479     }
   10480     D->setAccess(AS);
   10481     CurContext->addDecl(D);
   10482     return D;
   10483   }
   10484 
   10485   auto Build = [&](bool Invalid) {
   10486     UsingDecl *UD =
   10487         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
   10488                           UsingName, HasTypenameKeyword);
   10489     UD->setAccess(AS);
   10490     CurContext->addDecl(UD);
   10491     UD->setInvalidDecl(Invalid);
   10492     return UD;
   10493   };
   10494   auto BuildInvalid = [&]{ return Build(true); };
   10495   auto BuildValid = [&]{ return Build(false); };
   10496 
   10497   if (RequireCompleteDeclContext(SS, LookupContext))
   10498     return BuildInvalid();
   10499 
   10500   // Look up the target name.
   10501   LookupResult R(*this, NameInfo, LookupOrdinaryName);
   10502 
   10503   // Unlike most lookups, we don't always want to hide tag
   10504   // declarations: tag names are visible through the using declaration
   10505   // even if hidden by ordinary names, *except* in a dependent context
   10506   // where it's important for the sanity of two-phase lookup.
   10507   if (!IsInstantiation)
   10508     R.setHideTags(false);
   10509 
   10510   // For the purposes of this lookup, we have a base object type
   10511   // equal to that of the current context.
   10512   if (CurContext->isRecord()) {
   10513     R.setBaseObjectType(
   10514                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
   10515   }
   10516 
   10517   LookupQualifiedName(R, LookupContext);
   10518 
   10519   // Try to correct typos if possible. If constructor name lookup finds no
   10520   // results, that means the named class has no explicit constructors, and we
   10521   // suppressed declaring implicit ones (probably because it's dependent or
   10522   // invalid).
   10523   if (R.empty() &&
   10524       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
   10525     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
   10526     // it will believe that glibc provides a ::gets in cases where it does not,
   10527     // and will try to pull it into namespace std with a using-declaration.
   10528     // Just ignore the using-declaration in that case.
   10529     auto *II = NameInfo.getName().getAsIdentifierInfo();
   10530     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
   10531         CurContext->isStdNamespace() &&
   10532         isa<TranslationUnitDecl>(LookupContext) &&
   10533         getSourceManager().isInSystemHeader(UsingLoc))
   10534       return nullptr;
   10535     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
   10536                           dyn_cast<CXXRecordDecl>(CurContext));
   10537     if (TypoCorrection Corrected =
   10538             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
   10539                         CTK_ErrorRecovery)) {
   10540       // We reject candidates where DroppedSpecifier == true, hence the
   10541       // literal '0' below.
   10542       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
   10543                                 << NameInfo.getName() << LookupContext << 0
   10544                                 << SS.getRange());
   10545 
   10546       // If we picked a correction with no attached Decl we can't do anything
   10547       // useful with it, bail out.
   10548       NamedDecl *ND = Corrected.getCorrectionDecl();
   10549       if (!ND)
   10550         return BuildInvalid();
   10551 
   10552       // If we corrected to an inheriting constructor, handle it as one.
   10553       auto *RD = dyn_cast<CXXRecordDecl>(ND);
   10554       if (RD && RD->isInjectedClassName()) {
   10555         // The parent of the injected class name is the class itself.
   10556         RD = cast<CXXRecordDecl>(RD->getParent());
   10557 
   10558         // Fix up the information we'll use to build the using declaration.
   10559         if (Corrected.WillReplaceSpecifier()) {
   10560           NestedNameSpecifierLocBuilder Builder;
   10561           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
   10562                               QualifierLoc.getSourceRange());
   10563           QualifierLoc = Builder.getWithLocInContext(Context);
   10564         }
   10565 
   10566         // In this case, the name we introduce is the name of a derived class
   10567         // constructor.
   10568         auto *CurClass = cast<CXXRecordDecl>(CurContext);
   10569         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
   10570             Context.getCanonicalType(Context.getRecordType(CurClass))));
   10571         UsingName.setNamedTypeInfo(nullptr);
   10572         for (auto *Ctor : LookupConstructors(RD))
   10573           R.addDecl(Ctor);
   10574         R.resolveKind();
   10575       } else {
   10576         // FIXME: Pick up all the declarations if we found an overloaded
   10577         // function.
   10578         UsingName.setName(ND->getDeclName());
   10579         R.addDecl(ND);
   10580       }
   10581     } else {
   10582       Diag(IdentLoc, diag::err_no_member)
   10583         << NameInfo.getName() << LookupContext << SS.getRange();
   10584       return BuildInvalid();
   10585     }
   10586   }
   10587 
   10588   if (R.isAmbiguous())
   10589     return BuildInvalid();
   10590 
   10591   if (HasTypenameKeyword) {
   10592     // If we asked for a typename and got a non-type decl, error out.
   10593     if (!R.getAsSingle<TypeDecl>()) {
   10594       Diag(IdentLoc, diag::err_using_typename_non_type);
   10595       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
   10596         Diag((*I)->getUnderlyingDecl()->getLocation(),
   10597              diag::note_using_decl_target);
   10598       return BuildInvalid();
   10599     }
   10600   } else {
   10601     // If we asked for a non-typename and we got a type, error out,
   10602     // but only if this is an instantiation of an unresolved using
   10603     // decl.  Otherwise just silently find the type name.
   10604     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
   10605       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
   10606       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
   10607       return BuildInvalid();
   10608     }
   10609   }
   10610 
   10611   // C++14 [namespace.udecl]p6:
   10612   // A using-declaration shall not name a namespace.
   10613   if (R.getAsSingle<NamespaceDecl>()) {
   10614     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
   10615       << SS.getRange();
   10616     return BuildInvalid();
   10617   }
   10618 
   10619   // C++14 [namespace.udecl]p7:
   10620   // A using-declaration shall not name a scoped enumerator.
   10621   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
   10622     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
   10623       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
   10624         << SS.getRange();
   10625       return BuildInvalid();
   10626     }
   10627   }
   10628 
   10629   UsingDecl *UD = BuildValid();
   10630 
   10631   // Some additional rules apply to inheriting constructors.
   10632   if (UsingName.getName().getNameKind() ==
   10633         DeclarationName::CXXConstructorName) {
   10634     // Suppress access diagnostics; the access check is instead performed at the
   10635     // point of use for an inheriting constructor.
   10636     R.suppressDiagnostics();
   10637     if (CheckInheritingConstructorUsingDecl(UD))
   10638       return UD;
   10639   }
   10640 
   10641   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
   10642     UsingShadowDecl *PrevDecl = nullptr;
   10643     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
   10644       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
   10645   }
   10646 
   10647   return UD;
   10648 }
   10649 
   10650 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
   10651                                     ArrayRef<NamedDecl *> Expansions) {
   10652   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
   10653          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
   10654          isa<UsingPackDecl>(InstantiatedFrom));
   10655 
   10656   auto *UPD =
   10657       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
   10658   UPD->setAccess(InstantiatedFrom->getAccess());
   10659   CurContext->addDecl(UPD);
   10660   return UPD;
   10661 }
   10662 
   10663 /// Additional checks for a using declaration referring to a constructor name.
   10664 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
   10665   assert(!UD->hasTypename() && "expecting a constructor name");
   10666 
   10667   const Type *SourceType = UD->getQualifier()->getAsType();
   10668   assert(SourceType &&
   10669          "Using decl naming constructor doesn't have type in scope spec.");
   10670   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
   10671 
   10672   // Check whether the named type is a direct base class.
   10673   bool AnyDependentBases = false;
   10674   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
   10675                                       AnyDependentBases);
   10676   if (!Base && !AnyDependentBases) {
   10677     Diag(UD->getUsingLoc(),
   10678          diag::err_using_decl_constructor_not_in_direct_base)
   10679       << UD->getNameInfo().getSourceRange()
   10680       << QualType(SourceType, 0) << TargetClass;
   10681     UD->setInvalidDecl();
   10682     return true;
   10683   }
   10684 
   10685   if (Base)
   10686     Base->setInheritConstructors();
   10687 
   10688   return false;
   10689 }
   10690 
   10691 /// Checks that the given using declaration is not an invalid
   10692 /// redeclaration.  Note that this is checking only for the using decl
   10693 /// itself, not for any ill-formedness among the UsingShadowDecls.
   10694 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
   10695                                        bool HasTypenameKeyword,
   10696                                        const CXXScopeSpec &SS,
   10697                                        SourceLocation NameLoc,
   10698                                        const LookupResult &Prev) {
   10699   NestedNameSpecifier *Qual = SS.getScopeRep();
   10700 
   10701   // C++03 [namespace.udecl]p8:
   10702   // C++0x [namespace.udecl]p10:
   10703   //   A using-declaration is a declaration and can therefore be used
   10704   //   repeatedly where (and only where) multiple declarations are
   10705   //   allowed.
   10706   //
   10707   // That's in non-member contexts.
   10708   if (!CurContext->getRedeclContext()->isRecord()) {
   10709     // A dependent qualifier outside a class can only ever resolve to an
   10710     // enumeration type. Therefore it conflicts with any other non-type
   10711     // declaration in the same scope.
   10712     // FIXME: How should we check for dependent type-type conflicts at block
   10713     // scope?
   10714     if (Qual->isDependent() && !HasTypenameKeyword) {
   10715       for (auto *D : Prev) {
   10716         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
   10717           bool OldCouldBeEnumerator =
   10718               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
   10719           Diag(NameLoc,
   10720                OldCouldBeEnumerator ? diag::err_redefinition
   10721                                     : diag::err_redefinition_different_kind)
   10722               << Prev.getLookupName();
   10723           Diag(D->getLocation(), diag::note_previous_definition);
   10724           return true;
   10725         }
   10726       }
   10727     }
   10728     return false;
   10729   }
   10730 
   10731   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
   10732     NamedDecl *D = *I;
   10733 
   10734     bool DTypename;
   10735     NestedNameSpecifier *DQual;
   10736     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
   10737       DTypename = UD->hasTypename();
   10738       DQual = UD->getQualifier();
   10739     } else if (UnresolvedUsingValueDecl *UD
   10740                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
   10741       DTypename = false;
   10742       DQual = UD->getQualifier();
   10743     } else if (UnresolvedUsingTypenameDecl *UD
   10744                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
   10745       DTypename = true;
   10746       DQual = UD->getQualifier();
   10747     } else continue;
   10748 
   10749     // using decls differ if one says 'typename' and the other doesn't.
   10750     // FIXME: non-dependent using decls?
   10751     if (HasTypenameKeyword != DTypename) continue;
   10752 
   10753     // using decls differ if they name different scopes (but note that
   10754     // template instantiation can cause this check to trigger when it
   10755     // didn't before instantiation).
   10756     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
   10757         Context.getCanonicalNestedNameSpecifier(DQual))
   10758       continue;
   10759 
   10760     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
   10761     Diag(D->getLocation(), diag::note_using_decl) << 1;
   10762     return true;
   10763   }
   10764 
   10765   return false;
   10766 }
   10767 
   10768 
   10769 /// Checks that the given nested-name qualifier used in a using decl
   10770 /// in the current context is appropriately related to the current
   10771 /// scope.  If an error is found, diagnoses it and returns true.
   10772 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
   10773                                    bool HasTypename,
   10774                                    const CXXScopeSpec &SS,
   10775                                    const DeclarationNameInfo &NameInfo,
   10776                                    SourceLocation NameLoc) {
   10777   DeclContext *NamedContext = computeDeclContext(SS);
   10778 
   10779   if (!CurContext->isRecord()) {
   10780     // C++03 [namespace.udecl]p3:
   10781     // C++0x [namespace.udecl]p8:
   10782     //   A using-declaration for a class member shall be a member-declaration.
   10783 
   10784     // If we weren't able to compute a valid scope, it might validly be a
   10785     // dependent class scope or a dependent enumeration unscoped scope. If
   10786     // we have a 'typename' keyword, the scope must resolve to a class type.
   10787     if ((HasTypename && !NamedContext) ||
   10788         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
   10789       auto *RD = NamedContext
   10790                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
   10791                      : nullptr;
   10792       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
   10793         RD = nullptr;
   10794 
   10795       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
   10796         << SS.getRange();
   10797 
   10798       // If we have a complete, non-dependent source type, try to suggest a
   10799       // way to get the same effect.
   10800       if (!RD)
   10801         return true;
   10802 
   10803       // Find what this using-declaration was referring to.
   10804       LookupResult R(*this, NameInfo, LookupOrdinaryName);
   10805       R.setHideTags(false);
   10806       R.suppressDiagnostics();
   10807       LookupQualifiedName(R, RD);
   10808 
   10809       if (R.getAsSingle<TypeDecl>()) {
   10810         if (getLangOpts().CPlusPlus11) {
   10811           // Convert 'using X::Y;' to 'using Y = X::Y;'.
   10812           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
   10813             << 0 // alias declaration
   10814             << FixItHint::CreateInsertion(SS.getBeginLoc(),
   10815                                           NameInfo.getName().getAsString() +
   10816                                               " = ");
   10817         } else {
   10818           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
   10819           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
   10820           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
   10821             << 1 // typedef declaration
   10822             << FixItHint::CreateReplacement(UsingLoc, "typedef")
   10823             << FixItHint::CreateInsertion(
   10824                    InsertLoc, " " + NameInfo.getName().getAsString());
   10825         }
   10826       } else if (R.getAsSingle<VarDecl>()) {
   10827         // Don't provide a fixit outside C++11 mode; we don't want to suggest
   10828         // repeating the type of the static data member here.
   10829         FixItHint FixIt;
   10830         if (getLangOpts().CPlusPlus11) {
   10831           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
   10832           FixIt = FixItHint::CreateReplacement(
   10833               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
   10834         }
   10835 
   10836         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
   10837           << 2 // reference declaration
   10838           << FixIt;
   10839       } else if (R.getAsSingle<EnumConstantDecl>()) {
   10840         // Don't provide a fixit outside C++11 mode; we don't want to suggest
   10841         // repeating the type of the enumeration here, and we can't do so if
   10842         // the type is anonymous.
   10843         FixItHint FixIt;
   10844         if (getLangOpts().CPlusPlus11) {
   10845           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
   10846           FixIt = FixItHint::CreateReplacement(
   10847               UsingLoc,
   10848               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
   10849         }
   10850 
   10851         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
   10852           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
   10853           << FixIt;
   10854       }
   10855       return true;
   10856     }
   10857 
   10858     // Otherwise, this might be valid.
   10859     return false;
   10860   }
   10861 
   10862   // The current scope is a record.
   10863 
   10864   // If the named context is dependent, we can't decide much.
   10865   if (!NamedContext) {
   10866     // FIXME: in C++0x, we can diagnose if we can prove that the
   10867     // nested-name-specifier does not refer to a base class, which is
   10868     // still possible in some cases.
   10869 
   10870     // Otherwise we have to conservatively report that things might be
   10871     // okay.
   10872     return false;
   10873   }
   10874 
   10875   if (!NamedContext->isRecord()) {
   10876     // Ideally this would point at the last name in the specifier,
   10877     // but we don't have that level of source info.
   10878     Diag(SS.getRange().getBegin(),
   10879          diag::err_using_decl_nested_name_specifier_is_not_class)
   10880       << SS.getScopeRep() << SS.getRange();
   10881     return true;
   10882   }
   10883 
   10884   if (!NamedContext->isDependentContext() &&
   10885       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
   10886     return true;
   10887 
   10888   if (getLangOpts().CPlusPlus11) {
   10889     // C++11 [namespace.udecl]p3:
   10890     //   In a using-declaration used as a member-declaration, the
   10891     //   nested-name-specifier shall name a base class of the class
   10892     //   being defined.
   10893 
   10894     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
   10895                                  cast<CXXRecordDecl>(NamedContext))) {
   10896       if (CurContext == NamedContext) {
   10897         Diag(NameLoc,
   10898              diag::err_using_decl_nested_name_specifier_is_current_class)
   10899           << SS.getRange();
   10900         return true;
   10901       }
   10902 
   10903       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
   10904         Diag(SS.getRange().getBegin(),
   10905              diag::err_using_decl_nested_name_specifier_is_not_base_class)
   10906           << SS.getScopeRep()
   10907           << cast<CXXRecordDecl>(CurContext)
   10908           << SS.getRange();
   10909       }
   10910       return true;
   10911     }
   10912 
   10913     return false;
   10914   }
   10915 
   10916   // C++03 [namespace.udecl]p4:
   10917   //   A using-declaration used as a member-declaration shall refer
   10918   //   to a member of a base class of the class being defined [etc.].
   10919 
   10920   // Salient point: SS doesn't have to name a base class as long as
   10921   // lookup only finds members from base classes.  Therefore we can
   10922   // diagnose here only if we can prove that that can't happen,
   10923   // i.e. if the class hierarchies provably don't intersect.
   10924 
   10925   // TODO: it would be nice if "definitely valid" results were cached
   10926   // in the UsingDecl and UsingShadowDecl so that these checks didn't
   10927   // need to be repeated.
   10928 
   10929   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
   10930   auto Collect = [&Bases](const CXXRecordDecl *Base) {
   10931     Bases.insert(Base);
   10932     return true;
   10933   };
   10934 
   10935   // Collect all bases. Return false if we find a dependent base.
   10936   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
   10937     return false;
   10938 
   10939   // Returns true if the base is dependent or is one of the accumulated base
   10940   // classes.
   10941   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
   10942     return !Bases.count(Base);
   10943   };
   10944 
   10945   // Return false if the class has a dependent base or if it or one
   10946   // of its bases is present in the base set of the current context.
   10947   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
   10948       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
   10949     return false;
   10950 
   10951   Diag(SS.getRange().getBegin(),
   10952        diag::err_using_decl_nested_name_specifier_is_not_base_class)
   10953     << SS.getScopeRep()
   10954     << cast<CXXRecordDecl>(CurContext)
   10955     << SS.getRange();
   10956 
   10957   return true;
   10958 }
   10959 
   10960 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
   10961                                   MultiTemplateParamsArg TemplateParamLists,
   10962                                   SourceLocation UsingLoc, UnqualifiedId &Name,
   10963                                   const ParsedAttributesView &AttrList,
   10964                                   TypeResult Type, Decl *DeclFromDeclSpec) {
   10965   // Skip up to the relevant declaration scope.
   10966   while (S->isTemplateParamScope())
   10967     S = S->getParent();
   10968   assert((S->getFlags() & Scope::DeclScope) &&
   10969          "got alias-declaration outside of declaration scope");
   10970 
   10971   if (Type.isInvalid())
   10972     return nullptr;
   10973 
   10974   bool Invalid = false;
   10975   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
   10976   TypeSourceInfo *TInfo = nullptr;
   10977   GetTypeFromParser(Type.get(), &TInfo);
   10978 
   10979   if (DiagnoseClassNameShadow(CurContext, NameInfo))
   10980     return nullptr;
   10981 
   10982   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
   10983                                       UPPC_DeclarationType)) {
   10984     Invalid = true;
   10985     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
   10986                                              TInfo->getTypeLoc().getBeginLoc());
   10987   }
   10988 
   10989   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
   10990                         TemplateParamLists.size()
   10991                             ? forRedeclarationInCurContext()
   10992                             : ForVisibleRedeclaration);
   10993   LookupName(Previous, S);
   10994 
   10995   // Warn about shadowing the name of a template parameter.
   10996   if (Previous.isSingleResult() &&
   10997       Previous.getFoundDecl()->isTemplateParameter()) {
   10998     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
   10999     Previous.clear();
   11000   }
   11001 
   11002   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
   11003          "name in alias declaration must be an identifier");
   11004   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
   11005                                                Name.StartLocation,
   11006                                                Name.Identifier, TInfo);
   11007 
   11008   NewTD->setAccess(AS);
   11009 
   11010   if (Invalid)
   11011     NewTD->setInvalidDecl();
   11012 
   11013   ProcessDeclAttributeList(S, NewTD, AttrList);
   11014   AddPragmaAttributes(S, NewTD);
   11015 
   11016   CheckTypedefForVariablyModifiedType(S, NewTD);
   11017   Invalid |= NewTD->isInvalidDecl();
   11018 
   11019   bool Redeclaration = false;
   11020 
   11021   NamedDecl *NewND;
   11022   if (TemplateParamLists.size()) {
   11023     TypeAliasTemplateDecl *OldDecl = nullptr;
   11024     TemplateParameterList *OldTemplateParams = nullptr;
   11025 
   11026     if (TemplateParamLists.size() != 1) {
   11027       Diag(UsingLoc, diag::err_alias_template_extra_headers)
   11028         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
   11029          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
   11030     }
   11031     TemplateParameterList *TemplateParams = TemplateParamLists[0];
   11032 
   11033     // Check that we can declare a template here.
   11034     if (CheckTemplateDeclScope(S, TemplateParams))
   11035       return nullptr;
   11036 
   11037     // Only consider previous declarations in the same scope.
   11038     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
   11039                          /*ExplicitInstantiationOrSpecialization*/false);
   11040     if (!Previous.empty()) {
   11041       Redeclaration = true;
   11042 
   11043       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
   11044       if (!OldDecl && !Invalid) {
   11045         Diag(UsingLoc, diag::err_redefinition_different_kind)
   11046           << Name.Identifier;
   11047 
   11048         NamedDecl *OldD = Previous.getRepresentativeDecl();
   11049         if (OldD->getLocation().isValid())
   11050           Diag(OldD->getLocation(), diag::note_previous_definition);
   11051 
   11052         Invalid = true;
   11053       }
   11054 
   11055       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
   11056         if (TemplateParameterListsAreEqual(TemplateParams,
   11057                                            OldDecl->getTemplateParameters(),
   11058                                            /*Complain=*/true,
   11059                                            TPL_TemplateMatch))
   11060           OldTemplateParams =
   11061               OldDecl->getMostRecentDecl()->getTemplateParameters();
   11062         else
   11063           Invalid = true;
   11064 
   11065         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
   11066         if (!Invalid &&
   11067             !Context.hasSameType(OldTD->getUnderlyingType(),
   11068                                  NewTD->getUnderlyingType())) {
   11069           // FIXME: The C++0x standard does not clearly say this is ill-formed,
   11070           // but we can't reasonably accept it.
   11071           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
   11072             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
   11073           if (OldTD->getLocation().isValid())
   11074             Diag(OldTD->getLocation(), diag::note_previous_definition);
   11075           Invalid = true;
   11076         }
   11077       }
   11078     }
   11079 
   11080     // Merge any previous default template arguments into our parameters,
   11081     // and check the parameter list.
   11082     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
   11083                                    TPC_TypeAliasTemplate))
   11084       return nullptr;
   11085 
   11086     TypeAliasTemplateDecl *NewDecl =
   11087       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
   11088                                     Name.Identifier, TemplateParams,
   11089                                     NewTD);
   11090     NewTD->setDescribedAliasTemplate(NewDecl);
   11091 
   11092     NewDecl->setAccess(AS);
   11093 
   11094     if (Invalid)
   11095       NewDecl->setInvalidDecl();
   11096     else if (OldDecl) {
   11097       NewDecl->setPreviousDecl(OldDecl);
   11098       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
   11099     }
   11100 
   11101     NewND = NewDecl;
   11102   } else {
   11103     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
   11104       setTagNameForLinkagePurposes(TD, NewTD);
   11105       handleTagNumbering(TD, S);
   11106     }
   11107     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
   11108     NewND = NewTD;
   11109   }
   11110 
   11111   PushOnScopeChains(NewND, S);
   11112   ActOnDocumentableDecl(NewND);
   11113   return NewND;
   11114 }
   11115 
   11116 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
   11117                                    SourceLocation AliasLoc,
   11118                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
   11119                                    SourceLocation IdentLoc,
   11120                                    IdentifierInfo *Ident) {
   11121 
   11122   // Lookup the namespace name.
   11123   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
   11124   LookupParsedName(R, S, &SS);
   11125 
   11126   if (R.isAmbiguous())
   11127     return nullptr;
   11128 
   11129   if (R.empty()) {
   11130     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
   11131       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
   11132       return nullptr;
   11133     }
   11134   }
   11135   assert(!R.isAmbiguous() && !R.empty());
   11136   NamedDecl *ND = R.getRepresentativeDecl();
   11137 
   11138   // Check if we have a previous declaration with the same name.
   11139   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
   11140                      ForVisibleRedeclaration);
   11141   LookupName(PrevR, S);
   11142 
   11143   // Check we're not shadowing a template parameter.
   11144   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
   11145     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
   11146     PrevR.clear();
   11147   }
   11148 
   11149   // Filter out any other lookup result from an enclosing scope.
   11150   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
   11151                        /*AllowInlineNamespace*/false);
   11152 
   11153   // Find the previous declaration and check that we can redeclare it.
   11154   NamespaceAliasDecl *Prev = nullptr;
   11155   if (PrevR.isSingleResult()) {
   11156     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
   11157     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
   11158       // We already have an alias with the same name that points to the same
   11159       // namespace; check that it matches.
   11160       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
   11161         Prev = AD;
   11162       } else if (isVisible(PrevDecl)) {
   11163         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
   11164           << Alias;
   11165         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
   11166           << AD->getNamespace();
   11167         return nullptr;
   11168       }
   11169     } else if (isVisible(PrevDecl)) {
   11170       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
   11171                             ? diag::err_redefinition
   11172                             : diag::err_redefinition_different_kind;
   11173       Diag(AliasLoc, DiagID) << Alias;
   11174       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   11175       return nullptr;
   11176     }
   11177   }
   11178 
   11179   // The use of a nested name specifier may trigger deprecation warnings.
   11180   DiagnoseUseOfDecl(ND, IdentLoc);
   11181 
   11182   NamespaceAliasDecl *AliasDecl =
   11183     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
   11184                                Alias, SS.getWithLocInContext(Context),
   11185                                IdentLoc, ND);
   11186   if (Prev)
   11187     AliasDecl->setPreviousDecl(Prev);
   11188 
   11189   PushOnScopeChains(AliasDecl, S);
   11190   return AliasDecl;
   11191 }
   11192 
   11193 namespace {
   11194 struct SpecialMemberExceptionSpecInfo
   11195     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
   11196   SourceLocation Loc;
   11197   Sema::ImplicitExceptionSpecification ExceptSpec;
   11198 
   11199   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
   11200                                  Sema::CXXSpecialMember CSM,
   11201                                  Sema::InheritedConstructorInfo *ICI,
   11202                                  SourceLocation Loc)
   11203       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
   11204 
   11205   bool visitBase(CXXBaseSpecifier *Base);
   11206   bool visitField(FieldDecl *FD);
   11207 
   11208   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
   11209                            unsigned Quals);
   11210 
   11211   void visitSubobjectCall(Subobject Subobj,
   11212                           Sema::SpecialMemberOverloadResult SMOR);
   11213 };
   11214 }
   11215 
   11216 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
   11217   auto *RT = Base->getType()->getAs<RecordType>();
   11218   if (!RT)
   11219     return false;
   11220 
   11221   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
   11222   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
   11223   if (auto *BaseCtor = SMOR.getMethod()) {
   11224     visitSubobjectCall(Base, BaseCtor);
   11225     return false;
   11226   }
   11227 
   11228   visitClassSubobject(BaseClass, Base, 0);
   11229   return false;
   11230 }
   11231 
   11232 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
   11233   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
   11234     Expr *E = FD->getInClassInitializer();
   11235     if (!E)
   11236       // FIXME: It's a little wasteful to build and throw away a
   11237       // CXXDefaultInitExpr here.
   11238       // FIXME: We should have a single context note pointing at Loc, and
   11239       // this location should be MD->getLocation() instead, since that's
   11240       // the location where we actually use the default init expression.
   11241       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
   11242     if (E)
   11243       ExceptSpec.CalledExpr(E);
   11244   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
   11245                             ->getAs<RecordType>()) {
   11246     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
   11247                         FD->getType().getCVRQualifiers());
   11248   }
   11249   return false;
   11250 }
   11251 
   11252 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
   11253                                                          Subobject Subobj,
   11254                                                          unsigned Quals) {
   11255   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
   11256   bool IsMutable = Field && Field->isMutable();
   11257   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
   11258 }
   11259 
   11260 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
   11261     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
   11262   // Note, if lookup fails, it doesn't matter what exception specification we
   11263   // choose because the special member will be deleted.
   11264   if (CXXMethodDecl *MD = SMOR.getMethod())
   11265     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
   11266 }
   11267 
   11268 namespace {
   11269 /// RAII object to register a special member as being currently declared.
   11270 struct ComputingExceptionSpec {
   11271   Sema &S;
   11272 
   11273   ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
   11274       : S(S) {
   11275     Sema::CodeSynthesisContext Ctx;
   11276     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
   11277     Ctx.PointOfInstantiation = Loc;
   11278     Ctx.Entity = MD;
   11279     S.pushCodeSynthesisContext(Ctx);
   11280   }
   11281   ~ComputingExceptionSpec() {
   11282     S.popCodeSynthesisContext();
   11283   }
   11284 };
   11285 }
   11286 
   11287 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
   11288   llvm::APSInt Result;
   11289   ExprResult Converted = CheckConvertedConstantExpression(
   11290       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
   11291   ExplicitSpec.setExpr(Converted.get());
   11292   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
   11293     ExplicitSpec.setKind(Result.getBoolValue()
   11294                              ? ExplicitSpecKind::ResolvedTrue
   11295                              : ExplicitSpecKind::ResolvedFalse);
   11296     return true;
   11297   }
   11298   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
   11299   return false;
   11300 }
   11301 
   11302 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
   11303   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
   11304   if (!ExplicitExpr->isTypeDependent())
   11305     tryResolveExplicitSpecifier(ES);
   11306   return ES;
   11307 }
   11308 
   11309 static Sema::ImplicitExceptionSpecification
   11310 ComputeDefaultedSpecialMemberExceptionSpec(
   11311     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
   11312     Sema::InheritedConstructorInfo *ICI) {
   11313   ComputingExceptionSpec CES(S, MD, Loc);
   11314 
   11315   CXXRecordDecl *ClassDecl = MD->getParent();
   11316 
   11317   // C++ [except.spec]p14:
   11318   //   An implicitly declared special member function (Clause 12) shall have an
   11319   //   exception-specification. [...]
   11320   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
   11321   if (ClassDecl->isInvalidDecl())
   11322     return Info.ExceptSpec;
   11323 
   11324   // FIXME: If this diagnostic fires, we're probably missing a check for
   11325   // attempting to resolve an exception specification before it's known
   11326   // at a higher level.
   11327   if (S.RequireCompleteType(MD->getLocation(),
   11328                             S.Context.getRecordType(ClassDecl),
   11329                             diag::err_exception_spec_incomplete_type))
   11330     return Info.ExceptSpec;
   11331 
   11332   // C++1z [except.spec]p7:
   11333   //   [Look for exceptions thrown by] a constructor selected [...] to
   11334   //   initialize a potentially constructed subobject,
   11335   // C++1z [except.spec]p8:
   11336   //   The exception specification for an implicitly-declared destructor, or a
   11337   //   destructor without a noexcept-specifier, is potentially-throwing if and
   11338   //   only if any of the destructors for any of its potentially constructed
   11339   //   subojects is potentially throwing.
   11340   // FIXME: We respect the first rule but ignore the "potentially constructed"
   11341   // in the second rule to resolve a core issue (no number yet) that would have
   11342   // us reject:
   11343   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
   11344   //   struct B : A {};
   11345   //   struct C : B { void f(); };
   11346   // ... due to giving B::~B() a non-throwing exception specification.
   11347   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
   11348                                 : Info.VisitAllBases);
   11349 
   11350   return Info.ExceptSpec;
   11351 }
   11352 
   11353 namespace {
   11354 /// RAII object to register a special member as being currently declared.
   11355 struct DeclaringSpecialMember {
   11356   Sema &S;
   11357   Sema::SpecialMemberDecl D;
   11358   Sema::ContextRAII SavedContext;
   11359   bool WasAlreadyBeingDeclared;
   11360 
   11361   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
   11362       : S(S), D(RD, CSM), SavedContext(S, RD) {
   11363     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
   11364     if (WasAlreadyBeingDeclared)
   11365       // This almost never happens, but if it does, ensure that our cache
   11366       // doesn't contain a stale result.
   11367       S.SpecialMemberCache.clear();
   11368     else {
   11369       // Register a note to be produced if we encounter an error while
   11370       // declaring the special member.
   11371       Sema::CodeSynthesisContext Ctx;
   11372       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
   11373       // FIXME: We don't have a location to use here. Using the class's
   11374       // location maintains the fiction that we declare all special members
   11375       // with the class, but (1) it's not clear that lying about that helps our
   11376       // users understand what's going on, and (2) there may be outer contexts
   11377       // on the stack (some of which are relevant) and printing them exposes
   11378       // our lies.
   11379       Ctx.PointOfInstantiation = RD->getLocation();
   11380       Ctx.Entity = RD;
   11381       Ctx.SpecialMember = CSM;
   11382       S.pushCodeSynthesisContext(Ctx);
   11383     }
   11384   }
   11385   ~DeclaringSpecialMember() {
   11386     if (!WasAlreadyBeingDeclared) {
   11387       S.SpecialMembersBeingDeclared.erase(D);
   11388       S.popCodeSynthesisContext();
   11389     }
   11390   }
   11391 
   11392   /// Are we already trying to declare this special member?
   11393   bool isAlreadyBeingDeclared() const {
   11394     return WasAlreadyBeingDeclared;
   11395   }
   11396 };
   11397 }
   11398 
   11399 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
   11400   // Look up any existing declarations, but don't trigger declaration of all
   11401   // implicit special members with this name.
   11402   DeclarationName Name = FD->getDeclName();
   11403   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
   11404                  ForExternalRedeclaration);
   11405   for (auto *D : FD->getParent()->lookup(Name))
   11406     if (auto *Acceptable = R.getAcceptableDecl(D))
   11407       R.addDecl(Acceptable);
   11408   R.resolveKind();
   11409   R.suppressDiagnostics();
   11410 
   11411   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
   11412 }
   11413 
   11414 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
   11415                                           QualType ResultTy,
   11416                                           ArrayRef<QualType> Args) {
   11417   // Build an exception specification pointing back at this constructor.
   11418   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
   11419 
   11420   if (getLangOpts().OpenCLCPlusPlus) {
   11421     // OpenCL: Implicitly defaulted special member are of the generic address
   11422     // space.
   11423     EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
   11424   }
   11425 
   11426   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
   11427   SpecialMem->setType(QT);
   11428 }
   11429 
   11430 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
   11431                                                      CXXRecordDecl *ClassDecl) {
   11432   // C++ [class.ctor]p5:
   11433   //   A default constructor for a class X is a constructor of class X
   11434   //   that can be called without an argument. If there is no
   11435   //   user-declared constructor for class X, a default constructor is
   11436   //   implicitly declared. An implicitly-declared default constructor
   11437   //   is an inline public member of its class.
   11438   assert(ClassDecl->needsImplicitDefaultConstructor() &&
   11439          "Should not build implicit default constructor!");
   11440 
   11441   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
   11442   if (DSM.isAlreadyBeingDeclared())
   11443     return nullptr;
   11444 
   11445   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   11446                                                      CXXDefaultConstructor,
   11447                                                      false);
   11448 
   11449   // Create the actual constructor declaration.
   11450   CanQualType ClassType
   11451     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
   11452   SourceLocation ClassLoc = ClassDecl->getLocation();
   11453   DeclarationName Name
   11454     = Context.DeclarationNames.getCXXConstructorName(ClassType);
   11455   DeclarationNameInfo NameInfo(Name, ClassLoc);
   11456   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
   11457       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
   11458       /*TInfo=*/nullptr, ExplicitSpecifier(),
   11459       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
   11460       Constexpr ? CSK_constexpr : CSK_unspecified);
   11461   DefaultCon->setAccess(AS_public);
   11462   DefaultCon->setDefaulted();
   11463 
   11464   if (getLangOpts().CUDA) {
   11465     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
   11466                                             DefaultCon,
   11467                                             /* ConstRHS */ false,
   11468                                             /* Diagnose */ false);
   11469   }
   11470 
   11471   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
   11472 
   11473   // We don't need to use SpecialMemberIsTrivial here; triviality for default
   11474   // constructors is easy to compute.
   11475   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
   11476 
   11477   // Note that we have declared this constructor.
   11478   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
   11479 
   11480   Scope *S = getScopeForContext(ClassDecl);
   11481   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
   11482 
   11483   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
   11484     SetDeclDeleted(DefaultCon, ClassLoc);
   11485 
   11486   if (S)
   11487     PushOnScopeChains(DefaultCon, S, false);
   11488   ClassDecl->addDecl(DefaultCon);
   11489 
   11490   return DefaultCon;
   11491 }
   11492 
   11493 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
   11494                                             CXXConstructorDecl *Constructor) {
   11495   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
   11496           !Constructor->doesThisDeclarationHaveABody() &&
   11497           !Constructor->isDeleted()) &&
   11498     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
   11499   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
   11500     return;
   11501 
   11502   CXXRecordDecl *ClassDecl = Constructor->getParent();
   11503   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
   11504 
   11505   SynthesizedFunctionScope Scope(*this, Constructor);
   11506 
   11507   // The exception specification is needed because we are defining the
   11508   // function.
   11509   ResolveExceptionSpec(CurrentLocation,
   11510                        Constructor->getType()->castAs<FunctionProtoType>());
   11511   MarkVTableUsed(CurrentLocation, ClassDecl);
   11512 
   11513   // Add a context note for diagnostics produced after this point.
   11514   Scope.addContextNote(CurrentLocation);
   11515 
   11516   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
   11517     Constructor->setInvalidDecl();
   11518     return;
   11519   }
   11520 
   11521   SourceLocation Loc = Constructor->getEndLoc().isValid()
   11522                            ? Constructor->getEndLoc()
   11523                            : Constructor->getLocation();
   11524   Constructor->setBody(new (Context) CompoundStmt(Loc));
   11525   Constructor->markUsed(Context);
   11526 
   11527   if (ASTMutationListener *L = getASTMutationListener()) {
   11528     L->CompletedImplicitDefinition(Constructor);
   11529   }
   11530 
   11531   DiagnoseUninitializedFields(*this, Constructor);
   11532 }
   11533 
   11534 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
   11535   // Perform any delayed checks on exception specifications.
   11536   CheckDelayedMemberExceptionSpecs();
   11537 }
   11538 
   11539 /// Find or create the fake constructor we synthesize to model constructing an
   11540 /// object of a derived class via a constructor of a base class.
   11541 CXXConstructorDecl *
   11542 Sema::findInheritingConstructor(SourceLocation Loc,
   11543                                 CXXConstructorDecl *BaseCtor,
   11544                                 ConstructorUsingShadowDecl *Shadow) {
   11545   CXXRecordDecl *Derived = Shadow->getParent();
   11546   SourceLocation UsingLoc = Shadow->getLocation();
   11547 
   11548   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
   11549   // For now we use the name of the base class constructor as a member of the
   11550   // derived class to indicate a (fake) inherited constructor name.
   11551   DeclarationName Name = BaseCtor->getDeclName();
   11552 
   11553   // Check to see if we already have a fake constructor for this inherited
   11554   // constructor call.
   11555   for (NamedDecl *Ctor : Derived->lookup(Name))
   11556     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
   11557                                ->getInheritedConstructor()
   11558                                .getConstructor(),
   11559                            BaseCtor))
   11560       return cast<CXXConstructorDecl>(Ctor);
   11561 
   11562   DeclarationNameInfo NameInfo(Name, UsingLoc);
   11563   TypeSourceInfo *TInfo =
   11564       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
   11565   FunctionProtoTypeLoc ProtoLoc =
   11566       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
   11567 
   11568   // Check the inherited constructor is valid and find the list of base classes
   11569   // from which it was inherited.
   11570   InheritedConstructorInfo ICI(*this, Loc, Shadow);
   11571 
   11572   bool Constexpr =
   11573       BaseCtor->isConstexpr() &&
   11574       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
   11575                                         false, BaseCtor, &ICI);
   11576 
   11577   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
   11578       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
   11579       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
   11580       /*isImplicitlyDeclared=*/true,
   11581       Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
   11582       InheritedConstructor(Shadow, BaseCtor));
   11583   if (Shadow->isInvalidDecl())
   11584     DerivedCtor->setInvalidDecl();
   11585 
   11586   // Build an unevaluated exception specification for this fake constructor.
   11587   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
   11588   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
   11589   EPI.ExceptionSpec.Type = EST_Unevaluated;
   11590   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
   11591   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
   11592                                                FPT->getParamTypes(), EPI));
   11593 
   11594   // Build the parameter declarations.
   11595   SmallVector<ParmVarDecl *, 16> ParamDecls;
   11596   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
   11597     TypeSourceInfo *TInfo =
   11598         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
   11599     ParmVarDecl *PD = ParmVarDecl::Create(
   11600         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
   11601         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
   11602     PD->setScopeInfo(0, I);
   11603     PD->setImplicit();
   11604     // Ensure attributes are propagated onto parameters (this matters for
   11605     // format, pass_object_size, ...).
   11606     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
   11607     ParamDecls.push_back(PD);
   11608     ProtoLoc.setParam(I, PD);
   11609   }
   11610 
   11611   // Set up the new constructor.
   11612   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
   11613   DerivedCtor->setAccess(BaseCtor->getAccess());
   11614   DerivedCtor->setParams(ParamDecls);
   11615   Derived->addDecl(DerivedCtor);
   11616 
   11617   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
   11618     SetDeclDeleted(DerivedCtor, UsingLoc);
   11619 
   11620   return DerivedCtor;
   11621 }
   11622 
   11623 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
   11624   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
   11625                                Ctor->getInheritedConstructor().getShadowDecl());
   11626   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
   11627                             /*Diagnose*/true);
   11628 }
   11629 
   11630 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
   11631                                        CXXConstructorDecl *Constructor) {
   11632   CXXRecordDecl *ClassDecl = Constructor->getParent();
   11633   assert(Constructor->getInheritedConstructor() &&
   11634          !Constructor->doesThisDeclarationHaveABody() &&
   11635          !Constructor->isDeleted());
   11636   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
   11637     return;
   11638 
   11639   // Initializations are performed "as if by a defaulted default constructor",
   11640   // so enter the appropriate scope.
   11641   SynthesizedFunctionScope Scope(*this, Constructor);
   11642 
   11643   // The exception specification is needed because we are defining the
   11644   // function.
   11645   ResolveExceptionSpec(CurrentLocation,
   11646                        Constructor->getType()->castAs<FunctionProtoType>());
   11647   MarkVTableUsed(CurrentLocation, ClassDecl);
   11648 
   11649   // Add a context note for diagnostics produced after this point.
   11650   Scope.addContextNote(CurrentLocation);
   11651 
   11652   ConstructorUsingShadowDecl *Shadow =
   11653       Constructor->getInheritedConstructor().getShadowDecl();
   11654   CXXConstructorDecl *InheritedCtor =
   11655       Constructor->getInheritedConstructor().getConstructor();
   11656 
   11657   // [class.inhctor.init]p1:
   11658   //   initialization proceeds as if a defaulted default constructor is used to
   11659   //   initialize the D object and each base class subobject from which the
   11660   //   constructor was inherited
   11661 
   11662   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
   11663   CXXRecordDecl *RD = Shadow->getParent();
   11664   SourceLocation InitLoc = Shadow->getLocation();
   11665 
   11666   // Build explicit initializers for all base classes from which the
   11667   // constructor was inherited.
   11668   SmallVector<CXXCtorInitializer*, 8> Inits;
   11669   for (bool VBase : {false, true}) {
   11670     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
   11671       if (B.isVirtual() != VBase)
   11672         continue;
   11673 
   11674       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
   11675       if (!BaseRD)
   11676         continue;
   11677 
   11678       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
   11679       if (!BaseCtor.first)
   11680         continue;
   11681 
   11682       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
   11683       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
   11684           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
   11685 
   11686       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
   11687       Inits.push_back(new (Context) CXXCtorInitializer(
   11688           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
   11689           SourceLocation()));
   11690     }
   11691   }
   11692 
   11693   // We now proceed as if for a defaulted default constructor, with the relevant
   11694   // initializers replaced.
   11695 
   11696   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
   11697     Constructor->setInvalidDecl();
   11698     return;
   11699   }
   11700 
   11701   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
   11702   Constructor->markUsed(Context);
   11703 
   11704   if (ASTMutationListener *L = getASTMutationListener()) {
   11705     L->CompletedImplicitDefinition(Constructor);
   11706   }
   11707 
   11708   DiagnoseUninitializedFields(*this, Constructor);
   11709 }
   11710 
   11711 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
   11712   // C++ [class.dtor]p2:
   11713   //   If a class has no user-declared destructor, a destructor is
   11714   //   declared implicitly. An implicitly-declared destructor is an
   11715   //   inline public member of its class.
   11716   assert(ClassDecl->needsImplicitDestructor());
   11717 
   11718   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
   11719   if (DSM.isAlreadyBeingDeclared())
   11720     return nullptr;
   11721 
   11722   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   11723                                                      CXXDestructor,
   11724                                                      false);
   11725 
   11726   // Create the actual destructor declaration.
   11727   CanQualType ClassType
   11728     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
   11729   SourceLocation ClassLoc = ClassDecl->getLocation();
   11730   DeclarationName Name
   11731     = Context.DeclarationNames.getCXXDestructorName(ClassType);
   11732   DeclarationNameInfo NameInfo(Name, ClassLoc);
   11733   CXXDestructorDecl *Destructor =
   11734       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
   11735                                 QualType(), nullptr, /*isInline=*/true,
   11736                                 /*isImplicitlyDeclared=*/true,
   11737                                 Constexpr ? CSK_constexpr : CSK_unspecified);
   11738   Destructor->setAccess(AS_public);
   11739   Destructor->setDefaulted();
   11740 
   11741   if (getLangOpts().CUDA) {
   11742     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
   11743                                             Destructor,
   11744                                             /* ConstRHS */ false,
   11745                                             /* Diagnose */ false);
   11746   }
   11747 
   11748   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
   11749 
   11750   // We don't need to use SpecialMemberIsTrivial here; triviality for
   11751   // destructors is easy to compute.
   11752   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
   11753   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
   11754                                 ClassDecl->hasTrivialDestructorForCall());
   11755 
   11756   // Note that we have declared this destructor.
   11757   ++getASTContext().NumImplicitDestructorsDeclared;
   11758 
   11759   Scope *S = getScopeForContext(ClassDecl);
   11760   CheckImplicitSpecialMemberDeclaration(S, Destructor);
   11761 
   11762   // We can't check whether an implicit destructor is deleted before we complete
   11763   // the definition of the class, because its validity depends on the alignment
   11764   // of the class. We'll check this from ActOnFields once the class is complete.
   11765   if (ClassDecl->isCompleteDefinition() &&
   11766       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
   11767     SetDeclDeleted(Destructor, ClassLoc);
   11768 
   11769   // Introduce this destructor into its scope.
   11770   if (S)
   11771     PushOnScopeChains(Destructor, S, false);
   11772   ClassDecl->addDecl(Destructor);
   11773 
   11774   return Destructor;
   11775 }
   11776 
   11777 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
   11778                                     CXXDestructorDecl *Destructor) {
   11779   assert((Destructor->isDefaulted() &&
   11780           !Destructor->doesThisDeclarationHaveABody() &&
   11781           !Destructor->isDeleted()) &&
   11782          "DefineImplicitDestructor - call it for implicit default dtor");
   11783   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
   11784     return;
   11785 
   11786   CXXRecordDecl *ClassDecl = Destructor->getParent();
   11787   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
   11788 
   11789   SynthesizedFunctionScope Scope(*this, Destructor);
   11790 
   11791   // The exception specification is needed because we are defining the
   11792   // function.
   11793   ResolveExceptionSpec(CurrentLocation,
   11794                        Destructor->getType()->castAs<FunctionProtoType>());
   11795   MarkVTableUsed(CurrentLocation, ClassDecl);
   11796 
   11797   // Add a context note for diagnostics produced after this point.
   11798   Scope.addContextNote(CurrentLocation);
   11799 
   11800   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
   11801                                          Destructor->getParent());
   11802 
   11803   if (CheckDestructor(Destructor)) {
   11804     Destructor->setInvalidDecl();
   11805     return;
   11806   }
   11807 
   11808   SourceLocation Loc = Destructor->getEndLoc().isValid()
   11809                            ? Destructor->getEndLoc()
   11810                            : Destructor->getLocation();
   11811   Destructor->setBody(new (Context) CompoundStmt(Loc));
   11812   Destructor->markUsed(Context);
   11813 
   11814   if (ASTMutationListener *L = getASTMutationListener()) {
   11815     L->CompletedImplicitDefinition(Destructor);
   11816   }
   11817 }
   11818 
   11819 /// Perform any semantic analysis which needs to be delayed until all
   11820 /// pending class member declarations have been parsed.
   11821 void Sema::ActOnFinishCXXMemberDecls() {
   11822   // If the context is an invalid C++ class, just suppress these checks.
   11823   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
   11824     if (Record->isInvalidDecl()) {
   11825       DelayedOverridingExceptionSpecChecks.clear();
   11826       DelayedEquivalentExceptionSpecChecks.clear();
   11827       return;
   11828     }
   11829     checkForMultipleExportedDefaultConstructors(*this, Record);
   11830   }
   11831 }
   11832 
   11833 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
   11834   referenceDLLExportedClassMethods();
   11835 
   11836   if (!DelayedDllExportMemberFunctions.empty()) {
   11837     SmallVector<CXXMethodDecl*, 4> WorkList;
   11838     std::swap(DelayedDllExportMemberFunctions, WorkList);
   11839     for (CXXMethodDecl *M : WorkList) {
   11840       DefineImplicitSpecialMember(*this, M, M->getLocation());
   11841 
   11842       // Pass the method to the consumer to get emitted. This is not necessary
   11843       // for explicit instantiation definitions, as they will get emitted
   11844       // anyway.
   11845       if (M->getParent()->getTemplateSpecializationKind() !=
   11846           TSK_ExplicitInstantiationDefinition)
   11847         ActOnFinishInlineFunctionDef(M);
   11848     }
   11849   }
   11850 }
   11851 
   11852 void Sema::referenceDLLExportedClassMethods() {
   11853   if (!DelayedDllExportClasses.empty()) {
   11854     // Calling ReferenceDllExportedMembers might cause the current function to
   11855     // be called again, so use a local copy of DelayedDllExportClasses.
   11856     SmallVector<CXXRecordDecl *, 4> WorkList;
   11857     std::swap(DelayedDllExportClasses, WorkList);
   11858     for (CXXRecordDecl *Class : WorkList)
   11859       ReferenceDllExportedMembers(*this, Class);
   11860   }
   11861 }
   11862 
   11863 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
   11864   assert(getLangOpts().CPlusPlus11 &&
   11865          "adjusting dtor exception specs was introduced in c++11");
   11866 
   11867   if (Destructor->isDependentContext())
   11868     return;
   11869 
   11870   // C++11 [class.dtor]p3:
   11871   //   A declaration of a destructor that does not have an exception-
   11872   //   specification is implicitly considered to have the same exception-
   11873   //   specification as an implicit declaration.
   11874   const FunctionProtoType *DtorType = Destructor->getType()->
   11875                                         getAs<FunctionProtoType>();
   11876   if (DtorType->hasExceptionSpec())
   11877     return;
   11878 
   11879   // Replace the destructor's type, building off the existing one. Fortunately,
   11880   // the only thing of interest in the destructor type is its extended info.
   11881   // The return and arguments are fixed.
   11882   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
   11883   EPI.ExceptionSpec.Type = EST_Unevaluated;
   11884   EPI.ExceptionSpec.SourceDecl = Destructor;
   11885   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
   11886 
   11887   // FIXME: If the destructor has a body that could throw, and the newly created
   11888   // spec doesn't allow exceptions, we should emit a warning, because this
   11889   // change in behavior can break conforming C++03 programs at runtime.
   11890   // However, we don't have a body or an exception specification yet, so it
   11891   // needs to be done somewhere else.
   11892 }
   11893 
   11894 namespace {
   11895 /// An abstract base class for all helper classes used in building the
   11896 //  copy/move operators. These classes serve as factory functions and help us
   11897 //  avoid using the same Expr* in the AST twice.
   11898 class ExprBuilder {
   11899   ExprBuilder(const ExprBuilder&) = delete;
   11900   ExprBuilder &operator=(const ExprBuilder&) = delete;
   11901 
   11902 protected:
   11903   static Expr *assertNotNull(Expr *E) {
   11904     assert(E && "Expression construction must not fail.");
   11905     return E;
   11906   }
   11907 
   11908 public:
   11909   ExprBuilder() {}
   11910   virtual ~ExprBuilder() {}
   11911 
   11912   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
   11913 };
   11914 
   11915 class RefBuilder: public ExprBuilder {
   11916   VarDecl *Var;
   11917   QualType VarType;
   11918 
   11919 public:
   11920   Expr *build(Sema &S, SourceLocation Loc) const override {
   11921     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
   11922   }
   11923 
   11924   RefBuilder(VarDecl *Var, QualType VarType)
   11925       : Var(Var), VarType(VarType) {}
   11926 };
   11927 
   11928 class ThisBuilder: public ExprBuilder {
   11929 public:
   11930   Expr *build(Sema &S, SourceLocation Loc) const override {
   11931     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
   11932   }
   11933 };
   11934 
   11935 class CastBuilder: public ExprBuilder {
   11936   const ExprBuilder &Builder;
   11937   QualType Type;
   11938   ExprValueKind Kind;
   11939   const CXXCastPath &Path;
   11940 
   11941 public:
   11942   Expr *build(Sema &S, SourceLocation Loc) const override {
   11943     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
   11944                                              CK_UncheckedDerivedToBase, Kind,
   11945                                              &Path).get());
   11946   }
   11947 
   11948   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
   11949               const CXXCastPath &Path)
   11950       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
   11951 };
   11952 
   11953 class DerefBuilder: public ExprBuilder {
   11954   const ExprBuilder &Builder;
   11955 
   11956 public:
   11957   Expr *build(Sema &S, SourceLocation Loc) const override {
   11958     return assertNotNull(
   11959         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
   11960   }
   11961 
   11962   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
   11963 };
   11964 
   11965 class MemberBuilder: public ExprBuilder {
   11966   const ExprBuilder &Builder;
   11967   QualType Type;
   11968   CXXScopeSpec SS;
   11969   bool IsArrow;
   11970   LookupResult &MemberLookup;
   11971 
   11972 public:
   11973   Expr *build(Sema &S, SourceLocation Loc) const override {
   11974     return assertNotNull(S.BuildMemberReferenceExpr(
   11975         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
   11976         nullptr, MemberLookup, nullptr, nullptr).get());
   11977   }
   11978 
   11979   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
   11980                 LookupResult &MemberLookup)
   11981       : Builder(Builder), Type(Type), IsArrow(IsArrow),
   11982         MemberLookup(MemberLookup) {}
   11983 };
   11984 
   11985 class MoveCastBuilder: public ExprBuilder {
   11986   const ExprBuilder &Builder;
   11987 
   11988 public:
   11989   Expr *build(Sema &S, SourceLocation Loc) const override {
   11990     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
   11991   }
   11992 
   11993   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
   11994 };
   11995 
   11996 class LvalueConvBuilder: public ExprBuilder {
   11997   const ExprBuilder &Builder;
   11998 
   11999 public:
   12000   Expr *build(Sema &S, SourceLocation Loc) const override {
   12001     return assertNotNull(
   12002         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
   12003   }
   12004 
   12005   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
   12006 };
   12007 
   12008 class SubscriptBuilder: public ExprBuilder {
   12009   const ExprBuilder &Base;
   12010   const ExprBuilder &Index;
   12011 
   12012 public:
   12013   Expr *build(Sema &S, SourceLocation Loc) const override {
   12014     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
   12015         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
   12016   }
   12017 
   12018   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
   12019       : Base(Base), Index(Index) {}
   12020 };
   12021 
   12022 } // end anonymous namespace
   12023 
   12024 /// When generating a defaulted copy or move assignment operator, if a field
   12025 /// should be copied with __builtin_memcpy rather than via explicit assignments,
   12026 /// do so. This optimization only applies for arrays of scalars, and for arrays
   12027 /// of class type where the selected copy/move-assignment operator is trivial.
   12028 static StmtResult
   12029 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
   12030                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
   12031   // Compute the size of the memory buffer to be copied.
   12032   QualType SizeType = S.Context.getSizeType();
   12033   llvm::APInt Size(S.Context.getTypeSize(SizeType),
   12034                    S.Context.getTypeSizeInChars(T).getQuantity());
   12035 
   12036   // Take the address of the field references for "from" and "to". We
   12037   // directly construct UnaryOperators here because semantic analysis
   12038   // does not permit us to take the address of an xvalue.
   12039   Expr *From = FromB.build(S, Loc);
   12040   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
   12041                          S.Context.getPointerType(From->getType()),
   12042                          VK_RValue, OK_Ordinary, Loc, false);
   12043   Expr *To = ToB.build(S, Loc);
   12044   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
   12045                        S.Context.getPointerType(To->getType()),
   12046                        VK_RValue, OK_Ordinary, Loc, false);
   12047 
   12048   const Type *E = T->getBaseElementTypeUnsafe();
   12049   bool NeedsCollectableMemCpy =
   12050       E->isRecordType() &&
   12051       E->castAs<RecordType>()->getDecl()->hasObjectMember();
   12052 
   12053   // Create a reference to the __builtin_objc_memmove_collectable function
   12054   StringRef MemCpyName = NeedsCollectableMemCpy ?
   12055     "__builtin_objc_memmove_collectable" :
   12056     "__builtin_memcpy";
   12057   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
   12058                  Sema::LookupOrdinaryName);
   12059   S.LookupName(R, S.TUScope, true);
   12060 
   12061   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
   12062   if (!MemCpy)
   12063     // Something went horribly wrong earlier, and we will have complained
   12064     // about it.
   12065     return StmtError();
   12066 
   12067   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
   12068                                             VK_RValue, Loc, nullptr);
   12069   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
   12070 
   12071   Expr *CallArgs[] = {
   12072     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
   12073   };
   12074   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
   12075                                     Loc, CallArgs, Loc);
   12076 
   12077   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
   12078   return Call.getAs<Stmt>();
   12079 }
   12080 
   12081 /// Builds a statement that copies/moves the given entity from \p From to
   12082 /// \c To.
   12083 ///
   12084 /// This routine is used to copy/move the members of a class with an
   12085 /// implicitly-declared copy/move assignment operator. When the entities being
   12086 /// copied are arrays, this routine builds for loops to copy them.
   12087 ///
   12088 /// \param S The Sema object used for type-checking.
   12089 ///
   12090 /// \param Loc The location where the implicit copy/move is being generated.
   12091 ///
   12092 /// \param T The type of the expressions being copied/moved. Both expressions
   12093 /// must have this type.
   12094 ///
   12095 /// \param To The expression we are copying/moving to.
   12096 ///
   12097 /// \param From The expression we are copying/moving from.
   12098 ///
   12099 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
   12100 /// Otherwise, it's a non-static member subobject.
   12101 ///
   12102 /// \param Copying Whether we're copying or moving.
   12103 ///
   12104 /// \param Depth Internal parameter recording the depth of the recursion.
   12105 ///
   12106 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
   12107 /// if a memcpy should be used instead.
   12108 static StmtResult
   12109 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
   12110                                  const ExprBuilder &To, const ExprBuilder &From,
   12111                                  bool CopyingBaseSubobject, bool Copying,
   12112                                  unsigned Depth = 0) {
   12113   // C++11 [class.copy]p28:
   12114   //   Each subobject is assigned in the manner appropriate to its type:
   12115   //
   12116   //     - if the subobject is of class type, as if by a call to operator= with
   12117   //       the subobject as the object expression and the corresponding
   12118   //       subobject of x as a single function argument (as if by explicit
   12119   //       qualification; that is, ignoring any possible virtual overriding
   12120   //       functions in more derived classes);
   12121   //
   12122   // C++03 [class.copy]p13:
   12123   //     - if the subobject is of class type, the copy assignment operator for
   12124   //       the class is used (as if by explicit qualification; that is,
   12125   //       ignoring any possible virtual overriding functions in more derived
   12126   //       classes);
   12127   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
   12128     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
   12129 
   12130     // Look for operator=.
   12131     DeclarationName Name
   12132       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
   12133     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
   12134     S.LookupQualifiedName(OpLookup, ClassDecl, false);
   12135 
   12136     // Prior to C++11, filter out any result that isn't a copy/move-assignment
   12137     // operator.
   12138     if (!S.getLangOpts().CPlusPlus11) {
   12139       LookupResult::Filter F = OpLookup.makeFilter();
   12140       while (F.hasNext()) {
   12141         NamedDecl *D = F.next();
   12142         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
   12143           if (Method->isCopyAssignmentOperator() ||
   12144               (!Copying && Method->isMoveAssignmentOperator()))
   12145             continue;
   12146 
   12147         F.erase();
   12148       }
   12149       F.done();
   12150     }
   12151 
   12152     // Suppress the protected check (C++ [class.protected]) for each of the
   12153     // assignment operators we found. This strange dance is required when
   12154     // we're assigning via a base classes's copy-assignment operator. To
   12155     // ensure that we're getting the right base class subobject (without
   12156     // ambiguities), we need to cast "this" to that subobject type; to
   12157     // ensure that we don't go through the virtual call mechanism, we need
   12158     // to qualify the operator= name with the base class (see below). However,
   12159     // this means that if the base class has a protected copy assignment
   12160     // operator, the protected member access check will fail. So, we
   12161     // rewrite "protected" access to "public" access in this case, since we
   12162     // know by construction that we're calling from a derived class.
   12163     if (CopyingBaseSubobject) {
   12164       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
   12165            L != LEnd; ++L) {
   12166         if (L.getAccess() == AS_protected)
   12167           L.setAccess(AS_public);
   12168       }
   12169     }
   12170 
   12171     // Create the nested-name-specifier that will be used to qualify the
   12172     // reference to operator=; this is required to suppress the virtual
   12173     // call mechanism.
   12174     CXXScopeSpec SS;
   12175     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
   12176     SS.MakeTrivial(S.Context,
   12177                    NestedNameSpecifier::Create(S.Context, nullptr, false,
   12178                                                CanonicalT),
   12179                    Loc);
   12180 
   12181     // Create the reference to operator=.
   12182     ExprResult OpEqualRef
   12183       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
   12184                                    SS, /*TemplateKWLoc=*/SourceLocation(),
   12185                                    /*FirstQualifierInScope=*/nullptr,
   12186                                    OpLookup,
   12187                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
   12188                                    /*SuppressQualifierCheck=*/true);
   12189     if (OpEqualRef.isInvalid())
   12190       return StmtError();
   12191 
   12192     // Build the call to the assignment operator.
   12193 
   12194     Expr *FromInst = From.build(S, Loc);
   12195     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
   12196                                                   OpEqualRef.getAs<Expr>(),
   12197                                                   Loc, FromInst, Loc);
   12198     if (Call.isInvalid())
   12199       return StmtError();
   12200 
   12201     // If we built a call to a trivial 'operator=' while copying an array,
   12202     // bail out. We'll replace the whole shebang with a memcpy.
   12203     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
   12204     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
   12205       return StmtResult((Stmt*)nullptr);
   12206 
   12207     // Convert to an expression-statement, and clean up any produced
   12208     // temporaries.
   12209     return S.ActOnExprStmt(Call);
   12210   }
   12211 
   12212   //     - if the subobject is of scalar type, the built-in assignment
   12213   //       operator is used.
   12214   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
   12215   if (!ArrayTy) {
   12216     ExprResult Assignment = S.CreateBuiltinBinOp(
   12217         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
   12218     if (Assignment.isInvalid())
   12219       return StmtError();
   12220     return S.ActOnExprStmt(Assignment);
   12221   }
   12222 
   12223   //     - if the subobject is an array, each element is assigned, in the
   12224   //       manner appropriate to the element type;
   12225 
   12226   // Construct a loop over the array bounds, e.g.,
   12227   //
   12228   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
   12229   //
   12230   // that will copy each of the array elements.
   12231   QualType SizeType = S.Context.getSizeType();
   12232 
   12233   // Create the iteration variable.
   12234   IdentifierInfo *IterationVarName = nullptr;
   12235   {
   12236     SmallString<8> Str;
   12237     llvm::raw_svector_ostream OS(Str);
   12238     OS << "__i" << Depth;
   12239     IterationVarName = &S.Context.Idents.get(OS.str());
   12240   }
   12241   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
   12242                                           IterationVarName, SizeType,
   12243                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
   12244                                           SC_None);
   12245 
   12246   // Initialize the iteration variable to zero.
   12247   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
   12248   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
   12249 
   12250   // Creates a reference to the iteration variable.
   12251   RefBuilder IterationVarRef(IterationVar, SizeType);
   12252   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
   12253 
   12254   // Create the DeclStmt that holds the iteration variable.
   12255   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
   12256 
   12257   // Subscript the "from" and "to" expressions with the iteration variable.
   12258   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
   12259   MoveCastBuilder FromIndexMove(FromIndexCopy);
   12260   const ExprBuilder *FromIndex;
   12261   if (Copying)
   12262     FromIndex = &FromIndexCopy;
   12263   else
   12264     FromIndex = &FromIndexMove;
   12265 
   12266   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
   12267 
   12268   // Build the copy/move for an individual element of the array.
   12269   StmtResult Copy =
   12270     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
   12271                                      ToIndex, *FromIndex, CopyingBaseSubobject,
   12272                                      Copying, Depth + 1);
   12273   // Bail out if copying fails or if we determined that we should use memcpy.
   12274   if (Copy.isInvalid() || !Copy.get())
   12275     return Copy;
   12276 
   12277   // Create the comparison against the array bound.
   12278   llvm::APInt Upper
   12279     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
   12280   Expr *Comparison
   12281     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
   12282                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
   12283                                      BO_NE, S.Context.BoolTy,
   12284                                      VK_RValue, OK_Ordinary, Loc, FPOptions());
   12285 
   12286   // Create the pre-increment of the iteration variable. We can determine
   12287   // whether the increment will overflow based on the value of the array
   12288   // bound.
   12289   Expr *Increment = new (S.Context)
   12290       UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
   12291                     VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
   12292 
   12293   // Construct the loop that copies all elements of this array.
   12294   return S.ActOnForStmt(
   12295       Loc, Loc, InitStmt,
   12296       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
   12297       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
   12298 }
   12299 
   12300 static StmtResult
   12301 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
   12302                       const ExprBuilder &To, const ExprBuilder &From,
   12303                       bool CopyingBaseSubobject, bool Copying) {
   12304   // Maybe we should use a memcpy?
   12305   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
   12306       T.isTriviallyCopyableType(S.Context))
   12307     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
   12308 
   12309   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
   12310                                                      CopyingBaseSubobject,
   12311                                                      Copying, 0));
   12312 
   12313   // If we ended up picking a trivial assignment operator for an array of a
   12314   // non-trivially-copyable class type, just emit a memcpy.
   12315   if (!Result.isInvalid() && !Result.get())
   12316     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
   12317 
   12318   return Result;
   12319 }
   12320 
   12321 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
   12322   // Note: The following rules are largely analoguous to the copy
   12323   // constructor rules. Note that virtual bases are not taken into account
   12324   // for determining the argument type of the operator. Note also that
   12325   // operators taking an object instead of a reference are allowed.
   12326   assert(ClassDecl->needsImplicitCopyAssignment());
   12327 
   12328   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
   12329   if (DSM.isAlreadyBeingDeclared())
   12330     return nullptr;
   12331 
   12332   QualType ArgType = Context.getTypeDeclType(ClassDecl);
   12333   if (Context.getLangOpts().OpenCLCPlusPlus)
   12334     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
   12335   QualType RetType = Context.getLValueReferenceType(ArgType);
   12336   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
   12337   if (Const)
   12338     ArgType = ArgType.withConst();
   12339 
   12340   ArgType = Context.getLValueReferenceType(ArgType);
   12341 
   12342   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   12343                                                      CXXCopyAssignment,
   12344                                                      Const);
   12345 
   12346   //   An implicitly-declared copy assignment operator is an inline public
   12347   //   member of its class.
   12348   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
   12349   SourceLocation ClassLoc = ClassDecl->getLocation();
   12350   DeclarationNameInfo NameInfo(Name, ClassLoc);
   12351   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
   12352       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
   12353       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
   12354       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
   12355       SourceLocation());
   12356   CopyAssignment->setAccess(AS_public);
   12357   CopyAssignment->setDefaulted();
   12358   CopyAssignment->setImplicit();
   12359 
   12360   if (getLangOpts().CUDA) {
   12361     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
   12362                                             CopyAssignment,
   12363                                             /* ConstRHS */ Const,
   12364                                             /* Diagnose */ false);
   12365   }
   12366 
   12367   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
   12368 
   12369   // Add the parameter to the operator.
   12370   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
   12371                                                ClassLoc, ClassLoc,
   12372                                                /*Id=*/nullptr, ArgType,
   12373                                                /*TInfo=*/nullptr, SC_None,
   12374                                                nullptr);
   12375   CopyAssignment->setParams(FromParam);
   12376 
   12377   CopyAssignment->setTrivial(
   12378     ClassDecl->needsOverloadResolutionForCopyAssignment()
   12379       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
   12380       : ClassDecl->hasTrivialCopyAssignment());
   12381 
   12382   // Note that we have added this copy-assignment operator.
   12383   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
   12384 
   12385   Scope *S = getScopeForContext(ClassDecl);
   12386   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
   12387 
   12388   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
   12389     SetDeclDeleted(CopyAssignment, ClassLoc);
   12390 
   12391   if (S)
   12392     PushOnScopeChains(CopyAssignment, S, false);
   12393   ClassDecl->addDecl(CopyAssignment);
   12394 
   12395   return CopyAssignment;
   12396 }
   12397 
   12398 /// Diagnose an implicit copy operation for a class which is odr-used, but
   12399 /// which is deprecated because the class has a user-declared copy constructor,
   12400 /// copy assignment operator, or destructor.
   12401 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
   12402   assert(CopyOp->isImplicit());
   12403 
   12404   CXXRecordDecl *RD = CopyOp->getParent();
   12405   CXXMethodDecl *UserDeclaredOperation = nullptr;
   12406 
   12407   // In Microsoft mode, assignment operations don't affect constructors and
   12408   // vice versa.
   12409   if (RD->hasUserDeclaredDestructor()) {
   12410     UserDeclaredOperation = RD->getDestructor();
   12411   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
   12412              RD->hasUserDeclaredCopyConstructor() &&
   12413              !S.getLangOpts().MSVCCompat) {
   12414     // Find any user-declared copy constructor.
   12415     for (auto *I : RD->ctors()) {
   12416       if (I->isCopyConstructor()) {
   12417         UserDeclaredOperation = I;
   12418         break;
   12419       }
   12420     }
   12421     assert(UserDeclaredOperation);
   12422   } else if (isa<CXXConstructorDecl>(CopyOp) &&
   12423              RD->hasUserDeclaredCopyAssignment() &&
   12424              !S.getLangOpts().MSVCCompat) {
   12425     // Find any user-declared move assignment operator.
   12426     for (auto *I : RD->methods()) {
   12427       if (I->isCopyAssignmentOperator()) {
   12428         UserDeclaredOperation = I;
   12429         break;
   12430       }
   12431     }
   12432     assert(UserDeclaredOperation);
   12433   }
   12434 
   12435   if (UserDeclaredOperation) {
   12436     S.Diag(UserDeclaredOperation->getLocation(),
   12437          diag::warn_deprecated_copy_operation)
   12438       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
   12439       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
   12440   }
   12441 }
   12442 
   12443 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
   12444                                         CXXMethodDecl *CopyAssignOperator) {
   12445   assert((CopyAssignOperator->isDefaulted() &&
   12446           CopyAssignOperator->isOverloadedOperator() &&
   12447           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
   12448           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
   12449           !CopyAssignOperator->isDeleted()) &&
   12450          "DefineImplicitCopyAssignment called for wrong function");
   12451   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
   12452     return;
   12453 
   12454   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
   12455   if (ClassDecl->isInvalidDecl()) {
   12456     CopyAssignOperator->setInvalidDecl();
   12457     return;
   12458   }
   12459 
   12460   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
   12461 
   12462   // The exception specification is needed because we are defining the
   12463   // function.
   12464   ResolveExceptionSpec(CurrentLocation,
   12465                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
   12466 
   12467   // Add a context note for diagnostics produced after this point.
   12468   Scope.addContextNote(CurrentLocation);
   12469 
   12470   // C++11 [class.copy]p18:
   12471   //   The [definition of an implicitly declared copy assignment operator] is
   12472   //   deprecated if the class has a user-declared copy constructor or a
   12473   //   user-declared destructor.
   12474   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
   12475     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
   12476 
   12477   // C++0x [class.copy]p30:
   12478   //   The implicitly-defined or explicitly-defaulted copy assignment operator
   12479   //   for a non-union class X performs memberwise copy assignment of its
   12480   //   subobjects. The direct base classes of X are assigned first, in the
   12481   //   order of their declaration in the base-specifier-list, and then the
   12482   //   immediate non-static data members of X are assigned, in the order in
   12483   //   which they were declared in the class definition.
   12484 
   12485   // The statements that form the synthesized function body.
   12486   SmallVector<Stmt*, 8> Statements;
   12487 
   12488   // The parameter for the "other" object, which we are copying from.
   12489   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
   12490   Qualifiers OtherQuals = Other->getType().getQualifiers();
   12491   QualType OtherRefType = Other->getType();
   12492   if (const LValueReferenceType *OtherRef
   12493                                 = OtherRefType->getAs<LValueReferenceType>()) {
   12494     OtherRefType = OtherRef->getPointeeType();
   12495     OtherQuals = OtherRefType.getQualifiers();
   12496   }
   12497 
   12498   // Our location for everything implicitly-generated.
   12499   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
   12500                            ? CopyAssignOperator->getEndLoc()
   12501                            : CopyAssignOperator->getLocation();
   12502 
   12503   // Builds a DeclRefExpr for the "other" object.
   12504   RefBuilder OtherRef(Other, OtherRefType);
   12505 
   12506   // Builds the "this" pointer.
   12507   ThisBuilder This;
   12508 
   12509   // Assign base classes.
   12510   bool Invalid = false;
   12511   for (auto &Base : ClassDecl->bases()) {
   12512     // Form the assignment:
   12513     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
   12514     QualType BaseType = Base.getType().getUnqualifiedType();
   12515     if (!BaseType->isRecordType()) {
   12516       Invalid = true;
   12517       continue;
   12518     }
   12519 
   12520     CXXCastPath BasePath;
   12521     BasePath.push_back(&Base);
   12522 
   12523     // Construct the "from" expression, which is an implicit cast to the
   12524     // appropriately-qualified base type.
   12525     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
   12526                      VK_LValue, BasePath);
   12527 
   12528     // Dereference "this".
   12529     DerefBuilder DerefThis(This);
   12530     CastBuilder To(DerefThis,
   12531                    Context.getQualifiedType(
   12532                        BaseType, CopyAssignOperator->getMethodQualifiers()),
   12533                    VK_LValue, BasePath);
   12534 
   12535     // Build the copy.
   12536     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
   12537                                             To, From,
   12538                                             /*CopyingBaseSubobject=*/true,
   12539                                             /*Copying=*/true);
   12540     if (Copy.isInvalid()) {
   12541       CopyAssignOperator->setInvalidDecl();
   12542       return;
   12543     }
   12544 
   12545     // Success! Record the copy.
   12546     Statements.push_back(Copy.getAs<Expr>());
   12547   }
   12548 
   12549   // Assign non-static members.
   12550   for (auto *Field : ClassDecl->fields()) {
   12551     // FIXME: We should form some kind of AST representation for the implied
   12552     // memcpy in a union copy operation.
   12553     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
   12554       continue;
   12555 
   12556     if (Field->isInvalidDecl()) {
   12557       Invalid = true;
   12558       continue;
   12559     }
   12560 
   12561     // Check for members of reference type; we can't copy those.
   12562     if (Field->getType()->isReferenceType()) {
   12563       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
   12564         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
   12565       Diag(Field->getLocation(), diag::note_declared_at);
   12566       Invalid = true;
   12567       continue;
   12568     }
   12569 
   12570     // Check for members of const-qualified, non-class type.
   12571     QualType BaseType = Context.getBaseElementType(Field->getType());
   12572     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
   12573       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
   12574         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
   12575       Diag(Field->getLocation(), diag::note_declared_at);
   12576       Invalid = true;
   12577       continue;
   12578     }
   12579 
   12580     // Suppress assigning zero-width bitfields.
   12581     if (Field->isZeroLengthBitField(Context))
   12582       continue;
   12583 
   12584     QualType FieldType = Field->getType().getNonReferenceType();
   12585     if (FieldType->isIncompleteArrayType()) {
   12586       assert(ClassDecl->hasFlexibleArrayMember() &&
   12587              "Incomplete array type is not valid");
   12588       continue;
   12589     }
   12590 
   12591     // Build references to the field in the object we're copying from and to.
   12592     CXXScopeSpec SS; // Intentionally empty
   12593     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
   12594                               LookupMemberName);
   12595     MemberLookup.addDecl(Field);
   12596     MemberLookup.resolveKind();
   12597 
   12598     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
   12599 
   12600     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
   12601 
   12602     // Build the copy of this field.
   12603     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
   12604                                             To, From,
   12605                                             /*CopyingBaseSubobject=*/false,
   12606                                             /*Copying=*/true);
   12607     if (Copy.isInvalid()) {
   12608       CopyAssignOperator->setInvalidDecl();
   12609       return;
   12610     }
   12611 
   12612     // Success! Record the copy.
   12613     Statements.push_back(Copy.getAs<Stmt>());
   12614   }
   12615 
   12616   if (!Invalid) {
   12617     // Add a "return *this;"
   12618     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
   12619 
   12620     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
   12621     if (Return.isInvalid())
   12622       Invalid = true;
   12623     else
   12624       Statements.push_back(Return.getAs<Stmt>());
   12625   }
   12626 
   12627   if (Invalid) {
   12628     CopyAssignOperator->setInvalidDecl();
   12629     return;
   12630   }
   12631 
   12632   StmtResult Body;
   12633   {
   12634     CompoundScopeRAII CompoundScope(*this);
   12635     Body = ActOnCompoundStmt(Loc, Loc, Statements,
   12636                              /*isStmtExpr=*/false);
   12637     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
   12638   }
   12639   CopyAssignOperator->setBody(Body.getAs<Stmt>());
   12640   CopyAssignOperator->markUsed(Context);
   12641 
   12642   if (ASTMutationListener *L = getASTMutationListener()) {
   12643     L->CompletedImplicitDefinition(CopyAssignOperator);
   12644   }
   12645 }
   12646 
   12647 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
   12648   assert(ClassDecl->needsImplicitMoveAssignment());
   12649 
   12650   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
   12651   if (DSM.isAlreadyBeingDeclared())
   12652     return nullptr;
   12653 
   12654   // Note: The following rules are largely analoguous to the move
   12655   // constructor rules.
   12656 
   12657   QualType ArgType = Context.getTypeDeclType(ClassDecl);
   12658   if (Context.getLangOpts().OpenCLCPlusPlus)
   12659     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
   12660   QualType RetType = Context.getLValueReferenceType(ArgType);
   12661   ArgType = Context.getRValueReferenceType(ArgType);
   12662 
   12663   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   12664                                                      CXXMoveAssignment,
   12665                                                      false);
   12666 
   12667   //   An implicitly-declared move assignment operator is an inline public
   12668   //   member of its class.
   12669   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
   12670   SourceLocation ClassLoc = ClassDecl->getLocation();
   12671   DeclarationNameInfo NameInfo(Name, ClassLoc);
   12672   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
   12673       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
   12674       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
   12675       /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
   12676       SourceLocation());
   12677   MoveAssignment->setAccess(AS_public);
   12678   MoveAssignment->setDefaulted();
   12679   MoveAssignment->setImplicit();
   12680 
   12681   if (getLangOpts().CUDA) {
   12682     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
   12683                                             MoveAssignment,
   12684                                             /* ConstRHS */ false,
   12685                                             /* Diagnose */ false);
   12686   }
   12687 
   12688   // Build an exception specification pointing back at this member.
   12689   FunctionProtoType::ExtProtoInfo EPI =
   12690       getImplicitMethodEPI(*this, MoveAssignment);
   12691   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
   12692 
   12693   // Add the parameter to the operator.
   12694   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
   12695                                                ClassLoc, ClassLoc,
   12696                                                /*Id=*/nullptr, ArgType,
   12697                                                /*TInfo=*/nullptr, SC_None,
   12698                                                nullptr);
   12699   MoveAssignment->setParams(FromParam);
   12700 
   12701   MoveAssignment->setTrivial(
   12702     ClassDecl->needsOverloadResolutionForMoveAssignment()
   12703       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
   12704       : ClassDecl->hasTrivialMoveAssignment());
   12705 
   12706   // Note that we have added this copy-assignment operator.
   12707   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
   12708 
   12709   Scope *S = getScopeForContext(ClassDecl);
   12710   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
   12711 
   12712   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
   12713     ClassDecl->setImplicitMoveAssignmentIsDeleted();
   12714     SetDeclDeleted(MoveAssignment, ClassLoc);
   12715   }
   12716 
   12717   if (S)
   12718     PushOnScopeChains(MoveAssignment, S, false);
   12719   ClassDecl->addDecl(MoveAssignment);
   12720 
   12721   return MoveAssignment;
   12722 }
   12723 
   12724 /// Check if we're implicitly defining a move assignment operator for a class
   12725 /// with virtual bases. Such a move assignment might move-assign the virtual
   12726 /// base multiple times.
   12727 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
   12728                                                SourceLocation CurrentLocation) {
   12729   assert(!Class->isDependentContext() && "should not define dependent move");
   12730 
   12731   // Only a virtual base could get implicitly move-assigned multiple times.
   12732   // Only a non-trivial move assignment can observe this. We only want to
   12733   // diagnose if we implicitly define an assignment operator that assigns
   12734   // two base classes, both of which move-assign the same virtual base.
   12735   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
   12736       Class->getNumBases() < 2)
   12737     return;
   12738 
   12739   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
   12740   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
   12741   VBaseMap VBases;
   12742 
   12743   for (auto &BI : Class->bases()) {
   12744     Worklist.push_back(&BI);
   12745     while (!Worklist.empty()) {
   12746       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
   12747       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
   12748 
   12749       // If the base has no non-trivial move assignment operators,
   12750       // we don't care about moves from it.
   12751       if (!Base->hasNonTrivialMoveAssignment())
   12752         continue;
   12753 
   12754       // If there's nothing virtual here, skip it.
   12755       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
   12756         continue;
   12757 
   12758       // If we're not actually going to call a move assignment for this base,
   12759       // or the selected move assignment is trivial, skip it.
   12760       Sema::SpecialMemberOverloadResult SMOR =
   12761         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
   12762                               /*ConstArg*/false, /*VolatileArg*/false,
   12763                               /*RValueThis*/true, /*ConstThis*/false,
   12764                               /*VolatileThis*/false);
   12765       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
   12766           !SMOR.getMethod()->isMoveAssignmentOperator())
   12767         continue;
   12768 
   12769       if (BaseSpec->isVirtual()) {
   12770         // We're going to move-assign this virtual base, and its move
   12771         // assignment operator is not trivial. If this can happen for
   12772         // multiple distinct direct bases of Class, diagnose it. (If it
   12773         // only happens in one base, we'll diagnose it when synthesizing
   12774         // that base class's move assignment operator.)
   12775         CXXBaseSpecifier *&Existing =
   12776             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
   12777                 .first->second;
   12778         if (Existing && Existing != &BI) {
   12779           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
   12780             << Class << Base;
   12781           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
   12782               << (Base->getCanonicalDecl() ==
   12783                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
   12784               << Base << Existing->getType() << Existing->getSourceRange();
   12785           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
   12786               << (Base->getCanonicalDecl() ==
   12787                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
   12788               << Base << BI.getType() << BaseSpec->getSourceRange();
   12789 
   12790           // Only diagnose each vbase once.
   12791           Existing = nullptr;
   12792         }
   12793       } else {
   12794         // Only walk over bases that have defaulted move assignment operators.
   12795         // We assume that any user-provided move assignment operator handles
   12796         // the multiple-moves-of-vbase case itself somehow.
   12797         if (!SMOR.getMethod()->isDefaulted())
   12798           continue;
   12799 
   12800         // We're going to move the base classes of Base. Add them to the list.
   12801         for (auto &BI : Base->bases())
   12802           Worklist.push_back(&BI);
   12803       }
   12804     }
   12805   }
   12806 }
   12807 
   12808 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
   12809                                         CXXMethodDecl *MoveAssignOperator) {
   12810   assert((MoveAssignOperator->isDefaulted() &&
   12811           MoveAssignOperator->isOverloadedOperator() &&
   12812           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
   12813           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
   12814           !MoveAssignOperator->isDeleted()) &&
   12815          "DefineImplicitMoveAssignment called for wrong function");
   12816   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
   12817     return;
   12818 
   12819   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
   12820   if (ClassDecl->isInvalidDecl()) {
   12821     MoveAssignOperator->setInvalidDecl();
   12822     return;
   12823   }
   12824 
   12825   // C++0x [class.copy]p28:
   12826   //   The implicitly-defined or move assignment operator for a non-union class
   12827   //   X performs memberwise move assignment of its subobjects. The direct base
   12828   //   classes of X are assigned first, in the order of their declaration in the
   12829   //   base-specifier-list, and then the immediate non-static data members of X
   12830   //   are assigned, in the order in which they were declared in the class
   12831   //   definition.
   12832 
   12833   // Issue a warning if our implicit move assignment operator will move
   12834   // from a virtual base more than once.
   12835   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
   12836 
   12837   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
   12838 
   12839   // The exception specification is needed because we are defining the
   12840   // function.
   12841   ResolveExceptionSpec(CurrentLocation,
   12842                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
   12843 
   12844   // Add a context note for diagnostics produced after this point.
   12845   Scope.addContextNote(CurrentLocation);
   12846 
   12847   // The statements that form the synthesized function body.
   12848   SmallVector<Stmt*, 8> Statements;
   12849 
   12850   // The parameter for the "other" object, which we are move from.
   12851   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
   12852   QualType OtherRefType = Other->getType()->
   12853       getAs<RValueReferenceType>()->getPointeeType();
   12854 
   12855   // Our location for everything implicitly-generated.
   12856   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
   12857                            ? MoveAssignOperator->getEndLoc()
   12858                            : MoveAssignOperator->getLocation();
   12859 
   12860   // Builds a reference to the "other" object.
   12861   RefBuilder OtherRef(Other, OtherRefType);
   12862   // Cast to rvalue.
   12863   MoveCastBuilder MoveOther(OtherRef);
   12864 
   12865   // Builds the "this" pointer.
   12866   ThisBuilder This;
   12867 
   12868   // Assign base classes.
   12869   bool Invalid = false;
   12870   for (auto &Base : ClassDecl->bases()) {
   12871     // C++11 [class.copy]p28:
   12872     //   It is unspecified whether subobjects representing virtual base classes
   12873     //   are assigned more than once by the implicitly-defined copy assignment
   12874     //   operator.
   12875     // FIXME: Do not assign to a vbase that will be assigned by some other base
   12876     // class. For a move-assignment, this can result in the vbase being moved
   12877     // multiple times.
   12878 
   12879     // Form the assignment:
   12880     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
   12881     QualType BaseType = Base.getType().getUnqualifiedType();
   12882     if (!BaseType->isRecordType()) {
   12883       Invalid = true;
   12884       continue;
   12885     }
   12886 
   12887     CXXCastPath BasePath;
   12888     BasePath.push_back(&Base);
   12889 
   12890     // Construct the "from" expression, which is an implicit cast to the
   12891     // appropriately-qualified base type.
   12892     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
   12893 
   12894     // Dereference "this".
   12895     DerefBuilder DerefThis(This);
   12896 
   12897     // Implicitly cast "this" to the appropriately-qualified base type.
   12898     CastBuilder To(DerefThis,
   12899                    Context.getQualifiedType(
   12900                        BaseType, MoveAssignOperator->getMethodQualifiers()),
   12901                    VK_LValue, BasePath);
   12902 
   12903     // Build the move.
   12904     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
   12905                                             To, From,
   12906                                             /*CopyingBaseSubobject=*/true,
   12907                                             /*Copying=*/false);
   12908     if (Move.isInvalid()) {
   12909       MoveAssignOperator->setInvalidDecl();
   12910       return;
   12911     }
   12912 
   12913     // Success! Record the move.
   12914     Statements.push_back(Move.getAs<Expr>());
   12915   }
   12916 
   12917   // Assign non-static members.
   12918   for (auto *Field : ClassDecl->fields()) {
   12919     // FIXME: We should form some kind of AST representation for the implied
   12920     // memcpy in a union copy operation.
   12921     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
   12922       continue;
   12923 
   12924     if (Field->isInvalidDecl()) {
   12925       Invalid = true;
   12926       continue;
   12927     }
   12928 
   12929     // Check for members of reference type; we can't move those.
   12930     if (Field->getType()->isReferenceType()) {
   12931       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
   12932         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
   12933       Diag(Field->getLocation(), diag::note_declared_at);
   12934       Invalid = true;
   12935       continue;
   12936     }
   12937 
   12938     // Check for members of const-qualified, non-class type.
   12939     QualType BaseType = Context.getBaseElementType(Field->getType());
   12940     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
   12941       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
   12942         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
   12943       Diag(Field->getLocation(), diag::note_declared_at);
   12944       Invalid = true;
   12945       continue;
   12946     }
   12947 
   12948     // Suppress assigning zero-width bitfields.
   12949     if (Field->isZeroLengthBitField(Context))
   12950       continue;
   12951 
   12952     QualType FieldType = Field->getType().getNonReferenceType();
   12953     if (FieldType->isIncompleteArrayType()) {
   12954       assert(ClassDecl->hasFlexibleArrayMember() &&
   12955              "Incomplete array type is not valid");
   12956       continue;
   12957     }
   12958 
   12959     // Build references to the field in the object we're copying from and to.
   12960     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
   12961                               LookupMemberName);
   12962     MemberLookup.addDecl(Field);
   12963     MemberLookup.resolveKind();
   12964     MemberBuilder From(MoveOther, OtherRefType,
   12965                        /*IsArrow=*/false, MemberLookup);
   12966     MemberBuilder To(This, getCurrentThisType(),
   12967                      /*IsArrow=*/true, MemberLookup);
   12968 
   12969     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
   12970         "Member reference with rvalue base must be rvalue except for reference "
   12971         "members, which aren't allowed for move assignment.");
   12972 
   12973     // Build the move of this field.
   12974     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
   12975                                             To, From,
   12976                                             /*CopyingBaseSubobject=*/false,
   12977                                             /*Copying=*/false);
   12978     if (Move.isInvalid()) {
   12979       MoveAssignOperator->setInvalidDecl();
   12980       return;
   12981     }
   12982 
   12983     // Success! Record the copy.
   12984     Statements.push_back(Move.getAs<Stmt>());
   12985   }
   12986 
   12987   if (!Invalid) {
   12988     // Add a "return *this;"
   12989     ExprResult ThisObj =
   12990         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
   12991 
   12992     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
   12993     if (Return.isInvalid())
   12994       Invalid = true;
   12995     else
   12996       Statements.push_back(Return.getAs<Stmt>());
   12997   }
   12998 
   12999   if (Invalid) {
   13000     MoveAssignOperator->setInvalidDecl();
   13001     return;
   13002   }
   13003 
   13004   StmtResult Body;
   13005   {
   13006     CompoundScopeRAII CompoundScope(*this);
   13007     Body = ActOnCompoundStmt(Loc, Loc, Statements,
   13008                              /*isStmtExpr=*/false);
   13009     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
   13010   }
   13011   MoveAssignOperator->setBody(Body.getAs<Stmt>());
   13012   MoveAssignOperator->markUsed(Context);
   13013 
   13014   if (ASTMutationListener *L = getASTMutationListener()) {
   13015     L->CompletedImplicitDefinition(MoveAssignOperator);
   13016   }
   13017 }
   13018 
   13019 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
   13020                                                     CXXRecordDecl *ClassDecl) {
   13021   // C++ [class.copy]p4:
   13022   //   If the class definition does not explicitly declare a copy
   13023   //   constructor, one is declared implicitly.
   13024   assert(ClassDecl->needsImplicitCopyConstructor());
   13025 
   13026   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
   13027   if (DSM.isAlreadyBeingDeclared())
   13028     return nullptr;
   13029 
   13030   QualType ClassType = Context.getTypeDeclType(ClassDecl);
   13031   QualType ArgType = ClassType;
   13032   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
   13033   if (Const)
   13034     ArgType = ArgType.withConst();
   13035 
   13036   if (Context.getLangOpts().OpenCLCPlusPlus)
   13037     ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
   13038 
   13039   ArgType = Context.getLValueReferenceType(ArgType);
   13040 
   13041   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   13042                                                      CXXCopyConstructor,
   13043                                                      Const);
   13044 
   13045   DeclarationName Name
   13046     = Context.DeclarationNames.getCXXConstructorName(
   13047                                            Context.getCanonicalType(ClassType));
   13048   SourceLocation ClassLoc = ClassDecl->getLocation();
   13049   DeclarationNameInfo NameInfo(Name, ClassLoc);
   13050 
   13051   //   An implicitly-declared copy constructor is an inline public
   13052   //   member of its class.
   13053   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
   13054       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
   13055       ExplicitSpecifier(),
   13056       /*isInline=*/true,
   13057       /*isImplicitlyDeclared=*/true,
   13058       Constexpr ? CSK_constexpr : CSK_unspecified);
   13059   CopyConstructor->setAccess(AS_public);
   13060   CopyConstructor->setDefaulted();
   13061 
   13062   if (getLangOpts().CUDA) {
   13063     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
   13064                                             CopyConstructor,
   13065                                             /* ConstRHS */ Const,
   13066                                             /* Diagnose */ false);
   13067   }
   13068 
   13069   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
   13070 
   13071   // Add the parameter to the constructor.
   13072   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
   13073                                                ClassLoc, ClassLoc,
   13074                                                /*IdentifierInfo=*/nullptr,
   13075                                                ArgType, /*TInfo=*/nullptr,
   13076                                                SC_None, nullptr);
   13077   CopyConstructor->setParams(FromParam);
   13078 
   13079   CopyConstructor->setTrivial(
   13080       ClassDecl->needsOverloadResolutionForCopyConstructor()
   13081           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
   13082           : ClassDecl->hasTrivialCopyConstructor());
   13083 
   13084   CopyConstructor->setTrivialForCall(
   13085       ClassDecl->hasAttr<TrivialABIAttr>() ||
   13086       (ClassDecl->needsOverloadResolutionForCopyConstructor()
   13087            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
   13088              TAH_ConsiderTrivialABI)
   13089            : ClassDecl->hasTrivialCopyConstructorForCall()));
   13090 
   13091   // Note that we have declared this constructor.
   13092   ++getASTContext().NumImplicitCopyConstructorsDeclared;
   13093 
   13094   Scope *S = getScopeForContext(ClassDecl);
   13095   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
   13096 
   13097   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
   13098     ClassDecl->setImplicitCopyConstructorIsDeleted();
   13099     SetDeclDeleted(CopyConstructor, ClassLoc);
   13100   }
   13101 
   13102   if (S)
   13103     PushOnScopeChains(CopyConstructor, S, false);
   13104   ClassDecl->addDecl(CopyConstructor);
   13105 
   13106   return CopyConstructor;
   13107 }
   13108 
   13109 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
   13110                                          CXXConstructorDecl *CopyConstructor) {
   13111   assert((CopyConstructor->isDefaulted() &&
   13112           CopyConstructor->isCopyConstructor() &&
   13113           !CopyConstructor->doesThisDeclarationHaveABody() &&
   13114           !CopyConstructor->isDeleted()) &&
   13115          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
   13116   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
   13117     return;
   13118 
   13119   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
   13120   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
   13121 
   13122   SynthesizedFunctionScope Scope(*this, CopyConstructor);
   13123 
   13124   // The exception specification is needed because we are defining the
   13125   // function.
   13126   ResolveExceptionSpec(CurrentLocation,
   13127                        CopyConstructor->getType()->castAs<FunctionProtoType>());
   13128   MarkVTableUsed(CurrentLocation, ClassDecl);
   13129 
   13130   // Add a context note for diagnostics produced after this point.
   13131   Scope.addContextNote(CurrentLocation);
   13132 
   13133   // C++11 [class.copy]p7:
   13134   //   The [definition of an implicitly declared copy constructor] is
   13135   //   deprecated if the class has a user-declared copy assignment operator
   13136   //   or a user-declared destructor.
   13137   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
   13138     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
   13139 
   13140   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
   13141     CopyConstructor->setInvalidDecl();
   13142   }  else {
   13143     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
   13144                              ? CopyConstructor->getEndLoc()
   13145                              : CopyConstructor->getLocation();
   13146     Sema::CompoundScopeRAII CompoundScope(*this);
   13147     CopyConstructor->setBody(
   13148         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
   13149     CopyConstructor->markUsed(Context);
   13150   }
   13151 
   13152   if (ASTMutationListener *L = getASTMutationListener()) {
   13153     L->CompletedImplicitDefinition(CopyConstructor);
   13154   }
   13155 }
   13156 
   13157 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
   13158                                                     CXXRecordDecl *ClassDecl) {
   13159   assert(ClassDecl->needsImplicitMoveConstructor());
   13160 
   13161   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
   13162   if (DSM.isAlreadyBeingDeclared())
   13163     return nullptr;
   13164 
   13165   QualType ClassType = Context.getTypeDeclType(ClassDecl);
   13166 
   13167   QualType ArgType = ClassType;
   13168   if (Context.getLangOpts().OpenCLCPlusPlus)
   13169     ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
   13170   ArgType = Context.getRValueReferenceType(ArgType);
   13171 
   13172   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   13173                                                      CXXMoveConstructor,
   13174                                                      false);
   13175 
   13176   DeclarationName Name
   13177     = Context.DeclarationNames.getCXXConstructorName(
   13178                                            Context.getCanonicalType(ClassType));
   13179   SourceLocation ClassLoc = ClassDecl->getLocation();
   13180   DeclarationNameInfo NameInfo(Name, ClassLoc);
   13181 
   13182   // C++11 [class.copy]p11:
   13183   //   An implicitly-declared copy/move constructor is an inline public
   13184   //   member of its class.
   13185   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
   13186       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
   13187       ExplicitSpecifier(),
   13188       /*isInline=*/true,
   13189       /*isImplicitlyDeclared=*/true,
   13190       Constexpr ? CSK_constexpr : CSK_unspecified);
   13191   MoveConstructor->setAccess(AS_public);
   13192   MoveConstructor->setDefaulted();
   13193 
   13194   if (getLangOpts().CUDA) {
   13195     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
   13196                                             MoveConstructor,
   13197                                             /* ConstRHS */ false,
   13198                                             /* Diagnose */ false);
   13199   }
   13200 
   13201   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
   13202 
   13203   // Add the parameter to the constructor.
   13204   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
   13205                                                ClassLoc, ClassLoc,
   13206                                                /*IdentifierInfo=*/nullptr,
   13207                                                ArgType, /*TInfo=*/nullptr,
   13208                                                SC_None, nullptr);
   13209   MoveConstructor->setParams(FromParam);
   13210 
   13211   MoveConstructor->setTrivial(
   13212       ClassDecl->needsOverloadResolutionForMoveConstructor()
   13213           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
   13214           : ClassDecl->hasTrivialMoveConstructor());
   13215 
   13216   MoveConstructor->setTrivialForCall(
   13217       ClassDecl->hasAttr<TrivialABIAttr>() ||
   13218       (ClassDecl->needsOverloadResolutionForMoveConstructor()
   13219            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
   13220                                     TAH_ConsiderTrivialABI)
   13221            : ClassDecl->hasTrivialMoveConstructorForCall()));
   13222 
   13223   // Note that we have declared this constructor.
   13224   ++getASTContext().NumImplicitMoveConstructorsDeclared;
   13225 
   13226   Scope *S = getScopeForContext(ClassDecl);
   13227   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
   13228 
   13229   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
   13230     ClassDecl->setImplicitMoveConstructorIsDeleted();
   13231     SetDeclDeleted(MoveConstructor, ClassLoc);
   13232   }
   13233 
   13234   if (S)
   13235     PushOnScopeChains(MoveConstructor, S, false);
   13236   ClassDecl->addDecl(MoveConstructor);
   13237 
   13238   return MoveConstructor;
   13239 }
   13240 
   13241 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
   13242                                          CXXConstructorDecl *MoveConstructor) {
   13243   assert((MoveConstructor->isDefaulted() &&
   13244           MoveConstructor->isMoveConstructor() &&
   13245           !MoveConstructor->doesThisDeclarationHaveABody() &&
   13246           !MoveConstructor->isDeleted()) &&
   13247          "DefineImplicitMoveConstructor - call it for implicit move ctor");
   13248   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
   13249     return;
   13250 
   13251   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
   13252   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
   13253 
   13254   SynthesizedFunctionScope Scope(*this, MoveConstructor);
   13255 
   13256   // The exception specification is needed because we are defining the
   13257   // function.
   13258   ResolveExceptionSpec(CurrentLocation,
   13259                        MoveConstructor->getType()->castAs<FunctionProtoType>());
   13260   MarkVTableUsed(CurrentLocation, ClassDecl);
   13261 
   13262   // Add a context note for diagnostics produced after this point.
   13263   Scope.addContextNote(CurrentLocation);
   13264 
   13265   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
   13266     MoveConstructor->setInvalidDecl();
   13267   } else {
   13268     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
   13269                              ? MoveConstructor->getEndLoc()
   13270                              : MoveConstructor->getLocation();
   13271     Sema::CompoundScopeRAII CompoundScope(*this);
   13272     MoveConstructor->setBody(ActOnCompoundStmt(
   13273         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
   13274     MoveConstructor->markUsed(Context);
   13275   }
   13276 
   13277   if (ASTMutationListener *L = getASTMutationListener()) {
   13278     L->CompletedImplicitDefinition(MoveConstructor);
   13279   }
   13280 }
   13281 
   13282 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
   13283   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
   13284 }
   13285 
   13286 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
   13287                             SourceLocation CurrentLocation,
   13288                             CXXConversionDecl *Conv) {
   13289   SynthesizedFunctionScope Scope(*this, Conv);
   13290   assert(!Conv->getReturnType()->isUndeducedType());
   13291 
   13292   CXXRecordDecl *Lambda = Conv->getParent();
   13293   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
   13294   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
   13295 
   13296   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
   13297     CallOp = InstantiateFunctionDeclaration(
   13298         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
   13299     if (!CallOp)
   13300       return;
   13301 
   13302     Invoker = InstantiateFunctionDeclaration(
   13303         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
   13304     if (!Invoker)
   13305       return;
   13306   }
   13307 
   13308   if (CallOp->isInvalidDecl())
   13309     return;
   13310 
   13311   // Mark the call operator referenced (and add to pending instantiations
   13312   // if necessary).
   13313   // For both the conversion and static-invoker template specializations
   13314   // we construct their body's in this function, so no need to add them
   13315   // to the PendingInstantiations.
   13316   MarkFunctionReferenced(CurrentLocation, CallOp);
   13317 
   13318   // Fill in the __invoke function with a dummy implementation. IR generation
   13319   // will fill in the actual details. Update its type in case it contained
   13320   // an 'auto'.
   13321   Invoker->markUsed(Context);
   13322   Invoker->setReferenced();
   13323   Invoker->setType(Conv->getReturnType()->getPointeeType());
   13324   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
   13325 
   13326   // Construct the body of the conversion function { return __invoke; }.
   13327   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
   13328                                        VK_LValue, Conv->getLocation());
   13329   assert(FunctionRef && "Can't refer to __invoke function?");
   13330   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
   13331   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
   13332                                      Conv->getLocation()));
   13333   Conv->markUsed(Context);
   13334   Conv->setReferenced();
   13335 
   13336   if (ASTMutationListener *L = getASTMutationListener()) {
   13337     L->CompletedImplicitDefinition(Conv);
   13338     L->CompletedImplicitDefinition(Invoker);
   13339   }
   13340 }
   13341 
   13342 
   13343 
   13344 void Sema::DefineImplicitLambdaToBlockPointerConversion(
   13345        SourceLocation CurrentLocation,
   13346        CXXConversionDecl *Conv)
   13347 {
   13348   assert(!Conv->getParent()->isGenericLambda());
   13349 
   13350   SynthesizedFunctionScope Scope(*this, Conv);
   13351 
   13352   // Copy-initialize the lambda object as needed to capture it.
   13353   Expr *This = ActOnCXXThis(CurrentLocation).get();
   13354   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
   13355 
   13356   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
   13357                                                         Conv->getLocation(),
   13358                                                         Conv, DerefThis);
   13359 
   13360   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
   13361   // behavior.  Note that only the general conversion function does this
   13362   // (since it's unusable otherwise); in the case where we inline the
   13363   // block literal, it has block literal lifetime semantics.
   13364   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
   13365     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
   13366                                           CK_CopyAndAutoreleaseBlockObject,
   13367                                           BuildBlock.get(), nullptr, VK_RValue);
   13368 
   13369   if (BuildBlock.isInvalid()) {
   13370     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
   13371     Conv->setInvalidDecl();
   13372     return;
   13373   }
   13374 
   13375   // Create the return statement that returns the block from the conversion
   13376   // function.
   13377   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
   13378   if (Return.isInvalid()) {
   13379     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
   13380     Conv->setInvalidDecl();
   13381     return;
   13382   }
   13383 
   13384   // Set the body of the conversion function.
   13385   Stmt *ReturnS = Return.get();
   13386   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
   13387                                      Conv->getLocation()));
   13388   Conv->markUsed(Context);
   13389 
   13390   // We're done; notify the mutation listener, if any.
   13391   if (ASTMutationListener *L = getASTMutationListener()) {
   13392     L->CompletedImplicitDefinition(Conv);
   13393   }
   13394 }
   13395 
   13396 /// Determine whether the given list arguments contains exactly one
   13397 /// "real" (non-default) argument.
   13398 static bool hasOneRealArgument(MultiExprArg Args) {
   13399   switch (Args.size()) {
   13400   case 0:
   13401     return false;
   13402 
   13403   default:
   13404     if (!Args[1]->isDefaultArgument())
   13405       return false;
   13406 
   13407     LLVM_FALLTHROUGH;
   13408   case 1:
   13409     return !Args[0]->isDefaultArgument();
   13410   }
   13411 
   13412   return false;
   13413 }
   13414 
   13415 ExprResult
   13416 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   13417                             NamedDecl *FoundDecl,
   13418                             CXXConstructorDecl *Constructor,
   13419                             MultiExprArg ExprArgs,
   13420                             bool HadMultipleCandidates,
   13421                             bool IsListInitialization,
   13422                             bool IsStdInitListInitialization,
   13423                             bool RequiresZeroInit,
   13424                             unsigned ConstructKind,
   13425                             SourceRange ParenRange) {
   13426   bool Elidable = false;
   13427 
   13428   // C++0x [class.copy]p34:
   13429   //   When certain criteria are met, an implementation is allowed to
   13430   //   omit the copy/move construction of a class object, even if the
   13431   //   copy/move constructor and/or destructor for the object have
   13432   //   side effects. [...]
   13433   //     - when a temporary class object that has not been bound to a
   13434   //       reference (12.2) would be copied/moved to a class object
   13435   //       with the same cv-unqualified type, the copy/move operation
   13436   //       can be omitted by constructing the temporary object
   13437   //       directly into the target of the omitted copy/move
   13438   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
   13439       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
   13440     Expr *SubExpr = ExprArgs[0];
   13441     Elidable = SubExpr->isTemporaryObject(
   13442         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
   13443   }
   13444 
   13445   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
   13446                                FoundDecl, Constructor,
   13447                                Elidable, ExprArgs, HadMultipleCandidates,
   13448                                IsListInitialization,
   13449                                IsStdInitListInitialization, RequiresZeroInit,
   13450                                ConstructKind, ParenRange);
   13451 }
   13452 
   13453 ExprResult
   13454 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   13455                             NamedDecl *FoundDecl,
   13456                             CXXConstructorDecl *Constructor,
   13457                             bool Elidable,
   13458                             MultiExprArg ExprArgs,
   13459                             bool HadMultipleCandidates,
   13460                             bool IsListInitialization,
   13461                             bool IsStdInitListInitialization,
   13462                             bool RequiresZeroInit,
   13463                             unsigned ConstructKind,
   13464                             SourceRange ParenRange) {
   13465   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
   13466     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
   13467     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
   13468       return ExprError();
   13469   }
   13470 
   13471   return BuildCXXConstructExpr(
   13472       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
   13473       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
   13474       RequiresZeroInit, ConstructKind, ParenRange);
   13475 }
   13476 
   13477 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
   13478 /// including handling of its default argument expressions.
   13479 ExprResult
   13480 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   13481                             CXXConstructorDecl *Constructor,
   13482                             bool Elidable,
   13483                             MultiExprArg ExprArgs,
   13484                             bool HadMultipleCandidates,
   13485                             bool IsListInitialization,
   13486                             bool IsStdInitListInitialization,
   13487                             bool RequiresZeroInit,
   13488                             unsigned ConstructKind,
   13489                             SourceRange ParenRange) {
   13490   assert(declaresSameEntity(
   13491              Constructor->getParent(),
   13492              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
   13493          "given constructor for wrong type");
   13494   MarkFunctionReferenced(ConstructLoc, Constructor);
   13495   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
   13496     return ExprError();
   13497 
   13498   return CXXConstructExpr::Create(
   13499       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
   13500       ExprArgs, HadMultipleCandidates, IsListInitialization,
   13501       IsStdInitListInitialization, RequiresZeroInit,
   13502       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
   13503       ParenRange);
   13504 }
   13505 
   13506 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
   13507   assert(Field->hasInClassInitializer());
   13508 
   13509   // If we already have the in-class initializer nothing needs to be done.
   13510   if (Field->getInClassInitializer())
   13511     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
   13512 
   13513   // If we might have already tried and failed to instantiate, don't try again.
   13514   if (Field->isInvalidDecl())
   13515     return ExprError();
   13516 
   13517   // Maybe we haven't instantiated the in-class initializer. Go check the
   13518   // pattern FieldDecl to see if it has one.
   13519   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
   13520 
   13521   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
   13522     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
   13523     DeclContext::lookup_result Lookup =
   13524         ClassPattern->lookup(Field->getDeclName());
   13525 
   13526     // Lookup can return at most two results: the pattern for the field, or the
   13527     // injected class name of the parent record. No other member can have the
   13528     // same name as the field.
   13529     // In modules mode, lookup can return multiple results (coming from
   13530     // different modules).
   13531     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
   13532            "more than two lookup results for field name");
   13533     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
   13534     if (!Pattern) {
   13535       assert(isa<CXXRecordDecl>(Lookup[0]) &&
   13536              "cannot have other non-field member with same name");
   13537       for (auto L : Lookup)
   13538         if (isa<FieldDecl>(L)) {
   13539           Pattern = cast<FieldDecl>(L);
   13540           break;
   13541         }
   13542       assert(Pattern && "We must have set the Pattern!");
   13543     }
   13544 
   13545     if (!Pattern->hasInClassInitializer() ||
   13546         InstantiateInClassInitializer(Loc, Field, Pattern,
   13547                                       getTemplateInstantiationArgs(Field))) {
   13548       // Don't diagnose this again.
   13549       Field->setInvalidDecl();
   13550       return ExprError();
   13551     }
   13552     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
   13553   }
   13554 
   13555   // DR1351:
   13556   //   If the brace-or-equal-initializer of a non-static data member
   13557   //   invokes a defaulted default constructor of its class or of an
   13558   //   enclosing class in a potentially evaluated subexpression, the
   13559   //   program is ill-formed.
   13560   //
   13561   // This resolution is unworkable: the exception specification of the
   13562   // default constructor can be needed in an unevaluated context, in
   13563   // particular, in the operand of a noexcept-expression, and we can be
   13564   // unable to compute an exception specification for an enclosed class.
   13565   //
   13566   // Any attempt to resolve the exception specification of a defaulted default
   13567   // constructor before the initializer is lexically complete will ultimately
   13568   // come here at which point we can diagnose it.
   13569   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
   13570   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
   13571       << OutermostClass << Field;
   13572   Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
   13573   // Recover by marking the field invalid, unless we're in a SFINAE context.
   13574   if (!isSFINAEContext())
   13575     Field->setInvalidDecl();
   13576   return ExprError();
   13577 }
   13578 
   13579 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
   13580   if (VD->isInvalidDecl()) return;
   13581 
   13582   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
   13583   if (ClassDecl->isInvalidDecl()) return;
   13584   if (ClassDecl->hasIrrelevantDestructor()) return;
   13585   if (ClassDecl->isDependentContext()) return;
   13586 
   13587   if (VD->isNoDestroy(getASTContext()))
   13588     return;
   13589 
   13590   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
   13591 
   13592   // If this is an array, we'll require the destructor during initialization, so
   13593   // we can skip over this. We still want to emit exit-time destructor warnings
   13594   // though.
   13595   if (!VD->getType()->isArrayType()) {
   13596     MarkFunctionReferenced(VD->getLocation(), Destructor);
   13597     CheckDestructorAccess(VD->getLocation(), Destructor,
   13598                           PDiag(diag::err_access_dtor_var)
   13599                               << VD->getDeclName() << VD->getType());
   13600     DiagnoseUseOfDecl(Destructor, VD->getLocation());
   13601   }
   13602 
   13603   if (Destructor->isTrivial()) return;
   13604 
   13605   // If the destructor is constexpr, check whether the variable has constant
   13606   // destruction now.
   13607   if (Destructor->isConstexpr() && VD->getInit() &&
   13608       !VD->getInit()->isValueDependent() && VD->evaluateValue()) {
   13609     SmallVector<PartialDiagnosticAt, 8> Notes;
   13610     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) {
   13611       Diag(VD->getLocation(),
   13612            diag::err_constexpr_var_requires_const_destruction) << VD;
   13613       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
   13614         Diag(Notes[I].first, Notes[I].second);
   13615     }
   13616   }
   13617 
   13618   if (!VD->hasGlobalStorage()) return;
   13619 
   13620   // Emit warning for non-trivial dtor in global scope (a real global,
   13621   // class-static, function-static).
   13622   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
   13623 
   13624   // TODO: this should be re-enabled for static locals by !CXAAtExit
   13625   if (!VD->isStaticLocal())
   13626     Diag(VD->getLocation(), diag::warn_global_destructor);
   13627 }
   13628 
   13629 /// Given a constructor and the set of arguments provided for the
   13630 /// constructor, convert the arguments and add any required default arguments
   13631 /// to form a proper call to this constructor.
   13632 ///
   13633 /// \returns true if an error occurred, false otherwise.
   13634 bool
   13635 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
   13636                               MultiExprArg ArgsPtr,
   13637                               SourceLocation Loc,
   13638                               SmallVectorImpl<Expr*> &ConvertedArgs,
   13639                               bool AllowExplicit,
   13640                               bool IsListInitialization) {
   13641   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
   13642   unsigned NumArgs = ArgsPtr.size();
   13643   Expr **Args = ArgsPtr.data();
   13644 
   13645   const FunctionProtoType *Proto
   13646     = Constructor->getType()->getAs<FunctionProtoType>();
   13647   assert(Proto && "Constructor without a prototype?");
   13648   unsigned NumParams = Proto->getNumParams();
   13649 
   13650   // If too few arguments are available, we'll fill in the rest with defaults.
   13651   if (NumArgs < NumParams)
   13652     ConvertedArgs.reserve(NumParams);
   13653   else
   13654     ConvertedArgs.reserve(NumArgs);
   13655 
   13656   VariadicCallType CallType =
   13657     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
   13658   SmallVector<Expr *, 8> AllArgs;
   13659   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
   13660                                         Proto, 0,
   13661                                         llvm::makeArrayRef(Args, NumArgs),
   13662                                         AllArgs,
   13663                                         CallType, AllowExplicit,
   13664                                         IsListInitialization);
   13665   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
   13666 
   13667   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
   13668 
   13669   CheckConstructorCall(Constructor,
   13670                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
   13671                        Proto, Loc);
   13672 
   13673   return Invalid;
   13674 }
   13675 
   13676 static inline bool
   13677 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
   13678                                        const FunctionDecl *FnDecl) {
   13679   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
   13680   if (isa<NamespaceDecl>(DC)) {
   13681     return SemaRef.Diag(FnDecl->getLocation(),
   13682                         diag::err_operator_new_delete_declared_in_namespace)
   13683       << FnDecl->getDeclName();
   13684   }
   13685 
   13686   if (isa<TranslationUnitDecl>(DC) &&
   13687       FnDecl->getStorageClass() == SC_Static) {
   13688     return SemaRef.Diag(FnDecl->getLocation(),
   13689                         diag::err_operator_new_delete_declared_static)
   13690       << FnDecl->getDeclName();
   13691   }
   13692 
   13693   return false;
   13694 }
   13695 
   13696 static QualType
   13697 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
   13698   QualType QTy = PtrTy->getPointeeType();
   13699   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
   13700   return SemaRef.Context.getPointerType(QTy);
   13701 }
   13702 
   13703 static inline bool
   13704 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
   13705                             CanQualType ExpectedResultType,
   13706                             CanQualType ExpectedFirstParamType,
   13707                             unsigned DependentParamTypeDiag,
   13708                             unsigned InvalidParamTypeDiag) {
   13709   QualType ResultType =
   13710       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
   13711 
   13712   // Check that the result type is not dependent.
   13713   if (ResultType->isDependentType())
   13714     return SemaRef.Diag(FnDecl->getLocation(),
   13715                         diag::err_operator_new_delete_dependent_result_type)
   13716     << FnDecl->getDeclName() << ExpectedResultType;
   13717 
   13718   // The operator is valid on any address space for OpenCL.
   13719   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
   13720     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
   13721       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
   13722     }
   13723   }
   13724 
   13725   // Check that the result type is what we expect.
   13726   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
   13727     return SemaRef.Diag(FnDecl->getLocation(),
   13728                         diag::err_operator_new_delete_invalid_result_type)
   13729     << FnDecl->getDeclName() << ExpectedResultType;
   13730 
   13731   // A function template must have at least 2 parameters.
   13732   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
   13733     return SemaRef.Diag(FnDecl->getLocation(),
   13734                       diag::err_operator_new_delete_template_too_few_parameters)
   13735         << FnDecl->getDeclName();
   13736 
   13737   // The function decl must have at least 1 parameter.
   13738   if (FnDecl->getNumParams() == 0)
   13739     return SemaRef.Diag(FnDecl->getLocation(),
   13740                         diag::err_operator_new_delete_too_few_parameters)
   13741       << FnDecl->getDeclName();
   13742 
   13743   // Check the first parameter type is not dependent.
   13744   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
   13745   if (FirstParamType->isDependentType())
   13746     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
   13747       << FnDecl->getDeclName() << ExpectedFirstParamType;
   13748 
   13749   // Check that the first parameter type is what we expect.
   13750   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
   13751     // The operator is valid on any address space for OpenCL.
   13752     if (auto *PtrTy =
   13753             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
   13754       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
   13755     }
   13756   }
   13757   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
   13758       ExpectedFirstParamType)
   13759     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
   13760     << FnDecl->getDeclName() << ExpectedFirstParamType;
   13761 
   13762   return false;
   13763 }
   13764 
   13765 static bool
   13766 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
   13767   // C++ [basic.stc.dynamic.allocation]p1:
   13768   //   A program is ill-formed if an allocation function is declared in a
   13769   //   namespace scope other than global scope or declared static in global
   13770   //   scope.
   13771   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
   13772     return true;
   13773 
   13774   CanQualType SizeTy =
   13775     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
   13776 
   13777   // C++ [basic.stc.dynamic.allocation]p1:
   13778   //  The return type shall be void*. The first parameter shall have type
   13779   //  std::size_t.
   13780   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
   13781                                   SizeTy,
   13782                                   diag::err_operator_new_dependent_param_type,
   13783                                   diag::err_operator_new_param_type))
   13784     return true;
   13785 
   13786   // C++ [basic.stc.dynamic.allocation]p1:
   13787   //  The first parameter shall not have an associated default argument.
   13788   if (FnDecl->getParamDecl(0)->hasDefaultArg())
   13789     return SemaRef.Diag(FnDecl->getLocation(),
   13790                         diag::err_operator_new_default_arg)
   13791       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
   13792 
   13793   return false;
   13794 }
   13795 
   13796 static bool
   13797 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
   13798   // C++ [basic.stc.dynamic.deallocation]p1:
   13799   //   A program is ill-formed if deallocation functions are declared in a
   13800   //   namespace scope other than global scope or declared static in global
   13801   //   scope.
   13802   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
   13803     return true;
   13804 
   13805   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
   13806 
   13807   // C++ P0722:
   13808   //   Within a class C, the first parameter of a destroying operator delete
   13809   //   shall be of type C *. The first parameter of any other deallocation
   13810   //   function shall be of type void *.
   13811   CanQualType ExpectedFirstParamType =
   13812       MD && MD->isDestroyingOperatorDelete()
   13813           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
   13814                 SemaRef.Context.getRecordType(MD->getParent())))
   13815           : SemaRef.Context.VoidPtrTy;
   13816 
   13817   // C++ [basic.stc.dynamic.deallocation]p2:
   13818   //   Each deallocation function shall return void
   13819   if (CheckOperatorNewDeleteTypes(
   13820           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
   13821           diag::err_operator_delete_dependent_param_type,
   13822           diag::err_operator_delete_param_type))
   13823     return true;
   13824 
   13825   // C++ P0722:
   13826   //   A destroying operator delete shall be a usual deallocation function.
   13827   if (MD && !MD->getParent()->isDependentContext() &&
   13828       MD->isDestroyingOperatorDelete() &&
   13829       !SemaRef.isUsualDeallocationFunction(MD)) {
   13830     SemaRef.Diag(MD->getLocation(),
   13831                  diag::err_destroying_operator_delete_not_usual);
   13832     return true;
   13833   }
   13834 
   13835   return false;
   13836 }
   13837 
   13838 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
   13839 /// of this overloaded operator is well-formed. If so, returns false;
   13840 /// otherwise, emits appropriate diagnostics and returns true.
   13841 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
   13842   assert(FnDecl && FnDecl->isOverloadedOperator() &&
   13843          "Expected an overloaded operator declaration");
   13844 
   13845   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
   13846 
   13847   // C++ [over.oper]p5:
   13848   //   The allocation and deallocation functions, operator new,
   13849   //   operator new[], operator delete and operator delete[], are
   13850   //   described completely in 3.7.3. The attributes and restrictions
   13851   //   found in the rest of this subclause do not apply to them unless
   13852   //   explicitly stated in 3.7.3.
   13853   if (Op == OO_Delete || Op == OO_Array_Delete)
   13854     return CheckOperatorDeleteDeclaration(*this, FnDecl);
   13855 
   13856   if (Op == OO_New || Op == OO_Array_New)
   13857     return CheckOperatorNewDeclaration(*this, FnDecl);
   13858 
   13859   // C++ [over.oper]p6:
   13860   //   An operator function shall either be a non-static member
   13861   //   function or be a non-member function and have at least one
   13862   //   parameter whose type is a class, a reference to a class, an
   13863   //   enumeration, or a reference to an enumeration.
   13864   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
   13865     if (MethodDecl->isStatic())
   13866       return Diag(FnDecl->getLocation(),
   13867                   diag::err_operator_overload_static) << FnDecl->getDeclName();
   13868   } else {
   13869     bool ClassOrEnumParam = false;
   13870     for (auto Param : FnDecl->parameters()) {
   13871       QualType ParamType = Param->getType().getNonReferenceType();
   13872       if (ParamType->isDependentType() || ParamType->isRecordType() ||
   13873           ParamType->isEnumeralType()) {
   13874         ClassOrEnumParam = true;
   13875         break;
   13876       }
   13877     }
   13878 
   13879     if (!ClassOrEnumParam)
   13880       return Diag(FnDecl->getLocation(),
   13881                   diag::err_operator_overload_needs_class_or_enum)
   13882         << FnDecl->getDeclName();
   13883   }
   13884 
   13885   // C++ [over.oper]p8:
   13886   //   An operator function cannot have default arguments (8.3.6),
   13887   //   except where explicitly stated below.
   13888   //
   13889   // Only the function-call operator allows default arguments
   13890   // (C++ [over.call]p1).
   13891   if (Op != OO_Call) {
   13892     for (auto Param : FnDecl->parameters()) {
   13893       if (Param->hasDefaultArg())
   13894         return Diag(Param->getLocation(),
   13895                     diag::err_operator_overload_default_arg)
   13896           << FnDecl->getDeclName() << Param->getDefaultArgRange();
   13897     }
   13898   }
   13899 
   13900   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
   13901     { false, false, false }
   13902 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
   13903     , { Unary, Binary, MemberOnly }
   13904 #include "clang/Basic/OperatorKinds.def"
   13905   };
   13906 
   13907   bool CanBeUnaryOperator = OperatorUses[Op][0];
   13908   bool CanBeBinaryOperator = OperatorUses[Op][1];
   13909   bool MustBeMemberOperator = OperatorUses[Op][2];
   13910 
   13911   // C++ [over.oper]p8:
   13912   //   [...] Operator functions cannot have more or fewer parameters
   13913   //   than the number required for the corresponding operator, as
   13914   //   described in the rest of this subclause.
   13915   unsigned NumParams = FnDecl->getNumParams()
   13916                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
   13917   if (Op != OO_Call &&
   13918       ((NumParams == 1 && !CanBeUnaryOperator) ||
   13919        (NumParams == 2 && !CanBeBinaryOperator) ||
   13920        (NumParams < 1) || (NumParams > 2))) {
   13921     // We have the wrong number of parameters.
   13922     unsigned ErrorKind;
   13923     if (CanBeUnaryOperator && CanBeBinaryOperator) {
   13924       ErrorKind = 2;  // 2 -> unary or binary.
   13925     } else if (CanBeUnaryOperator) {
   13926       ErrorKind = 0;  // 0 -> unary
   13927     } else {
   13928       assert(CanBeBinaryOperator &&
   13929              "All non-call overloaded operators are unary or binary!");
   13930       ErrorKind = 1;  // 1 -> binary
   13931     }
   13932 
   13933     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
   13934       << FnDecl->getDeclName() << NumParams << ErrorKind;
   13935   }
   13936 
   13937   // Overloaded operators other than operator() cannot be variadic.
   13938   if (Op != OO_Call &&
   13939       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
   13940     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
   13941       << FnDecl->getDeclName();
   13942   }
   13943 
   13944   // Some operators must be non-static member functions.
   13945   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
   13946     return Diag(FnDecl->getLocation(),
   13947                 diag::err_operator_overload_must_be_member)
   13948       << FnDecl->getDeclName();
   13949   }
   13950 
   13951   // C++ [over.inc]p1:
   13952   //   The user-defined function called operator++ implements the
   13953   //   prefix and postfix ++ operator. If this function is a member
   13954   //   function with no parameters, or a non-member function with one
   13955   //   parameter of class or enumeration type, it defines the prefix
   13956   //   increment operator ++ for objects of that type. If the function
   13957   //   is a member function with one parameter (which shall be of type
   13958   //   int) or a non-member function with two parameters (the second
   13959   //   of which shall be of type int), it defines the postfix
   13960   //   increment operator ++ for objects of that type.
   13961   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
   13962     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
   13963     QualType ParamType = LastParam->getType();
   13964 
   13965     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
   13966         !ParamType->isDependentType())
   13967       return Diag(LastParam->getLocation(),
   13968                   diag::err_operator_overload_post_incdec_must_be_int)
   13969         << LastParam->getType() << (Op == OO_MinusMinus);
   13970   }
   13971 
   13972   return false;
   13973 }
   13974 
   13975 static bool
   13976 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
   13977                                           FunctionTemplateDecl *TpDecl) {
   13978   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
   13979 
   13980   // Must have one or two template parameters.
   13981   if (TemplateParams->size() == 1) {
   13982     NonTypeTemplateParmDecl *PmDecl =
   13983         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
   13984 
   13985     // The template parameter must be a char parameter pack.
   13986     if (PmDecl && PmDecl->isTemplateParameterPack() &&
   13987         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
   13988       return false;
   13989 
   13990   } else if (TemplateParams->size() == 2) {
   13991     TemplateTypeParmDecl *PmType =
   13992         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
   13993     NonTypeTemplateParmDecl *PmArgs =
   13994         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
   13995 
   13996     // The second template parameter must be a parameter pack with the
   13997     // first template parameter as its type.
   13998     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
   13999         PmArgs->isTemplateParameterPack()) {
   14000       const TemplateTypeParmType *TArgs =
   14001           PmArgs->getType()->getAs<TemplateTypeParmType>();
   14002       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
   14003           TArgs->getIndex() == PmType->getIndex()) {
   14004         if (!SemaRef.inTemplateInstantiation())
   14005           SemaRef.Diag(TpDecl->getLocation(),
   14006                        diag::ext_string_literal_operator_template);
   14007         return false;
   14008       }
   14009     }
   14010   }
   14011 
   14012   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
   14013                diag::err_literal_operator_template)
   14014       << TpDecl->getTemplateParameters()->getSourceRange();
   14015   return true;
   14016 }
   14017 
   14018 /// CheckLiteralOperatorDeclaration - Check whether the declaration
   14019 /// of this literal operator function is well-formed. If so, returns
   14020 /// false; otherwise, emits appropriate diagnostics and returns true.
   14021 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
   14022   if (isa<CXXMethodDecl>(FnDecl)) {
   14023     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
   14024       << FnDecl->getDeclName();
   14025     return true;
   14026   }
   14027 
   14028   if (FnDecl->isExternC()) {
   14029     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
   14030     if (const LinkageSpecDecl *LSD =
   14031             FnDecl->getDeclContext()->getExternCContext())
   14032       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
   14033     return true;
   14034   }
   14035 
   14036   // This might be the definition of a literal operator template.
   14037   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
   14038 
   14039   // This might be a specialization of a literal operator template.
   14040   if (!TpDecl)
   14041     TpDecl = FnDecl->getPrimaryTemplate();
   14042 
   14043   // template <char...> type operator "" name() and
   14044   // template <class T, T...> type operator "" name() are the only valid
   14045   // template signatures, and the only valid signatures with no parameters.
   14046   if (TpDecl) {
   14047     if (FnDecl->param_size() != 0) {
   14048       Diag(FnDecl->getLocation(),
   14049            diag::err_literal_operator_template_with_params);
   14050       return true;
   14051     }
   14052 
   14053     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
   14054       return true;
   14055 
   14056   } else if (FnDecl->param_size() == 1) {
   14057     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
   14058 
   14059     QualType ParamType = Param->getType().getUnqualifiedType();
   14060 
   14061     // Only unsigned long long int, long double, any character type, and const
   14062     // char * are allowed as the only parameters.
   14063     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
   14064         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
   14065         Context.hasSameType(ParamType, Context.CharTy) ||
   14066         Context.hasSameType(ParamType, Context.WideCharTy) ||
   14067         Context.hasSameType(ParamType, Context.Char8Ty) ||
   14068         Context.hasSameType(ParamType, Context.Char16Ty) ||
   14069         Context.hasSameType(ParamType, Context.Char32Ty)) {
   14070     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
   14071       QualType InnerType = Ptr->getPointeeType();
   14072 
   14073       // Pointer parameter must be a const char *.
   14074       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
   14075                                 Context.CharTy) &&
   14076             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
   14077         Diag(Param->getSourceRange().getBegin(),
   14078              diag::err_literal_operator_param)
   14079             << ParamType << "'const char *'" << Param->getSourceRange();
   14080         return true;
   14081       }
   14082 
   14083     } else if (ParamType->isRealFloatingType()) {
   14084       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
   14085           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
   14086       return true;
   14087 
   14088     } else if (ParamType->isIntegerType()) {
   14089       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
   14090           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
   14091       return true;
   14092 
   14093     } else {
   14094       Diag(Param->getSourceRange().getBegin(),
   14095            diag::err_literal_operator_invalid_param)
   14096           << ParamType << Param->getSourceRange();
   14097       return true;
   14098     }
   14099 
   14100   } else if (FnDecl->param_size() == 2) {
   14101     FunctionDecl::param_iterator Param = FnDecl->param_begin();
   14102 
   14103     // First, verify that the first parameter is correct.
   14104 
   14105     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
   14106 
   14107     // Two parameter function must have a pointer to const as a
   14108     // first parameter; let's strip those qualifiers.
   14109     const PointerType *PT = FirstParamType->getAs<PointerType>();
   14110 
   14111     if (!PT) {
   14112       Diag((*Param)->getSourceRange().getBegin(),
   14113            diag::err_literal_operator_param)
   14114           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
   14115       return true;
   14116     }
   14117 
   14118     QualType PointeeType = PT->getPointeeType();
   14119     // First parameter must be const
   14120     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
   14121       Diag((*Param)->getSourceRange().getBegin(),
   14122            diag::err_literal_operator_param)
   14123           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
   14124       return true;
   14125     }
   14126 
   14127     QualType InnerType = PointeeType.getUnqualifiedType();
   14128     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
   14129     // const char32_t* are allowed as the first parameter to a two-parameter
   14130     // function
   14131     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
   14132           Context.hasSameType(InnerType, Context.WideCharTy) ||
   14133           Context.hasSameType(InnerType, Context.Char8Ty) ||
   14134           Context.hasSameType(InnerType, Context.Char16Ty) ||
   14135           Context.hasSameType(InnerType, Context.Char32Ty))) {
   14136       Diag((*Param)->getSourceRange().getBegin(),
   14137            diag::err_literal_operator_param)
   14138           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
   14139       return true;
   14140     }
   14141 
   14142     // Move on to the second and final parameter.
   14143     ++Param;
   14144 
   14145     // The second parameter must be a std::size_t.
   14146     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
   14147     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
   14148       Diag((*Param)->getSourceRange().getBegin(),
   14149            diag::err_literal_operator_param)
   14150           << SecondParamType << Context.getSizeType()
   14151           << (*Param)->getSourceRange();
   14152       return true;
   14153     }
   14154   } else {
   14155     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
   14156     return true;
   14157   }
   14158 
   14159   // Parameters are good.
   14160 
   14161   // A parameter-declaration-clause containing a default argument is not
   14162   // equivalent to any of the permitted forms.
   14163   for (auto Param : FnDecl->parameters()) {
   14164     if (Param->hasDefaultArg()) {
   14165       Diag(Param->getDefaultArgRange().getBegin(),
   14166            diag::err_literal_operator_default_argument)
   14167         << Param->getDefaultArgRange();
   14168       break;
   14169     }
   14170   }
   14171 
   14172   StringRef LiteralName
   14173     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
   14174   if (LiteralName[0] != '_' &&
   14175       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
   14176     // C++11 [usrlit.suffix]p1:
   14177     //   Literal suffix identifiers that do not start with an underscore
   14178     //   are reserved for future standardization.
   14179     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
   14180       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
   14181   }
   14182 
   14183   return false;
   14184 }
   14185 
   14186 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
   14187 /// linkage specification, including the language and (if present)
   14188 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
   14189 /// language string literal. LBraceLoc, if valid, provides the location of
   14190 /// the '{' brace. Otherwise, this linkage specification does not
   14191 /// have any braces.
   14192 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
   14193                                            Expr *LangStr,
   14194                                            SourceLocation LBraceLoc) {
   14195   StringLiteral *Lit = cast<StringLiteral>(LangStr);
   14196   if (!Lit->isAscii()) {
   14197     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
   14198       << LangStr->getSourceRange();
   14199     return nullptr;
   14200   }
   14201 
   14202   StringRef Lang = Lit->getString();
   14203   LinkageSpecDecl::LanguageIDs Language;
   14204   if (Lang == "C")
   14205     Language = LinkageSpecDecl::lang_c;
   14206   else if (Lang == "C++")
   14207     Language = LinkageSpecDecl::lang_cxx;
   14208   else if (Lang == "C++11")
   14209     Language = LinkageSpecDecl::lang_cxx_11;
   14210   else if (Lang == "C++14")
   14211     Language = LinkageSpecDecl::lang_cxx_14;
   14212   else {
   14213     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
   14214       << LangStr->getSourceRange();
   14215     return nullptr;
   14216   }
   14217 
   14218   // FIXME: Add all the various semantics of linkage specifications
   14219 
   14220   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
   14221                                                LangStr->getExprLoc(), Language,
   14222                                                LBraceLoc.isValid());
   14223   CurContext->addDecl(D);
   14224   PushDeclContext(S, D);
   14225   return D;
   14226 }
   14227 
   14228 /// ActOnFinishLinkageSpecification - Complete the definition of
   14229 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
   14230 /// valid, it's the position of the closing '}' brace in a linkage
   14231 /// specification that uses braces.
   14232 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
   14233                                             Decl *LinkageSpec,
   14234                                             SourceLocation RBraceLoc) {
   14235   if (RBraceLoc.isValid()) {
   14236     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
   14237     LSDecl->setRBraceLoc(RBraceLoc);
   14238   }
   14239   PopDeclContext();
   14240   return LinkageSpec;
   14241 }
   14242 
   14243 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
   14244                                   const ParsedAttributesView &AttrList,
   14245                                   SourceLocation SemiLoc) {
   14246   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
   14247   // Attribute declarations appertain to empty declaration so we handle
   14248   // them here.
   14249   ProcessDeclAttributeList(S, ED, AttrList);
   14250 
   14251   CurContext->addDecl(ED);
   14252   return ED;
   14253 }
   14254 
   14255 /// Perform semantic analysis for the variable declaration that
   14256 /// occurs within a C++ catch clause, returning the newly-created
   14257 /// variable.
   14258 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
   14259                                          TypeSourceInfo *TInfo,
   14260                                          SourceLocation StartLoc,
   14261                                          SourceLocation Loc,
   14262                                          IdentifierInfo *Name) {
   14263   bool Invalid = false;
   14264   QualType ExDeclType = TInfo->getType();
   14265 
   14266   // Arrays and functions decay.
   14267   if (ExDeclType->isArrayType())
   14268     ExDeclType = Context.getArrayDecayedType(ExDeclType);
   14269   else if (ExDeclType->isFunctionType())
   14270     ExDeclType = Context.getPointerType(ExDeclType);
   14271 
   14272   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
   14273   // The exception-declaration shall not denote a pointer or reference to an
   14274   // incomplete type, other than [cv] void*.
   14275   // N2844 forbids rvalue references.
   14276   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
   14277     Diag(Loc, diag::err_catch_rvalue_ref);
   14278     Invalid = true;
   14279   }
   14280 
   14281   if (ExDeclType->isVariablyModifiedType()) {
   14282     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
   14283     Invalid = true;
   14284   }
   14285 
   14286   QualType BaseType = ExDeclType;
   14287   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
   14288   unsigned DK = diag::err_catch_incomplete;
   14289   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
   14290     BaseType = Ptr->getPointeeType();
   14291     Mode = 1;
   14292     DK = diag::err_catch_incomplete_ptr;
   14293   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
   14294     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
   14295     BaseType = Ref->getPointeeType();
   14296     Mode = 2;
   14297     DK = diag::err_catch_incomplete_ref;
   14298   }
   14299   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
   14300       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
   14301     Invalid = true;
   14302 
   14303   if (!Invalid && !ExDeclType->isDependentType() &&
   14304       RequireNonAbstractType(Loc, ExDeclType,
   14305                              diag::err_abstract_type_in_decl,
   14306                              AbstractVariableType))
   14307     Invalid = true;
   14308 
   14309   // Only the non-fragile NeXT runtime currently supports C++ catches
   14310   // of ObjC types, and no runtime supports catching ObjC types by value.
   14311   if (!Invalid && getLangOpts().ObjC) {
   14312     QualType T = ExDeclType;
   14313     if (const ReferenceType *RT = T->getAs<ReferenceType>())
   14314       T = RT->getPointeeType();
   14315 
   14316     if (T->isObjCObjectType()) {
   14317       Diag(Loc, diag::err_objc_object_catch);
   14318       Invalid = true;
   14319     } else if (T->isObjCObjectPointerType()) {
   14320       // FIXME: should this be a test for macosx-fragile specifically?
   14321       if (getLangOpts().ObjCRuntime.isFragile())
   14322         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
   14323     }
   14324   }
   14325 
   14326   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
   14327                                     ExDeclType, TInfo, SC_None);
   14328   ExDecl->setExceptionVariable(true);
   14329 
   14330   // In ARC, infer 'retaining' for variables of retainable type.
   14331   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
   14332     Invalid = true;
   14333 
   14334   if (!Invalid && !ExDeclType->isDependentType()) {
   14335     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
   14336       // Insulate this from anything else we might currently be parsing.
   14337       EnterExpressionEvaluationContext scope(
   14338           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
   14339 
   14340       // C++ [except.handle]p16:
   14341       //   The object declared in an exception-declaration or, if the
   14342       //   exception-declaration does not specify a name, a temporary (12.2) is
   14343       //   copy-initialized (8.5) from the exception object. [...]
   14344       //   The object is destroyed when the handler exits, after the destruction
   14345       //   of any automatic objects initialized within the handler.
   14346       //
   14347       // We just pretend to initialize the object with itself, then make sure
   14348       // it can be destroyed later.
   14349       QualType initType = Context.getExceptionObjectType(ExDeclType);
   14350 
   14351       InitializedEntity entity =
   14352         InitializedEntity::InitializeVariable(ExDecl);
   14353       InitializationKind initKind =
   14354         InitializationKind::CreateCopy(Loc, SourceLocation());
   14355 
   14356       Expr *opaqueValue =
   14357         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
   14358       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
   14359       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
   14360       if (result.isInvalid())
   14361         Invalid = true;
   14362       else {
   14363         // If the constructor used was non-trivial, set this as the
   14364         // "initializer".
   14365         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
   14366         if (!construct->getConstructor()->isTrivial()) {
   14367           Expr *init = MaybeCreateExprWithCleanups(construct);
   14368           ExDecl->setInit(init);
   14369         }
   14370 
   14371         // And make sure it's destructable.
   14372         FinalizeVarWithDestructor(ExDecl, recordType);
   14373       }
   14374     }
   14375   }
   14376 
   14377   if (Invalid)
   14378     ExDecl->setInvalidDecl();
   14379 
   14380   return ExDecl;
   14381 }
   14382 
   14383 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
   14384 /// handler.
   14385 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
   14386   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   14387   bool Invalid = D.isInvalidType();
   14388 
   14389   // Check for unexpanded parameter packs.
   14390   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
   14391                                       UPPC_ExceptionType)) {
   14392     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
   14393                                              D.getIdentifierLoc());
   14394     Invalid = true;
   14395   }
   14396 
   14397   IdentifierInfo *II = D.getIdentifier();
   14398   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
   14399                                              LookupOrdinaryName,
   14400                                              ForVisibleRedeclaration)) {
   14401     // The scope should be freshly made just for us. There is just no way
   14402     // it contains any previous declaration, except for function parameters in
   14403     // a function-try-block's catch statement.
   14404     assert(!S->isDeclScope(PrevDecl));
   14405     if (isDeclInScope(PrevDecl, CurContext, S)) {
   14406       Diag(D.getIdentifierLoc(), diag::err_redefinition)
   14407         << D.getIdentifier();
   14408       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   14409       Invalid = true;
   14410     } else if (PrevDecl->isTemplateParameter())
   14411       // Maybe we will complain about the shadowed template parameter.
   14412       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
   14413   }
   14414 
   14415   if (D.getCXXScopeSpec().isSet() && !Invalid) {
   14416     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
   14417       << D.getCXXScopeSpec().getRange();
   14418     Invalid = true;
   14419   }
   14420 
   14421   VarDecl *ExDecl = BuildExceptionDeclaration(
   14422       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
   14423   if (Invalid)
   14424     ExDecl->setInvalidDecl();
   14425 
   14426   // Add the exception declaration into this scope.
   14427   if (II)
   14428     PushOnScopeChains(ExDecl, S);
   14429   else
   14430     CurContext->addDecl(ExDecl);
   14431 
   14432   ProcessDeclAttributes(S, ExDecl, D);
   14433   return ExDecl;
   14434 }
   14435 
   14436 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
   14437                                          Expr *AssertExpr,
   14438                                          Expr *AssertMessageExpr,
   14439                                          SourceLocation RParenLoc) {
   14440   StringLiteral *AssertMessage =
   14441       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
   14442 
   14443   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
   14444     return nullptr;
   14445 
   14446   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
   14447                                       AssertMessage, RParenLoc, false);
   14448 }
   14449 
   14450 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
   14451                                          Expr *AssertExpr,
   14452                                          StringLiteral *AssertMessage,
   14453                                          SourceLocation RParenLoc,
   14454                                          bool Failed) {
   14455   assert(AssertExpr != nullptr && "Expected non-null condition");
   14456   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
   14457       !Failed) {
   14458     // In a static_assert-declaration, the constant-expression shall be a
   14459     // constant expression that can be contextually converted to bool.
   14460     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
   14461     if (Converted.isInvalid())
   14462       Failed = true;
   14463 
   14464     ExprResult FullAssertExpr =
   14465         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
   14466                             /*DiscardedValue*/ false,
   14467                             /*IsConstexpr*/ true);
   14468     if (FullAssertExpr.isInvalid())
   14469       Failed = true;
   14470     else
   14471       AssertExpr = FullAssertExpr.get();
   14472 
   14473     llvm::APSInt Cond;
   14474     if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
   14475           diag::err_static_assert_expression_is_not_constant,
   14476           /*AllowFold=*/false).isInvalid())
   14477       Failed = true;
   14478 
   14479     if (!Failed && !Cond) {
   14480       SmallString<256> MsgBuffer;
   14481       llvm::raw_svector_ostream Msg(MsgBuffer);
   14482       if (AssertMessage)
   14483         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
   14484 
   14485       Expr *InnerCond = nullptr;
   14486       std::string InnerCondDescription;
   14487       std::tie(InnerCond, InnerCondDescription) =
   14488         findFailedBooleanCondition(Converted.get());
   14489       if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
   14490                     && !isa<IntegerLiteral>(InnerCond)) {
   14491         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
   14492           << InnerCondDescription << !AssertMessage
   14493           << Msg.str() << InnerCond->getSourceRange();
   14494       } else {
   14495         Diag(StaticAssertLoc, diag::err_static_assert_failed)
   14496           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
   14497       }
   14498       Failed = true;
   14499     }
   14500   } else {
   14501     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
   14502                                                     /*DiscardedValue*/false,
   14503                                                     /*IsConstexpr*/true);
   14504     if (FullAssertExpr.isInvalid())
   14505       Failed = true;
   14506     else
   14507       AssertExpr = FullAssertExpr.get();
   14508   }
   14509 
   14510   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
   14511                                         AssertExpr, AssertMessage, RParenLoc,
   14512                                         Failed);
   14513 
   14514   CurContext->addDecl(Decl);
   14515   return Decl;
   14516 }
   14517 
   14518 /// Perform semantic analysis of the given friend type declaration.
   14519 ///
   14520 /// \returns A friend declaration that.
   14521 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
   14522                                       SourceLocation FriendLoc,
   14523                                       TypeSourceInfo *TSInfo) {
   14524   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
   14525 
   14526   QualType T = TSInfo->getType();
   14527   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
   14528 
   14529   // C++03 [class.friend]p2:
   14530   //   An elaborated-type-specifier shall be used in a friend declaration
   14531   //   for a class.*
   14532   //
   14533   //   * The class-key of the elaborated-type-specifier is required.
   14534   if (!CodeSynthesisContexts.empty()) {
   14535     // Do not complain about the form of friend template types during any kind
   14536     // of code synthesis. For template instantiation, we will have complained
   14537     // when the template was defined.
   14538   } else {
   14539     if (!T->isElaboratedTypeSpecifier()) {
   14540       // If we evaluated the type to a record type, suggest putting
   14541       // a tag in front.
   14542       if (const RecordType *RT = T->getAs<RecordType>()) {
   14543         RecordDecl *RD = RT->getDecl();
   14544 
   14545         SmallString<16> InsertionText(" ");
   14546         InsertionText += RD->getKindName();
   14547 
   14548         Diag(TypeRange.getBegin(),
   14549              getLangOpts().CPlusPlus11 ?
   14550                diag::warn_cxx98_compat_unelaborated_friend_type :
   14551                diag::ext_unelaborated_friend_type)
   14552           << (unsigned) RD->getTagKind()
   14553           << T
   14554           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
   14555                                         InsertionText);
   14556       } else {
   14557         Diag(FriendLoc,
   14558              getLangOpts().CPlusPlus11 ?
   14559                diag::warn_cxx98_compat_nonclass_type_friend :
   14560                diag::ext_nonclass_type_friend)
   14561           << T
   14562           << TypeRange;
   14563       }
   14564     } else if (T->getAs<EnumType>()) {
   14565       Diag(FriendLoc,
   14566            getLangOpts().CPlusPlus11 ?
   14567              diag::warn_cxx98_compat_enum_friend :
   14568              diag::ext_enum_friend)
   14569         << T
   14570         << TypeRange;
   14571     }
   14572 
   14573     // C++11 [class.friend]p3:
   14574     //   A friend declaration that does not declare a function shall have one
   14575     //   of the following forms:
   14576     //     friend elaborated-type-specifier ;
   14577     //     friend simple-type-specifier ;
   14578     //     friend typename-specifier ;
   14579     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
   14580       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
   14581   }
   14582 
   14583   //   If the type specifier in a friend declaration designates a (possibly
   14584   //   cv-qualified) class type, that class is declared as a friend; otherwise,
   14585   //   the friend declaration is ignored.
   14586   return FriendDecl::Create(Context, CurContext,
   14587                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
   14588                             FriendLoc);
   14589 }
   14590 
   14591 /// Handle a friend tag declaration where the scope specifier was
   14592 /// templated.
   14593 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
   14594                                     unsigned TagSpec, SourceLocation TagLoc,
   14595                                     CXXScopeSpec &SS, IdentifierInfo *Name,
   14596                                     SourceLocation NameLoc,
   14597                                     const ParsedAttributesView &Attr,
   14598                                     MultiTemplateParamsArg TempParamLists) {
   14599   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
   14600 
   14601   bool IsMemberSpecialization = false;
   14602   bool Invalid = false;
   14603 
   14604   if (TemplateParameterList *TemplateParams =
   14605           MatchTemplateParametersToScopeSpecifier(
   14606               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
   14607               IsMemberSpecialization, Invalid)) {
   14608     if (TemplateParams->size() > 0) {
   14609       // This is a declaration of a class template.
   14610       if (Invalid)
   14611         return nullptr;
   14612 
   14613       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
   14614                                 NameLoc, Attr, TemplateParams, AS_public,
   14615                                 /*ModulePrivateLoc=*/SourceLocation(),
   14616                                 FriendLoc, TempParamLists.size() - 1,
   14617                                 TempParamLists.data()).get();
   14618     } else {
   14619       // The "template<>" header is extraneous.
   14620       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
   14621         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
   14622       IsMemberSpecialization = true;
   14623     }
   14624   }
   14625 
   14626   if (Invalid) return nullptr;
   14627 
   14628   bool isAllExplicitSpecializations = true;
   14629   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
   14630     if (TempParamLists[I]->size()) {
   14631       isAllExplicitSpecializations = false;
   14632       break;
   14633     }
   14634   }
   14635 
   14636   // FIXME: don't ignore attributes.
   14637 
   14638   // If it's explicit specializations all the way down, just forget
   14639   // about the template header and build an appropriate non-templated
   14640   // friend.  TODO: for source fidelity, remember the headers.
   14641   if (isAllExplicitSpecializations) {
   14642     if (SS.isEmpty()) {
   14643       bool Owned = false;
   14644       bool IsDependent = false;
   14645       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
   14646                       Attr, AS_public,
   14647                       /*ModulePrivateLoc=*/SourceLocation(),
   14648                       MultiTemplateParamsArg(), Owned, IsDependent,
   14649                       /*ScopedEnumKWLoc=*/SourceLocation(),
   14650                       /*ScopedEnumUsesClassTag=*/false,
   14651                       /*UnderlyingType=*/TypeResult(),
   14652                       /*IsTypeSpecifier=*/false,
   14653                       /*IsTemplateParamOrArg=*/false);
   14654     }
   14655 
   14656     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
   14657     ElaboratedTypeKeyword Keyword
   14658       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
   14659     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
   14660                                    *Name, NameLoc);
   14661     if (T.isNull())
   14662       return nullptr;
   14663 
   14664     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
   14665     if (isa<DependentNameType>(T)) {
   14666       DependentNameTypeLoc TL =
   14667           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
   14668       TL.setElaboratedKeywordLoc(TagLoc);
   14669       TL.setQualifierLoc(QualifierLoc);
   14670       TL.setNameLoc(NameLoc);
   14671     } else {
   14672       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
   14673       TL.setElaboratedKeywordLoc(TagLoc);
   14674       TL.setQualifierLoc(QualifierLoc);
   14675       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
   14676     }
   14677 
   14678     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
   14679                                             TSI, FriendLoc, TempParamLists);
   14680     Friend->setAccess(AS_public);
   14681     CurContext->addDecl(Friend);
   14682     return Friend;
   14683   }
   14684 
   14685   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
   14686 
   14687 
   14688 
   14689   // Handle the case of a templated-scope friend class.  e.g.
   14690   //   template <class T> class A<T>::B;
   14691   // FIXME: we don't support these right now.
   14692   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
   14693     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
   14694   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
   14695   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
   14696   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
   14697   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
   14698   TL.setElaboratedKeywordLoc(TagLoc);
   14699   TL.setQualifierLoc(SS.getWithLocInContext(Context));
   14700   TL.setNameLoc(NameLoc);
   14701 
   14702   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
   14703                                           TSI, FriendLoc, TempParamLists);
   14704   Friend->setAccess(AS_public);
   14705   Friend->setUnsupportedFriend(true);
   14706   CurContext->addDecl(Friend);
   14707   return Friend;
   14708 }
   14709 
   14710 /// Handle a friend type declaration.  This works in tandem with
   14711 /// ActOnTag.
   14712 ///
   14713 /// Notes on friend class templates:
   14714 ///
   14715 /// We generally treat friend class declarations as if they were
   14716 /// declaring a class.  So, for example, the elaborated type specifier
   14717 /// in a friend declaration is required to obey the restrictions of a
   14718 /// class-head (i.e. no typedefs in the scope chain), template
   14719 /// parameters are required to match up with simple template-ids, &c.
   14720 /// However, unlike when declaring a template specialization, it's
   14721 /// okay to refer to a template specialization without an empty
   14722 /// template parameter declaration, e.g.
   14723 ///   friend class A<T>::B<unsigned>;
   14724 /// We permit this as a special case; if there are any template
   14725 /// parameters present at all, require proper matching, i.e.
   14726 ///   template <> template \<class T> friend class A<int>::B;
   14727 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
   14728                                 MultiTemplateParamsArg TempParams) {
   14729   SourceLocation Loc = DS.getBeginLoc();
   14730 
   14731   assert(DS.isFriendSpecified());
   14732   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
   14733 
   14734   // C++ [class.friend]p3:
   14735   // A friend declaration that does not declare a function shall have one of
   14736   // the following forms:
   14737   //     friend elaborated-type-specifier ;
   14738   //     friend simple-type-specifier ;
   14739   //     friend typename-specifier ;
   14740   //
   14741   // Any declaration with a type qualifier does not have that form. (It's
   14742   // legal to specify a qualified type as a friend, you just can't write the
   14743   // keywords.)
   14744   if (DS.getTypeQualifiers()) {
   14745     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
   14746       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
   14747     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
   14748       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
   14749     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
   14750       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
   14751     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
   14752       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
   14753     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
   14754       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
   14755   }
   14756 
   14757   // Try to convert the decl specifier to a type.  This works for
   14758   // friend templates because ActOnTag never produces a ClassTemplateDecl
   14759   // for a TUK_Friend.
   14760   Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
   14761   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
   14762   QualType T = TSI->getType();
   14763   if (TheDeclarator.isInvalidType())
   14764     return nullptr;
   14765 
   14766   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
   14767     return nullptr;
   14768 
   14769   // This is definitely an error in C++98.  It's probably meant to
   14770   // be forbidden in C++0x, too, but the specification is just
   14771   // poorly written.
   14772   //
   14773   // The problem is with declarations like the following:
   14774   //   template <T> friend A<T>::foo;
   14775   // where deciding whether a class C is a friend or not now hinges
   14776   // on whether there exists an instantiation of A that causes
   14777   // 'foo' to equal C.  There are restrictions on class-heads
   14778   // (which we declare (by fiat) elaborated friend declarations to
   14779   // be) that makes this tractable.
   14780   //
   14781   // FIXME: handle "template <> friend class A<T>;", which
   14782   // is possibly well-formed?  Who even knows?
   14783   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
   14784     Diag(Loc, diag::err_tagless_friend_type_template)
   14785       << DS.getSourceRange();
   14786     return nullptr;
   14787   }
   14788 
   14789   // C++98 [class.friend]p1: A friend of a class is a function
   14790   //   or class that is not a member of the class . . .
   14791   // This is fixed in DR77, which just barely didn't make the C++03
   14792   // deadline.  It's also a very silly restriction that seriously
   14793   // affects inner classes and which nobody else seems to implement;
   14794   // thus we never diagnose it, not even in -pedantic.
   14795   //
   14796   // But note that we could warn about it: it's always useless to
   14797   // friend one of your own members (it's not, however, worthless to
   14798   // friend a member of an arbitrary specialization of your template).
   14799 
   14800   Decl *D;
   14801   if (!TempParams.empty())
   14802     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
   14803                                    TempParams,
   14804                                    TSI,
   14805                                    DS.getFriendSpecLoc());
   14806   else
   14807     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
   14808 
   14809   if (!D)
   14810     return nullptr;
   14811 
   14812   D->setAccess(AS_public);
   14813   CurContext->addDecl(D);
   14814 
   14815   return D;
   14816 }
   14817 
   14818 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
   14819                                         MultiTemplateParamsArg TemplateParams) {
   14820   const DeclSpec &DS = D.getDeclSpec();
   14821 
   14822   assert(DS.isFriendSpecified());
   14823   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
   14824 
   14825   SourceLocation Loc = D.getIdentifierLoc();
   14826   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   14827 
   14828   // C++ [class.friend]p1
   14829   //   A friend of a class is a function or class....
   14830   // Note that this sees through typedefs, which is intended.
   14831   // It *doesn't* see through dependent types, which is correct
   14832   // according to [temp.arg.type]p3:
   14833   //   If a declaration acquires a function type through a
   14834   //   type dependent on a template-parameter and this causes
   14835   //   a declaration that does not use the syntactic form of a
   14836   //   function declarator to have a function type, the program
   14837   //   is ill-formed.
   14838   if (!TInfo->getType()->isFunctionType()) {
   14839     Diag(Loc, diag::err_unexpected_friend);
   14840 
   14841     // It might be worthwhile to try to recover by creating an
   14842     // appropriate declaration.
   14843     return nullptr;
   14844   }
   14845 
   14846   // C++ [namespace.memdef]p3
   14847   //  - If a friend declaration in a non-local class first declares a
   14848   //    class or function, the friend class or function is a member
   14849   //    of the innermost enclosing namespace.
   14850   //  - The name of the friend is not found by simple name lookup
   14851   //    until a matching declaration is provided in that namespace
   14852   //    scope (either before or after the class declaration granting
   14853   //    friendship).
   14854   //  - If a friend function is called, its name may be found by the
   14855   //    name lookup that considers functions from namespaces and
   14856   //    classes associated with the types of the function arguments.
   14857   //  - When looking for a prior declaration of a class or a function
   14858   //    declared as a friend, scopes outside the innermost enclosing
   14859   //    namespace scope are not considered.
   14860 
   14861   CXXScopeSpec &SS = D.getCXXScopeSpec();
   14862   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
   14863   assert(NameInfo.getName());
   14864 
   14865   // Check for unexpanded parameter packs.
   14866   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
   14867       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
   14868       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
   14869     return nullptr;
   14870 
   14871   // The context we found the declaration in, or in which we should
   14872   // create the declaration.
   14873   DeclContext *DC;
   14874   Scope *DCScope = S;
   14875   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
   14876                         ForExternalRedeclaration);
   14877 
   14878   // There are five cases here.
   14879   //   - There's no scope specifier and we're in a local class. Only look
   14880   //     for functions declared in the immediately-enclosing block scope.
   14881   // We recover from invalid scope qualifiers as if they just weren't there.
   14882   FunctionDecl *FunctionContainingLocalClass = nullptr;
   14883   if ((SS.isInvalid() || !SS.isSet()) &&
   14884       (FunctionContainingLocalClass =
   14885            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
   14886     // C++11 [class.friend]p11:
   14887     //   If a friend declaration appears in a local class and the name
   14888     //   specified is an unqualified name, a prior declaration is
   14889     //   looked up without considering scopes that are outside the
   14890     //   innermost enclosing non-class scope. For a friend function
   14891     //   declaration, if there is no prior declaration, the program is
   14892     //   ill-formed.
   14893 
   14894     // Find the innermost enclosing non-class scope. This is the block
   14895     // scope containing the local class definition (or for a nested class,
   14896     // the outer local class).
   14897     DCScope = S->getFnParent();
   14898 
   14899     // Look up the function name in the scope.
   14900     Previous.clear(LookupLocalFriendName);
   14901     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
   14902 
   14903     if (!Previous.empty()) {
   14904       // All possible previous declarations must have the same context:
   14905       // either they were declared at block scope or they are members of
   14906       // one of the enclosing local classes.
   14907       DC = Previous.getRepresentativeDecl()->getDeclContext();
   14908     } else {
   14909       // This is ill-formed, but provide the context that we would have
   14910       // declared the function in, if we were permitted to, for error recovery.
   14911       DC = FunctionContainingLocalClass;
   14912     }
   14913     adjustContextForLocalExternDecl(DC);
   14914 
   14915     // C++ [class.friend]p6:
   14916     //   A function can be defined in a friend declaration of a class if and
   14917     //   only if the class is a non-local class (9.8), the function name is
   14918     //   unqualified, and the function has namespace scope.
   14919     if (D.isFunctionDefinition()) {
   14920       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
   14921     }
   14922 
   14923   //   - There's no scope specifier, in which case we just go to the
   14924   //     appropriate scope and look for a function or function template
   14925   //     there as appropriate.
   14926   } else if (SS.isInvalid() || !SS.isSet()) {
   14927     // C++11 [namespace.memdef]p3:
   14928     //   If the name in a friend declaration is neither qualified nor
   14929     //   a template-id and the declaration is a function or an
   14930     //   elaborated-type-specifier, the lookup to determine whether
   14931     //   the entity has been previously declared shall not consider
   14932     //   any scopes outside the innermost enclosing namespace.
   14933     bool isTemplateId =
   14934         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
   14935 
   14936     // Find the appropriate context according to the above.
   14937     DC = CurContext;
   14938 
   14939     // Skip class contexts.  If someone can cite chapter and verse
   14940     // for this behavior, that would be nice --- it's what GCC and
   14941     // EDG do, and it seems like a reasonable intent, but the spec
   14942     // really only says that checks for unqualified existing
   14943     // declarations should stop at the nearest enclosing namespace,
   14944     // not that they should only consider the nearest enclosing
   14945     // namespace.
   14946     while (DC->isRecord())
   14947       DC = DC->getParent();
   14948 
   14949     DeclContext *LookupDC = DC;
   14950     while (LookupDC->isTransparentContext())
   14951       LookupDC = LookupDC->getParent();
   14952 
   14953     while (true) {
   14954       LookupQualifiedName(Previous, LookupDC);
   14955 
   14956       if (!Previous.empty()) {
   14957         DC = LookupDC;
   14958         break;
   14959       }
   14960 
   14961       if (isTemplateId) {
   14962         if (isa<TranslationUnitDecl>(LookupDC)) break;
   14963       } else {
   14964         if (LookupDC->isFileContext()) break;
   14965       }
   14966       LookupDC = LookupDC->getParent();
   14967     }
   14968 
   14969     DCScope = getScopeForDeclContext(S, DC);
   14970 
   14971   //   - There's a non-dependent scope specifier, in which case we
   14972   //     compute it and do a previous lookup there for a function
   14973   //     or function template.
   14974   } else if (!SS.getScopeRep()->isDependent()) {
   14975     DC = computeDeclContext(SS);
   14976     if (!DC) return nullptr;
   14977 
   14978     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
   14979 
   14980     LookupQualifiedName(Previous, DC);
   14981 
   14982     // C++ [class.friend]p1: A friend of a class is a function or
   14983     //   class that is not a member of the class . . .
   14984     if (DC->Equals(CurContext))
   14985       Diag(DS.getFriendSpecLoc(),
   14986            getLangOpts().CPlusPlus11 ?
   14987              diag::warn_cxx98_compat_friend_is_member :
   14988              diag::err_friend_is_member);
   14989 
   14990     if (D.isFunctionDefinition()) {
   14991       // C++ [class.friend]p6:
   14992       //   A function can be defined in a friend declaration of a class if and
   14993       //   only if the class is a non-local class (9.8), the function name is
   14994       //   unqualified, and the function has namespace scope.
   14995       //
   14996       // FIXME: We should only do this if the scope specifier names the
   14997       // innermost enclosing namespace; otherwise the fixit changes the
   14998       // meaning of the code.
   14999       SemaDiagnosticBuilder DB
   15000         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
   15001 
   15002       DB << SS.getScopeRep();
   15003       if (DC->isFileContext())
   15004         DB << FixItHint::CreateRemoval(SS.getRange());
   15005       SS.clear();
   15006     }
   15007 
   15008   //   - There's a scope specifier that does not match any template
   15009   //     parameter lists, in which case we use some arbitrary context,
   15010   //     create a method or method template, and wait for instantiation.
   15011   //   - There's a scope specifier that does match some template
   15012   //     parameter lists, which we don't handle right now.
   15013   } else {
   15014     if (D.isFunctionDefinition()) {
   15015       // C++ [class.friend]p6:
   15016       //   A function can be defined in a friend declaration of a class if and
   15017       //   only if the class is a non-local class (9.8), the function name is
   15018       //   unqualified, and the function has namespace scope.
   15019       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
   15020         << SS.getScopeRep();
   15021     }
   15022 
   15023     DC = CurContext;
   15024     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
   15025   }
   15026 
   15027   if (!DC->isRecord()) {
   15028     int DiagArg = -1;
   15029     switch (D.getName().getKind()) {
   15030     case UnqualifiedIdKind::IK_ConstructorTemplateId:
   15031     case UnqualifiedIdKind::IK_ConstructorName:
   15032       DiagArg = 0;
   15033       break;
   15034     case UnqualifiedIdKind::IK_DestructorName:
   15035       DiagArg = 1;
   15036       break;
   15037     case UnqualifiedIdKind::IK_ConversionFunctionId:
   15038       DiagArg = 2;
   15039       break;
   15040     case UnqualifiedIdKind::IK_DeductionGuideName:
   15041       DiagArg = 3;
   15042       break;
   15043     case UnqualifiedIdKind::IK_Identifier:
   15044     case UnqualifiedIdKind::IK_ImplicitSelfParam:
   15045     case UnqualifiedIdKind::IK_LiteralOperatorId:
   15046     case UnqualifiedIdKind::IK_OperatorFunctionId:
   15047     case UnqualifiedIdKind::IK_TemplateId:
   15048       break;
   15049     }
   15050     // This implies that it has to be an operator or function.
   15051     if (DiagArg >= 0) {
   15052       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
   15053       return nullptr;
   15054     }
   15055   }
   15056 
   15057   // FIXME: This is an egregious hack to cope with cases where the scope stack
   15058   // does not contain the declaration context, i.e., in an out-of-line
   15059   // definition of a class.
   15060   Scope FakeDCScope(S, Scope::DeclScope, Diags);
   15061   if (!DCScope) {
   15062     FakeDCScope.setEntity(DC);
   15063     DCScope = &FakeDCScope;
   15064   }
   15065 
   15066   bool AddToScope = true;
   15067   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
   15068                                           TemplateParams, AddToScope);
   15069   if (!ND) return nullptr;
   15070 
   15071   assert(ND->getLexicalDeclContext() == CurContext);
   15072 
   15073   // If we performed typo correction, we might have added a scope specifier
   15074   // and changed the decl context.
   15075   DC = ND->getDeclContext();
   15076 
   15077   // Add the function declaration to the appropriate lookup tables,
   15078   // adjusting the redeclarations list as necessary.  We don't
   15079   // want to do this yet if the friending class is dependent.
   15080   //
   15081   // Also update the scope-based lookup if the target context's
   15082   // lookup context is in lexical scope.
   15083   if (!CurContext->isDependentContext()) {
   15084     DC = DC->getRedeclContext();
   15085     DC->makeDeclVisibleInContext(ND);
   15086     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
   15087       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
   15088   }
   15089 
   15090   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
   15091                                        D.getIdentifierLoc(), ND,
   15092                                        DS.getFriendSpecLoc());
   15093   FrD->setAccess(AS_public);
   15094   CurContext->addDecl(FrD);
   15095 
   15096   if (ND->isInvalidDecl()) {
   15097     FrD->setInvalidDecl();
   15098   } else {
   15099     if (DC->isRecord()) CheckFriendAccess(ND);
   15100 
   15101     FunctionDecl *FD;
   15102     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
   15103       FD = FTD->getTemplatedDecl();
   15104     else
   15105       FD = cast<FunctionDecl>(ND);
   15106 
   15107     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
   15108     // default argument expression, that declaration shall be a definition
   15109     // and shall be the only declaration of the function or function
   15110     // template in the translation unit.
   15111     if (functionDeclHasDefaultArgument(FD)) {
   15112       // We can't look at FD->getPreviousDecl() because it may not have been set
   15113       // if we're in a dependent context. If the function is known to be a
   15114       // redeclaration, we will have narrowed Previous down to the right decl.
   15115       if (D.isRedeclaration()) {
   15116         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
   15117         Diag(Previous.getRepresentativeDecl()->getLocation(),
   15118              diag::note_previous_declaration);
   15119       } else if (!D.isFunctionDefinition())
   15120         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
   15121     }
   15122 
   15123     // Mark templated-scope function declarations as unsupported.
   15124     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
   15125       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
   15126         << SS.getScopeRep() << SS.getRange()
   15127         << cast<CXXRecordDecl>(CurContext);
   15128       FrD->setUnsupportedFriend(true);
   15129     }
   15130   }
   15131 
   15132   return ND;
   15133 }
   15134 
   15135 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
   15136   AdjustDeclIfTemplate(Dcl);
   15137 
   15138   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
   15139   if (!Fn) {
   15140     Diag(DelLoc, diag::err_deleted_non_function);
   15141     return;
   15142   }
   15143 
   15144   // Deleted function does not have a body.
   15145   Fn->setWillHaveBody(false);
   15146 
   15147   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
   15148     // Don't consider the implicit declaration we generate for explicit
   15149     // specializations. FIXME: Do not generate these implicit declarations.
   15150     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
   15151          Prev->getPreviousDecl()) &&
   15152         !Prev->isDefined()) {
   15153       Diag(DelLoc, diag::err_deleted_decl_not_first);
   15154       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
   15155            Prev->isImplicit() ? diag::note_previous_implicit_declaration
   15156                               : diag::note_previous_declaration);
   15157     }
   15158     // If the declaration wasn't the first, we delete the function anyway for
   15159     // recovery.
   15160     Fn = Fn->getCanonicalDecl();
   15161   }
   15162 
   15163   // dllimport/dllexport cannot be deleted.
   15164   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
   15165     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
   15166     Fn->setInvalidDecl();
   15167   }
   15168 
   15169   if (Fn->isDeleted())
   15170     return;
   15171 
   15172   // See if we're deleting a function which is already known to override a
   15173   // non-deleted virtual function.
   15174   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
   15175     bool IssuedDiagnostic = false;
   15176     for (const CXXMethodDecl *O : MD->overridden_methods()) {
   15177       if (!(*MD->begin_overridden_methods())->isDeleted()) {
   15178         if (!IssuedDiagnostic) {
   15179           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
   15180           IssuedDiagnostic = true;
   15181         }
   15182         Diag(O->getLocation(), diag::note_overridden_virtual_function);
   15183       }
   15184     }
   15185     // If this function was implicitly deleted because it was defaulted,
   15186     // explain why it was deleted.
   15187     if (IssuedDiagnostic && MD->isDefaulted())
   15188       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
   15189                                 /*Diagnose*/true);
   15190   }
   15191 
   15192   // C++11 [basic.start.main]p3:
   15193   //   A program that defines main as deleted [...] is ill-formed.
   15194   if (Fn->isMain())
   15195     Diag(DelLoc, diag::err_deleted_main);
   15196 
   15197   // C++11 [dcl.fct.def.delete]p4:
   15198   //  A deleted function is implicitly inline.
   15199   Fn->setImplicitlyInline();
   15200   Fn->setDeletedAsWritten();
   15201 }
   15202 
   15203 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
   15204   if (!Dcl || Dcl->isInvalidDecl())
   15205     return;
   15206 
   15207   auto *FD = dyn_cast<FunctionDecl>(Dcl);
   15208   if (!FD) {
   15209     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
   15210       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
   15211         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
   15212         return;
   15213       }
   15214     }
   15215 
   15216     Diag(DefaultLoc, diag::err_default_special_members)
   15217         << getLangOpts().CPlusPlus2a;
   15218     return;
   15219   }
   15220 
   15221   // Reject if this can't possibly be a defaultable function.
   15222   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
   15223   if (!DefKind &&
   15224       // A dependent function that doesn't locally look defaultable can
   15225       // still instantiate to a defaultable function if it's a constructor
   15226       // or assignment operator.
   15227       (!FD->isDependentContext() ||
   15228        (!isa<CXXConstructorDecl>(FD) &&
   15229         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
   15230     Diag(DefaultLoc, diag::err_default_special_members)
   15231         << getLangOpts().CPlusPlus2a;
   15232     return;
   15233   }
   15234 
   15235   if (DefKind.isComparison() &&
   15236       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
   15237     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
   15238         << (int)DefKind.asComparison();
   15239     return;
   15240   }
   15241 
   15242   // Issue compatibility warning. We already warned if the operator is
   15243   // 'operator<=>' when parsing the '<=>' token.
   15244   if (DefKind.isComparison() &&
   15245       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
   15246     Diag(DefaultLoc, getLangOpts().CPlusPlus2a
   15247                          ? diag::warn_cxx17_compat_defaulted_comparison
   15248                          : diag::ext_defaulted_comparison);
   15249   }
   15250 
   15251   FD->setDefaulted();
   15252   FD->setExplicitlyDefaulted();
   15253 
   15254   // Defer checking functions that are defaulted in a dependent context.
   15255   if (FD->isDependentContext())
   15256     return;
   15257 
   15258   // Unset that we will have a body for this function. We might not,
   15259   // if it turns out to be trivial, and we don't need this marking now
   15260   // that we've marked it as defaulted.
   15261   FD->setWillHaveBody(false);
   15262 
   15263   // If this definition appears within the record, do the checking when
   15264   // the record is complete. This is always the case for a defaulted
   15265   // comparison.
   15266   if (DefKind.isComparison())
   15267     return;
   15268   auto *MD = cast<CXXMethodDecl>(FD);
   15269 
   15270   const FunctionDecl *Primary = FD;
   15271   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
   15272     // Ask the template instantiation pattern that actually had the
   15273     // '= default' on it.
   15274     Primary = Pattern;
   15275 
   15276   // If the method was defaulted on its first declaration, we will have
   15277   // already performed the checking in CheckCompletedCXXClass. Such a
   15278   // declaration doesn't trigger an implicit definition.
   15279   if (Primary->getCanonicalDecl()->isDefaulted())
   15280     return;
   15281 
   15282   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
   15283     MD->setInvalidDecl();
   15284   else
   15285     DefineImplicitSpecialMember(*this, MD, DefaultLoc);
   15286 }
   15287 
   15288 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
   15289   for (Stmt *SubStmt : S->children()) {
   15290     if (!SubStmt)
   15291       continue;
   15292     if (isa<ReturnStmt>(SubStmt))
   15293       Self.Diag(SubStmt->getBeginLoc(),
   15294                 diag::err_return_in_constructor_handler);
   15295     if (!isa<Expr>(SubStmt))
   15296       SearchForReturnInStmt(Self, SubStmt);
   15297   }
   15298 }
   15299 
   15300 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
   15301   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
   15302     CXXCatchStmt *Handler = TryBlock->getHandler(I);
   15303     SearchForReturnInStmt(*this, Handler);
   15304   }
   15305 }
   15306 
   15307 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
   15308                                              const CXXMethodDecl *Old) {
   15309   const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
   15310   const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
   15311 
   15312   if (OldFT->hasExtParameterInfos()) {
   15313     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
   15314       // A parameter of the overriding method should be annotated with noescape
   15315       // if the corresponding parameter of the overridden method is annotated.
   15316       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
   15317           !NewFT->getExtParameterInfo(I).isNoEscape()) {
   15318         Diag(New->getParamDecl(I)->getLocation(),
   15319              diag::warn_overriding_method_missing_noescape);
   15320         Diag(Old->getParamDecl(I)->getLocation(),
   15321              diag::note_overridden_marked_noescape);
   15322       }
   15323   }
   15324 
   15325   // Virtual overrides must have the same code_seg.
   15326   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
   15327   const auto *NewCSA = New->getAttr<CodeSegAttr>();
   15328   if ((NewCSA || OldCSA) &&
   15329       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
   15330     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
   15331     Diag(Old->getLocation(), diag::note_previous_declaration);
   15332     return true;
   15333   }
   15334 
   15335   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
   15336 
   15337   // If the calling conventions match, everything is fine
   15338   if (NewCC == OldCC)
   15339     return false;
   15340 
   15341   // If the calling conventions mismatch because the new function is static,
   15342   // suppress the calling convention mismatch error; the error about static
   15343   // function override (err_static_overrides_virtual from
   15344   // Sema::CheckFunctionDeclaration) is more clear.
   15345   if (New->getStorageClass() == SC_Static)
   15346     return false;
   15347 
   15348   Diag(New->getLocation(),
   15349        diag::err_conflicting_overriding_cc_attributes)
   15350     << New->getDeclName() << New->getType() << Old->getType();
   15351   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
   15352   return true;
   15353 }
   15354 
   15355 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
   15356                                              const CXXMethodDecl *Old) {
   15357   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
   15358   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
   15359 
   15360   if (Context.hasSameType(NewTy, OldTy) ||
   15361       NewTy->isDependentType() || OldTy->isDependentType())
   15362     return false;
   15363 
   15364   // Check if the return types are covariant
   15365   QualType NewClassTy, OldClassTy;
   15366 
   15367   /// Both types must be pointers or references to classes.
   15368   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
   15369     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
   15370       NewClassTy = NewPT->getPointeeType();
   15371       OldClassTy = OldPT->getPointeeType();
   15372     }
   15373   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
   15374     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
   15375       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
   15376         NewClassTy = NewRT->getPointeeType();
   15377         OldClassTy = OldRT->getPointeeType();
   15378       }
   15379     }
   15380   }
   15381 
   15382   // The return types aren't either both pointers or references to a class type.
   15383   if (NewClassTy.isNull()) {
   15384     Diag(New->getLocation(),
   15385          diag::err_different_return_type_for_overriding_virtual_function)
   15386         << New->getDeclName() << NewTy << OldTy
   15387         << New->getReturnTypeSourceRange();
   15388     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   15389         << Old->getReturnTypeSourceRange();
   15390 
   15391     return true;
   15392   }
   15393 
   15394   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
   15395     // C++14 [class.virtual]p8:
   15396     //   If the class type in the covariant return type of D::f differs from
   15397     //   that of B::f, the class type in the return type of D::f shall be
   15398     //   complete at the point of declaration of D::f or shall be the class
   15399     //   type D.
   15400     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
   15401       if (!RT->isBeingDefined() &&
   15402           RequireCompleteType(New->getLocation(), NewClassTy,
   15403                               diag::err_covariant_return_incomplete,
   15404                               New->getDeclName()))
   15405         return true;
   15406     }
   15407 
   15408     // Check if the new class derives from the old class.
   15409     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
   15410       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
   15411           << New->getDeclName() << NewTy << OldTy
   15412           << New->getReturnTypeSourceRange();
   15413       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   15414           << Old->getReturnTypeSourceRange();
   15415       return true;
   15416     }
   15417 
   15418     // Check if we the conversion from derived to base is valid.
   15419     if (CheckDerivedToBaseConversion(
   15420             NewClassTy, OldClassTy,
   15421             diag::err_covariant_return_inaccessible_base,
   15422             diag::err_covariant_return_ambiguous_derived_to_base_conv,
   15423             New->getLocation(), New->getReturnTypeSourceRange(),
   15424             New->getDeclName(), nullptr)) {
   15425       // FIXME: this note won't trigger for delayed access control
   15426       // diagnostics, and it's impossible to get an undelayed error
   15427       // here from access control during the original parse because
   15428       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
   15429       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   15430           << Old->getReturnTypeSourceRange();
   15431       return true;
   15432     }
   15433   }
   15434 
   15435   // The qualifiers of the return types must be the same.
   15436   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
   15437     Diag(New->getLocation(),
   15438          diag::err_covariant_return_type_different_qualifications)
   15439         << New->getDeclName() << NewTy << OldTy
   15440         << New->getReturnTypeSourceRange();
   15441     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   15442         << Old->getReturnTypeSourceRange();
   15443     return true;
   15444   }
   15445 
   15446 
   15447   // The new class type must have the same or less qualifiers as the old type.
   15448   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
   15449     Diag(New->getLocation(),
   15450          diag::err_covariant_return_type_class_type_more_qualified)
   15451         << New->getDeclName() << NewTy << OldTy
   15452         << New->getReturnTypeSourceRange();
   15453     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   15454         << Old->getReturnTypeSourceRange();
   15455     return true;
   15456   }
   15457 
   15458   return false;
   15459 }
   15460 
   15461 /// Mark the given method pure.
   15462 ///
   15463 /// \param Method the method to be marked pure.
   15464 ///
   15465 /// \param InitRange the source range that covers the "0" initializer.
   15466 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
   15467   SourceLocation EndLoc = InitRange.getEnd();
   15468   if (EndLoc.isValid())
   15469     Method->setRangeEnd(EndLoc);
   15470 
   15471   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
   15472     Method->setPure();
   15473     return false;
   15474   }
   15475 
   15476   if (!Method->isInvalidDecl())
   15477     Diag(Method->getLocation(), diag::err_non_virtual_pure)
   15478       << Method->getDeclName() << InitRange;
   15479   return true;
   15480 }
   15481 
   15482 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
   15483   if (D->getFriendObjectKind())
   15484     Diag(D->getLocation(), diag::err_pure_friend);
   15485   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
   15486     CheckPureMethod(M, ZeroLoc);
   15487   else
   15488     Diag(D->getLocation(), diag::err_illegal_initializer);
   15489 }
   15490 
   15491 /// Determine whether the given declaration is a global variable or
   15492 /// static data member.
   15493 static bool isNonlocalVariable(const Decl *D) {
   15494   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
   15495     return Var->hasGlobalStorage();
   15496 
   15497   return false;
   15498 }
   15499 
   15500 /// Invoked when we are about to parse an initializer for the declaration
   15501 /// 'Dcl'.
   15502 ///
   15503 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
   15504 /// static data member of class X, names should be looked up in the scope of
   15505 /// class X. If the declaration had a scope specifier, a scope will have
   15506 /// been created and passed in for this purpose. Otherwise, S will be null.
   15507 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
   15508   // If there is no declaration, there was an error parsing it.
   15509   if (!D || D->isInvalidDecl())
   15510     return;
   15511 
   15512   // We will always have a nested name specifier here, but this declaration
   15513   // might not be out of line if the specifier names the current namespace:
   15514   //   extern int n;
   15515   //   int ::n = 0;
   15516   if (S && D->isOutOfLine())
   15517     EnterDeclaratorContext(S, D->getDeclContext());
   15518 
   15519   // If we are parsing the initializer for a static data member, push a
   15520   // new expression evaluation context that is associated with this static
   15521   // data member.
   15522   if (isNonlocalVariable(D))
   15523     PushExpressionEvaluationContext(
   15524         ExpressionEvaluationContext::PotentiallyEvaluated, D);
   15525 }
   15526 
   15527 /// Invoked after we are finished parsing an initializer for the declaration D.
   15528 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
   15529   // If there is no declaration, there was an error parsing it.
   15530   if (!D || D->isInvalidDecl())
   15531     return;
   15532 
   15533   if (isNonlocalVariable(D))
   15534     PopExpressionEvaluationContext();
   15535 
   15536   if (S && D->isOutOfLine())
   15537     ExitDeclaratorContext(S);
   15538 }
   15539 
   15540 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
   15541 /// C++ if/switch/while/for statement.
   15542 /// e.g: "if (int x = f()) {...}"
   15543 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
   15544   // C++ 6.4p2:
   15545   // The declarator shall not specify a function or an array.
   15546   // The type-specifier-seq shall not contain typedef and shall not declare a
   15547   // new class or enumeration.
   15548   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
   15549          "Parser allowed 'typedef' as storage class of condition decl.");
   15550 
   15551   Decl *Dcl = ActOnDeclarator(S, D);
   15552   if (!Dcl)
   15553     return true;
   15554 
   15555   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
   15556     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
   15557       << D.getSourceRange();
   15558     return true;
   15559   }
   15560 
   15561   return Dcl;
   15562 }
   15563 
   15564 void Sema::LoadExternalVTableUses() {
   15565   if (!ExternalSource)
   15566     return;
   15567 
   15568   SmallVector<ExternalVTableUse, 4> VTables;
   15569   ExternalSource->ReadUsedVTables(VTables);
   15570   SmallVector<VTableUse, 4> NewUses;
   15571   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
   15572     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
   15573       = VTablesUsed.find(VTables[I].Record);
   15574     // Even if a definition wasn't required before, it may be required now.
   15575     if (Pos != VTablesUsed.end()) {
   15576       if (!Pos->second && VTables[I].DefinitionRequired)
   15577         Pos->second = true;
   15578       continue;
   15579     }
   15580 
   15581     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
   15582     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
   15583   }
   15584 
   15585   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
   15586 }
   15587 
   15588 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
   15589                           bool DefinitionRequired) {
   15590   // Ignore any vtable uses in unevaluated operands or for classes that do
   15591   // not have a vtable.
   15592   if (!Class->isDynamicClass() || Class->isDependentContext() ||
   15593       CurContext->isDependentContext() || isUnevaluatedContext())
   15594     return;
   15595   // Do not mark as used if compiling for the device outside of the target
   15596   // region.
   15597   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
   15598       !isInOpenMPDeclareTargetContext() &&
   15599       !isInOpenMPTargetExecutionDirective()) {
   15600     if (!DefinitionRequired)
   15601       MarkVirtualMembersReferenced(Loc, Class);
   15602     return;
   15603   }
   15604 
   15605   // Try to insert this class into the map.
   15606   LoadExternalVTableUses();
   15607   Class = Class->getCanonicalDecl();
   15608   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
   15609     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
   15610   if (!Pos.second) {
   15611     // If we already had an entry, check to see if we are promoting this vtable
   15612     // to require a definition. If so, we need to reappend to the VTableUses
   15613     // list, since we may have already processed the first entry.
   15614     if (DefinitionRequired && !Pos.first->second) {
   15615       Pos.first->second = true;
   15616     } else {
   15617       // Otherwise, we can early exit.
   15618       return;
   15619     }
   15620   } else {
   15621     // The Microsoft ABI requires that we perform the destructor body
   15622     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
   15623     // the deleting destructor is emitted with the vtable, not with the
   15624     // destructor definition as in the Itanium ABI.
   15625     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
   15626       CXXDestructorDecl *DD = Class->getDestructor();
   15627       if (DD && DD->isVirtual() && !DD->isDeleted()) {
   15628         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
   15629           // If this is an out-of-line declaration, marking it referenced will
   15630           // not do anything. Manually call CheckDestructor to look up operator
   15631           // delete().
   15632           ContextRAII SavedContext(*this, DD);
   15633           CheckDestructor(DD);
   15634         } else {
   15635           MarkFunctionReferenced(Loc, Class->getDestructor());
   15636         }
   15637       }
   15638     }
   15639   }
   15640 
   15641   // Local classes need to have their virtual members marked
   15642   // immediately. For all other classes, we mark their virtual members
   15643   // at the end of the translation unit.
   15644   if (Class->isLocalClass())
   15645     MarkVirtualMembersReferenced(Loc, Class);
   15646   else
   15647     VTableUses.push_back(std::make_pair(Class, Loc));
   15648 }
   15649 
   15650 bool Sema::DefineUsedVTables() {
   15651   LoadExternalVTableUses();
   15652   if (VTableUses.empty())
   15653     return false;
   15654 
   15655   // Note: The VTableUses vector could grow as a result of marking
   15656   // the members of a class as "used", so we check the size each
   15657   // time through the loop and prefer indices (which are stable) to
   15658   // iterators (which are not).
   15659   bool DefinedAnything = false;
   15660   for (unsigned I = 0; I != VTableUses.size(); ++I) {
   15661     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
   15662     if (!Class)
   15663       continue;
   15664     TemplateSpecializationKind ClassTSK =
   15665         Class->getTemplateSpecializationKind();
   15666 
   15667     SourceLocation Loc = VTableUses[I].second;
   15668 
   15669     bool DefineVTable = true;
   15670 
   15671     // If this class has a key function, but that key function is
   15672     // defined in another translation unit, we don't need to emit the
   15673     // vtable even though we're using it.
   15674     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
   15675     if (KeyFunction && !KeyFunction->hasBody()) {
   15676       // The key function is in another translation unit.
   15677       DefineVTable = false;
   15678       TemplateSpecializationKind TSK =
   15679           KeyFunction->getTemplateSpecializationKind();
   15680       assert(TSK != TSK_ExplicitInstantiationDefinition &&
   15681              TSK != TSK_ImplicitInstantiation &&
   15682              "Instantiations don't have key functions");
   15683       (void)TSK;
   15684     } else if (!KeyFunction) {
   15685       // If we have a class with no key function that is the subject
   15686       // of an explicit instantiation declaration, suppress the
   15687       // vtable; it will live with the explicit instantiation
   15688       // definition.
   15689       bool IsExplicitInstantiationDeclaration =
   15690           ClassTSK == TSK_ExplicitInstantiationDeclaration;
   15691       for (auto R : Class->redecls()) {
   15692         TemplateSpecializationKind TSK
   15693           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
   15694         if (TSK == TSK_ExplicitInstantiationDeclaration)
   15695           IsExplicitInstantiationDeclaration = true;
   15696         else if (TSK == TSK_ExplicitInstantiationDefinition) {
   15697           IsExplicitInstantiationDeclaration = false;
   15698           break;
   15699         }
   15700       }
   15701 
   15702       if (IsExplicitInstantiationDeclaration)
   15703         DefineVTable = false;
   15704     }
   15705 
   15706     // The exception specifications for all virtual members may be needed even
   15707     // if we are not providing an authoritative form of the vtable in this TU.
   15708     // We may choose to emit it available_externally anyway.
   15709     if (!DefineVTable) {
   15710       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
   15711       continue;
   15712     }
   15713 
   15714     // Mark all of the virtual members of this class as referenced, so
   15715     // that we can build a vtable. Then, tell the AST consumer that a
   15716     // vtable for this class is required.
   15717     DefinedAnything = true;
   15718     MarkVirtualMembersReferenced(Loc, Class);
   15719     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
   15720     if (VTablesUsed[Canonical])
   15721       Consumer.HandleVTable(Class);
   15722 
   15723     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
   15724     // no key function or the key function is inlined. Don't warn in C++ ABIs
   15725     // that lack key functions, since the user won't be able to make one.
   15726     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
   15727         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
   15728       const FunctionDecl *KeyFunctionDef = nullptr;
   15729       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
   15730                            KeyFunctionDef->isInlined())) {
   15731         Diag(Class->getLocation(),
   15732              ClassTSK == TSK_ExplicitInstantiationDefinition
   15733                  ? diag::warn_weak_template_vtable
   15734                  : diag::warn_weak_vtable)
   15735             << Class;
   15736       }
   15737     }
   15738   }
   15739   VTableUses.clear();
   15740 
   15741   return DefinedAnything;
   15742 }
   15743 
   15744 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
   15745                                                  const CXXRecordDecl *RD) {
   15746   for (const auto *I : RD->methods())
   15747     if (I->isVirtual() && !I->isPure())
   15748       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
   15749 }
   15750 
   15751 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
   15752                                         const CXXRecordDecl *RD,
   15753                                         bool ConstexprOnly) {
   15754   // Mark all functions which will appear in RD's vtable as used.
   15755   CXXFinalOverriderMap FinalOverriders;
   15756   RD->getFinalOverriders(FinalOverriders);
   15757   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
   15758                                             E = FinalOverriders.end();
   15759        I != E; ++I) {
   15760     for (OverridingMethods::const_iterator OI = I->second.begin(),
   15761                                            OE = I->second.end();
   15762          OI != OE; ++OI) {
   15763       assert(OI->second.size() > 0 && "no final overrider");
   15764       CXXMethodDecl *Overrider = OI->second.front().Method;
   15765 
   15766       // C++ [basic.def.odr]p2:
   15767       //   [...] A virtual member function is used if it is not pure. [...]
   15768       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
   15769         MarkFunctionReferenced(Loc, Overrider);
   15770     }
   15771   }
   15772 
   15773   // Only classes that have virtual bases need a VTT.
   15774   if (RD->getNumVBases() == 0)
   15775     return;
   15776 
   15777   for (const auto &I : RD->bases()) {
   15778     const auto *Base =
   15779         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
   15780     if (Base->getNumVBases() == 0)
   15781       continue;
   15782     MarkVirtualMembersReferenced(Loc, Base);
   15783   }
   15784 }
   15785 
   15786 /// SetIvarInitializers - This routine builds initialization ASTs for the
   15787 /// Objective-C implementation whose ivars need be initialized.
   15788 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
   15789   if (!getLangOpts().CPlusPlus)
   15790     return;
   15791   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
   15792     SmallVector<ObjCIvarDecl*, 8> ivars;
   15793     CollectIvarsToConstructOrDestruct(OID, ivars);
   15794     if (ivars.empty())
   15795       return;
   15796     SmallVector<CXXCtorInitializer*, 32> AllToInit;
   15797     for (unsigned i = 0; i < ivars.size(); i++) {
   15798       FieldDecl *Field = ivars[i];
   15799       if (Field->isInvalidDecl())
   15800         continue;
   15801 
   15802       CXXCtorInitializer *Member;
   15803       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
   15804       InitializationKind InitKind =
   15805         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
   15806 
   15807       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
   15808       ExprResult MemberInit =
   15809         InitSeq.Perform(*this, InitEntity, InitKind, None);
   15810       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
   15811       // Note, MemberInit could actually come back empty if no initialization
   15812       // is required (e.g., because it would call a trivial default constructor)
   15813       if (!MemberInit.get() || MemberInit.isInvalid())
   15814         continue;
   15815 
   15816       Member =
   15817         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
   15818                                          SourceLocation(),
   15819                                          MemberInit.getAs<Expr>(),
   15820                                          SourceLocation());
   15821       AllToInit.push_back(Member);
   15822 
   15823       // Be sure that the destructor is accessible and is marked as referenced.
   15824       if (const RecordType *RecordTy =
   15825               Context.getBaseElementType(Field->getType())
   15826                   ->getAs<RecordType>()) {
   15827         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
   15828         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
   15829           MarkFunctionReferenced(Field->getLocation(), Destructor);
   15830           CheckDestructorAccess(Field->getLocation(), Destructor,
   15831                             PDiag(diag::err_access_dtor_ivar)
   15832                               << Context.getBaseElementType(Field->getType()));
   15833         }
   15834       }
   15835     }
   15836     ObjCImplementation->setIvarInitializers(Context,
   15837                                             AllToInit.data(), AllToInit.size());
   15838   }
   15839 }
   15840 
   15841 static
   15842 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
   15843                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
   15844                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
   15845                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
   15846                            Sema &S) {
   15847   if (Ctor->isInvalidDecl())
   15848     return;
   15849 
   15850   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
   15851 
   15852   // Target may not be determinable yet, for instance if this is a dependent
   15853   // call in an uninstantiated template.
   15854   if (Target) {
   15855     const FunctionDecl *FNTarget = nullptr;
   15856     (void)Target->hasBody(FNTarget);
   15857     Target = const_cast<CXXConstructorDecl*>(
   15858       cast_or_null<CXXConstructorDecl>(FNTarget));
   15859   }
   15860 
   15861   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
   15862                      // Avoid dereferencing a null pointer here.
   15863                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
   15864 
   15865   if (!Current.insert(Canonical).second)
   15866     return;
   15867 
   15868   // We know that beyond here, we aren't chaining into a cycle.
   15869   if (!Target || !Target->isDelegatingConstructor() ||
   15870       Target->isInvalidDecl() || Valid.count(TCanonical)) {
   15871     Valid.insert(Current.begin(), Current.end());
   15872     Current.clear();
   15873   // We've hit a cycle.
   15874   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
   15875              Current.count(TCanonical)) {
   15876     // If we haven't diagnosed this cycle yet, do so now.
   15877     if (!Invalid.count(TCanonical)) {
   15878       S.Diag((*Ctor->init_begin())->getSourceLocation(),
   15879              diag::warn_delegating_ctor_cycle)
   15880         << Ctor;
   15881 
   15882       // Don't add a note for a function delegating directly to itself.
   15883       if (TCanonical != Canonical)
   15884         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
   15885 
   15886       CXXConstructorDecl *C = Target;
   15887       while (C->getCanonicalDecl() != Canonical) {
   15888         const FunctionDecl *FNTarget = nullptr;
   15889         (void)C->getTargetConstructor()->hasBody(FNTarget);
   15890         assert(FNTarget && "Ctor cycle through bodiless function");
   15891 
   15892         C = const_cast<CXXConstructorDecl*>(
   15893           cast<CXXConstructorDecl>(FNTarget));
   15894         S.Diag(C->getLocation(), diag::note_which_delegates_to);
   15895       }
   15896     }
   15897 
   15898     Invalid.insert(Current.begin(), Current.end());
   15899     Current.clear();
   15900   } else {
   15901     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
   15902   }
   15903 }
   15904 
   15905 
   15906 void Sema::CheckDelegatingCtorCycles() {
   15907   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
   15908 
   15909   for (DelegatingCtorDeclsType::iterator
   15910          I = DelegatingCtorDecls.begin(ExternalSource),
   15911          E = DelegatingCtorDecls.end();
   15912        I != E; ++I)
   15913     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
   15914 
   15915   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
   15916     (*CI)->setInvalidDecl();
   15917 }
   15918 
   15919 namespace {
   15920   /// AST visitor that finds references to the 'this' expression.
   15921   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
   15922     Sema &S;
   15923 
   15924   public:
   15925     explicit FindCXXThisExpr(Sema &S) : S(S) { }
   15926 
   15927     bool VisitCXXThisExpr(CXXThisExpr *E) {
   15928       S.Diag(E->getLocation(), diag::err_this_static_member_func)
   15929         << E->isImplicit();
   15930       return false;
   15931     }
   15932   };
   15933 }
   15934 
   15935 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
   15936   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
   15937   if (!TSInfo)
   15938     return false;
   15939 
   15940   TypeLoc TL = TSInfo->getTypeLoc();
   15941   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
   15942   if (!ProtoTL)
   15943     return false;
   15944 
   15945   // C++11 [expr.prim.general]p3:
   15946   //   [The expression this] shall not appear before the optional
   15947   //   cv-qualifier-seq and it shall not appear within the declaration of a
   15948   //   static member function (although its type and value category are defined
   15949   //   within a static member function as they are within a non-static member
   15950   //   function). [ Note: this is because declaration matching does not occur
   15951   //  until the complete declarator is known. - end note ]
   15952   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
   15953   FindCXXThisExpr Finder(*this);
   15954 
   15955   // If the return type came after the cv-qualifier-seq, check it now.
   15956   if (Proto->hasTrailingReturn() &&
   15957       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
   15958     return true;
   15959 
   15960   // Check the exception specification.
   15961   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
   15962     return true;
   15963 
   15964   return checkThisInStaticMemberFunctionAttributes(Method);
   15965 }
   15966 
   15967 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
   15968   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
   15969   if (!TSInfo)
   15970     return false;
   15971 
   15972   TypeLoc TL = TSInfo->getTypeLoc();
   15973   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
   15974   if (!ProtoTL)
   15975     return false;
   15976 
   15977   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
   15978   FindCXXThisExpr Finder(*this);
   15979 
   15980   switch (Proto->getExceptionSpecType()) {
   15981   case EST_Unparsed:
   15982   case EST_Uninstantiated:
   15983   case EST_Unevaluated:
   15984   case EST_BasicNoexcept:
   15985   case EST_NoThrow:
   15986   case EST_DynamicNone:
   15987   case EST_MSAny:
   15988   case EST_None:
   15989     break;
   15990 
   15991   case EST_DependentNoexcept:
   15992   case EST_NoexceptFalse:
   15993   case EST_NoexceptTrue:
   15994     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
   15995       return true;
   15996     LLVM_FALLTHROUGH;
   15997 
   15998   case EST_Dynamic:
   15999     for (const auto &E : Proto->exceptions()) {
   16000       if (!Finder.TraverseType(E))
   16001         return true;
   16002     }
   16003     break;
   16004   }
   16005 
   16006   return false;
   16007 }
   16008 
   16009 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
   16010   FindCXXThisExpr Finder(*this);
   16011 
   16012   // Check attributes.
   16013   for (const auto *A : Method->attrs()) {
   16014     // FIXME: This should be emitted by tblgen.
   16015     Expr *Arg = nullptr;
   16016     ArrayRef<Expr *> Args;
   16017     if (const auto *G = dyn_cast<GuardedByAttr>(A))
   16018       Arg = G->getArg();
   16019     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
   16020       Arg = G->getArg();
   16021     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
   16022       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
   16023     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
   16024       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
   16025     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
   16026       Arg = ETLF->getSuccessValue();
   16027       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
   16028     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
   16029       Arg = STLF->getSuccessValue();
   16030       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
   16031     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
   16032       Arg = LR->getArg();
   16033     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
   16034       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
   16035     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
   16036       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
   16037     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
   16038       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
   16039     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
   16040       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
   16041     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
   16042       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
   16043 
   16044     if (Arg && !Finder.TraverseStmt(Arg))
   16045       return true;
   16046 
   16047     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
   16048       if (!Finder.TraverseStmt(Args[I]))
   16049         return true;
   16050     }
   16051   }
   16052 
   16053   return false;
   16054 }
   16055 
   16056 void Sema::checkExceptionSpecification(
   16057     bool IsTopLevel, ExceptionSpecificationType EST,
   16058     ArrayRef<ParsedType> DynamicExceptions,
   16059     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
   16060     SmallVectorImpl<QualType> &Exceptions,
   16061     FunctionProtoType::ExceptionSpecInfo &ESI) {
   16062   Exceptions.clear();
   16063   ESI.Type = EST;
   16064   if (EST == EST_Dynamic) {
   16065     Exceptions.reserve(DynamicExceptions.size());
   16066     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
   16067       // FIXME: Preserve type source info.
   16068       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
   16069 
   16070       if (IsTopLevel) {
   16071         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   16072         collectUnexpandedParameterPacks(ET, Unexpanded);
   16073         if (!Unexpanded.empty()) {
   16074           DiagnoseUnexpandedParameterPacks(
   16075               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
   16076               Unexpanded);
   16077           continue;
   16078         }
   16079       }
   16080 
   16081       // Check that the type is valid for an exception spec, and
   16082       // drop it if not.
   16083       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
   16084         Exceptions.push_back(ET);
   16085     }
   16086     ESI.Exceptions = Exceptions;
   16087     return;
   16088   }
   16089 
   16090   if (isComputedNoexcept(EST)) {
   16091     assert((NoexceptExpr->isTypeDependent() ||
   16092             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
   16093             Context.BoolTy) &&
   16094            "Parser should have made sure that the expression is boolean");
   16095     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
   16096       ESI.Type = EST_BasicNoexcept;
   16097       return;
   16098     }
   16099 
   16100     ESI.NoexceptExpr = NoexceptExpr;
   16101     return;
   16102   }
   16103 }
   16104 
   16105 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
   16106              ExceptionSpecificationType EST,
   16107              SourceRange SpecificationRange,
   16108              ArrayRef<ParsedType> DynamicExceptions,
   16109              ArrayRef<SourceRange> DynamicExceptionRanges,
   16110              Expr *NoexceptExpr) {
   16111   if (!MethodD)
   16112     return;
   16113 
   16114   // Dig out the method we're referring to.
   16115   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
   16116     MethodD = FunTmpl->getTemplatedDecl();
   16117 
   16118   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
   16119   if (!Method)
   16120     return;
   16121 
   16122   // Check the exception specification.
   16123   llvm::SmallVector<QualType, 4> Exceptions;
   16124   FunctionProtoType::ExceptionSpecInfo ESI;
   16125   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
   16126                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
   16127                               ESI);
   16128 
   16129   // Update the exception specification on the function type.
   16130   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
   16131 
   16132   if (Method->isStatic())
   16133     checkThisInStaticMemberFunctionExceptionSpec(Method);
   16134 
   16135   if (Method->isVirtual()) {
   16136     // Check overrides, which we previously had to delay.
   16137     for (const CXXMethodDecl *O : Method->overridden_methods())
   16138       CheckOverridingFunctionExceptionSpec(Method, O);
   16139   }
   16140 }
   16141 
   16142 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
   16143 ///
   16144 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
   16145                                        SourceLocation DeclStart, Declarator &D,
   16146                                        Expr *BitWidth,
   16147                                        InClassInitStyle InitStyle,
   16148                                        AccessSpecifier AS,
   16149                                        const ParsedAttr &MSPropertyAttr) {
   16150   IdentifierInfo *II = D.getIdentifier();
   16151   if (!II) {
   16152     Diag(DeclStart, diag::err_anonymous_property);
   16153     return nullptr;
   16154   }
   16155   SourceLocation Loc = D.getIdentifierLoc();
   16156 
   16157   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   16158   QualType T = TInfo->getType();
   16159   if (getLangOpts().CPlusPlus) {
   16160     CheckExtraCXXDefaultArguments(D);
   16161 
   16162     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
   16163                                         UPPC_DataMemberType)) {
   16164       D.setInvalidType();
   16165       T = Context.IntTy;
   16166       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
   16167     }
   16168   }
   16169 
   16170   DiagnoseFunctionSpecifiers(D.getDeclSpec());
   16171 
   16172   if (D.getDeclSpec().isInlineSpecified())
   16173     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
   16174         << getLangOpts().CPlusPlus17;
   16175   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
   16176     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
   16177          diag::err_invalid_thread)
   16178       << DeclSpec::getSpecifierName(TSCS);
   16179 
   16180   // Check to see if this name was declared as a member previously
   16181   NamedDecl *PrevDecl = nullptr;
   16182   LookupResult Previous(*this, II, Loc, LookupMemberName,
   16183                         ForVisibleRedeclaration);
   16184   LookupName(Previous, S);
   16185   switch (Previous.getResultKind()) {
   16186   case LookupResult::Found:
   16187   case LookupResult::FoundUnresolvedValue:
   16188     PrevDecl = Previous.getAsSingle<NamedDecl>();
   16189     break;
   16190 
   16191   case LookupResult::FoundOverloaded:
   16192     PrevDecl = Previous.getRepresentativeDecl();
   16193     break;
   16194 
   16195   case LookupResult::NotFound:
   16196   case LookupResult::NotFoundInCurrentInstantiation:
   16197   case LookupResult::Ambiguous:
   16198     break;
   16199   }
   16200 
   16201   if (PrevDecl && PrevDecl->isTemplateParameter()) {
   16202     // Maybe we will complain about the shadowed template parameter.
   16203     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
   16204     // Just pretend that we didn't see the previous declaration.
   16205     PrevDecl = nullptr;
   16206   }
   16207 
   16208   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
   16209     PrevDecl = nullptr;
   16210 
   16211   SourceLocation TSSL = D.getBeginLoc();
   16212   MSPropertyDecl *NewPD =
   16213       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
   16214                              MSPropertyAttr.getPropertyDataGetter(),
   16215                              MSPropertyAttr.getPropertyDataSetter());
   16216   ProcessDeclAttributes(TUScope, NewPD, D);
   16217   NewPD->setAccess(AS);
   16218 
   16219   if (NewPD->isInvalidDecl())
   16220     Record->setInvalidDecl();
   16221 
   16222   if (D.getDeclSpec().isModulePrivateSpecified())
   16223     NewPD->setModulePrivate();
   16224 
   16225   if (NewPD->isInvalidDecl() && PrevDecl) {
   16226     // Don't introduce NewFD into scope; there's already something
   16227     // with the same name in the same scope.
   16228   } else if (II) {
   16229     PushOnScopeChains(NewPD, S);
   16230   } else
   16231     Record->addDecl(NewPD);
   16232 
   16233   return NewPD;
   16234 }
   16235