Home | History | Annotate | Download | only in Sema
      1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements semantic analysis for C++ declarations.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Sema/SemaInternal.h"
     15 #include "clang/AST/ASTConsumer.h"
     16 #include "clang/AST/ASTContext.h"
     17 #include "clang/AST/ASTLambda.h"
     18 #include "clang/AST/ASTMutationListener.h"
     19 #include "clang/AST/CXXInheritance.h"
     20 #include "clang/AST/CharUnits.h"
     21 #include "clang/AST/EvaluatedExprVisitor.h"
     22 #include "clang/AST/ExprCXX.h"
     23 #include "clang/AST/RecordLayout.h"
     24 #include "clang/AST/RecursiveASTVisitor.h"
     25 #include "clang/AST/StmtVisitor.h"
     26 #include "clang/AST/TypeLoc.h"
     27 #include "clang/AST/TypeOrdering.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/Template.h"
     40 #include "llvm/ADT/STLExtras.h"
     41 #include "llvm/ADT/SmallString.h"
     42 #include <map>
     43 #include <set>
     44 
     45 using namespace clang;
     46 
     47 //===----------------------------------------------------------------------===//
     48 // CheckDefaultArgumentVisitor
     49 //===----------------------------------------------------------------------===//
     50 
     51 namespace {
     52   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
     53   /// the default argument of a parameter to determine whether it
     54   /// contains any ill-formed subexpressions. For example, this will
     55   /// diagnose the use of local variables or parameters within the
     56   /// default argument expression.
     57   class CheckDefaultArgumentVisitor
     58     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
     59     Expr *DefaultArg;
     60     Sema *S;
     61 
     62   public:
     63     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
     64       : DefaultArg(defarg), S(s) {}
     65 
     66     bool VisitExpr(Expr *Node);
     67     bool VisitDeclRefExpr(DeclRefExpr *DRE);
     68     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
     69     bool VisitLambdaExpr(LambdaExpr *Lambda);
     70     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
     71   };
     72 
     73   /// VisitExpr - Visit all of the children of this expression.
     74   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
     75     bool IsInvalid = false;
     76     for (Stmt *SubStmt : Node->children())
     77       IsInvalid |= Visit(SubStmt);
     78     return IsInvalid;
     79   }
     80 
     81   /// VisitDeclRefExpr - Visit a reference to a declaration, to
     82   /// determine whether this declaration can be used in the default
     83   /// argument expression.
     84   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
     85     NamedDecl *Decl = DRE->getDecl();
     86     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
     87       // C++ [dcl.fct.default]p9
     88       //   Default arguments are evaluated each time the function is
     89       //   called. The order of evaluation of function arguments is
     90       //   unspecified. Consequently, parameters of a function shall not
     91       //   be used in default argument expressions, even if they are not
     92       //   evaluated. Parameters of a function declared before a default
     93       //   argument expression are in scope and can hide namespace and
     94       //   class member names.
     95       return S->Diag(DRE->getLocStart(),
     96                      diag::err_param_default_argument_references_param)
     97          << Param->getDeclName() << DefaultArg->getSourceRange();
     98     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
     99       // C++ [dcl.fct.default]p7
    100       //   Local variables shall not be used in default argument
    101       //   expressions.
    102       if (VDecl->isLocalVarDecl())
    103         return S->Diag(DRE->getLocStart(),
    104                        diag::err_param_default_argument_references_local)
    105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
    106     }
    107 
    108     return false;
    109   }
    110 
    111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
    112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
    113     // C++ [dcl.fct.default]p8:
    114     //   The keyword this shall not be used in a default argument of a
    115     //   member function.
    116     return S->Diag(ThisE->getLocStart(),
    117                    diag::err_param_default_argument_references_this)
    118                << ThisE->getSourceRange();
    119   }
    120 
    121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
    122     bool Invalid = false;
    123     for (PseudoObjectExpr::semantics_iterator
    124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
    125       Expr *E = *i;
    126 
    127       // Look through bindings.
    128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
    129         E = OVE->getSourceExpr();
    130         assert(E && "pseudo-object binding without source expression?");
    131       }
    132 
    133       Invalid |= Visit(E);
    134     }
    135     return Invalid;
    136   }
    137 
    138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
    139     // C++11 [expr.lambda.prim]p13:
    140     //   A lambda-expression appearing in a default argument shall not
    141     //   implicitly or explicitly capture any entity.
    142     if (Lambda->capture_begin() == Lambda->capture_end())
    143       return false;
    144 
    145     return S->Diag(Lambda->getLocStart(),
    146                    diag::err_lambda_capture_default_arg);
    147   }
    148 }
    149 
    150 void
    151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
    152                                                  const CXXMethodDecl *Method) {
    153   // If we have an MSAny spec already, don't bother.
    154   if (!Method || ComputedEST == EST_MSAny)
    155     return;
    156 
    157   const FunctionProtoType *Proto
    158     = Method->getType()->getAs<FunctionProtoType>();
    159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
    160   if (!Proto)
    161     return;
    162 
    163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
    164 
    165   // If we have a throw-all spec at this point, ignore the function.
    166   if (ComputedEST == EST_None)
    167     return;
    168 
    169   switch(EST) {
    170   // If this function can throw any exceptions, make a note of that.
    171   case EST_MSAny:
    172   case EST_None:
    173     ClearExceptions();
    174     ComputedEST = EST;
    175     return;
    176   // FIXME: If the call to this decl is using any of its default arguments, we
    177   // need to search them for potentially-throwing calls.
    178   // If this function has a basic noexcept, it doesn't affect the outcome.
    179   case EST_BasicNoexcept:
    180     return;
    181   // If we're still at noexcept(true) and there's a nothrow() callee,
    182   // change to that specification.
    183   case EST_DynamicNone:
    184     if (ComputedEST == EST_BasicNoexcept)
    185       ComputedEST = EST_DynamicNone;
    186     return;
    187   // Check out noexcept specs.
    188   case EST_ComputedNoexcept:
    189   {
    190     FunctionProtoType::NoexceptResult NR =
    191         Proto->getNoexceptSpec(Self->Context);
    192     assert(NR != FunctionProtoType::NR_NoNoexcept &&
    193            "Must have noexcept result for EST_ComputedNoexcept.");
    194     assert(NR != FunctionProtoType::NR_Dependent &&
    195            "Should not generate implicit declarations for dependent cases, "
    196            "and don't know how to handle them anyway.");
    197     // noexcept(false) -> no spec on the new function
    198     if (NR == FunctionProtoType::NR_Throw) {
    199       ClearExceptions();
    200       ComputedEST = EST_None;
    201     }
    202     // noexcept(true) won't change anything either.
    203     return;
    204   }
    205   default:
    206     break;
    207   }
    208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
    209   assert(ComputedEST != EST_None &&
    210          "Shouldn't collect exceptions when throw-all is guaranteed.");
    211   ComputedEST = EST_Dynamic;
    212   // Record the exceptions in this function's exception specification.
    213   for (const auto &E : Proto->exceptions())
    214     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
    215       Exceptions.push_back(E);
    216 }
    217 
    218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
    219   if (!E || ComputedEST == EST_MSAny)
    220     return;
    221 
    222   // FIXME:
    223   //
    224   // C++0x [except.spec]p14:
    225   //   [An] implicit exception-specification specifies the type-id T if and
    226   // only if T is allowed by the exception-specification of a function directly
    227   // invoked by f's implicit definition; f shall allow all exceptions if any
    228   // function it directly invokes allows all exceptions, and f shall allow no
    229   // exceptions if every function it directly invokes allows no exceptions.
    230   //
    231   // Note in particular that if an implicit exception-specification is generated
    232   // for a function containing a throw-expression, that specification can still
    233   // be noexcept(true).
    234   //
    235   // Note also that 'directly invoked' is not defined in the standard, and there
    236   // is no indication that we should only consider potentially-evaluated calls.
    237   //
    238   // Ultimately we should implement the intent of the standard: the exception
    239   // specification should be the set of exceptions which can be thrown by the
    240   // implicit definition. For now, we assume that any non-nothrow expression can
    241   // throw any exception.
    242 
    243   if (Self->canThrow(E))
    244     ComputedEST = EST_None;
    245 }
    246 
    247 bool
    248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
    249                               SourceLocation EqualLoc) {
    250   if (RequireCompleteType(Param->getLocation(), Param->getType(),
    251                           diag::err_typecheck_decl_incomplete_type)) {
    252     Param->setInvalidDecl();
    253     return true;
    254   }
    255 
    256   // C++ [dcl.fct.default]p5
    257   //   A default argument expression is implicitly converted (clause
    258   //   4) to the parameter type. The default argument expression has
    259   //   the same semantic constraints as the initializer expression in
    260   //   a declaration of a variable of the parameter type, using the
    261   //   copy-initialization semantics (8.5).
    262   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
    263                                                                     Param);
    264   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
    265                                                            EqualLoc);
    266   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
    267   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
    268   if (Result.isInvalid())
    269     return true;
    270   Arg = Result.getAs<Expr>();
    271 
    272   CheckCompletedExpr(Arg, EqualLoc);
    273   Arg = MaybeCreateExprWithCleanups(Arg);
    274 
    275   // Okay: add the default argument to the parameter
    276   Param->setDefaultArg(Arg);
    277 
    278   // We have already instantiated this parameter; provide each of the
    279   // instantiations with the uninstantiated default argument.
    280   UnparsedDefaultArgInstantiationsMap::iterator InstPos
    281     = UnparsedDefaultArgInstantiations.find(Param);
    282   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
    283     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
    284       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
    285 
    286     // We're done tracking this parameter's instantiations.
    287     UnparsedDefaultArgInstantiations.erase(InstPos);
    288   }
    289 
    290   return false;
    291 }
    292 
    293 /// ActOnParamDefaultArgument - Check whether the default argument
    294 /// provided for a function parameter is well-formed. If so, attach it
    295 /// to the parameter declaration.
    296 void
    297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
    298                                 Expr *DefaultArg) {
    299   if (!param || !DefaultArg)
    300     return;
    301 
    302   ParmVarDecl *Param = cast<ParmVarDecl>(param);
    303   UnparsedDefaultArgLocs.erase(Param);
    304 
    305   // Default arguments are only permitted in C++
    306   if (!getLangOpts().CPlusPlus) {
    307     Diag(EqualLoc, diag::err_param_default_argument)
    308       << DefaultArg->getSourceRange();
    309     Param->setInvalidDecl();
    310     return;
    311   }
    312 
    313   // Check for unexpanded parameter packs.
    314   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
    315     Param->setInvalidDecl();
    316     return;
    317   }
    318 
    319   // C++11 [dcl.fct.default]p3
    320   //   A default argument expression [...] shall not be specified for a
    321   //   parameter pack.
    322   if (Param->isParameterPack()) {
    323     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
    324         << DefaultArg->getSourceRange();
    325     return;
    326   }
    327 
    328   // Check that the default argument is well-formed
    329   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
    330   if (DefaultArgChecker.Visit(DefaultArg)) {
    331     Param->setInvalidDecl();
    332     return;
    333   }
    334 
    335   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
    336 }
    337 
    338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
    339 /// argument for a function parameter, but we can't parse it yet
    340 /// because we're inside a class definition. Note that this default
    341 /// argument will be parsed later.
    342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
    343                                              SourceLocation EqualLoc,
    344                                              SourceLocation ArgLoc) {
    345   if (!param)
    346     return;
    347 
    348   ParmVarDecl *Param = cast<ParmVarDecl>(param);
    349   Param->setUnparsedDefaultArg();
    350   UnparsedDefaultArgLocs[Param] = ArgLoc;
    351 }
    352 
    353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
    354 /// the default argument for the parameter param failed.
    355 void Sema::ActOnParamDefaultArgumentError(Decl *param,
    356                                           SourceLocation EqualLoc) {
    357   if (!param)
    358     return;
    359 
    360   ParmVarDecl *Param = cast<ParmVarDecl>(param);
    361   Param->setInvalidDecl();
    362   UnparsedDefaultArgLocs.erase(Param);
    363   Param->setDefaultArg(new(Context)
    364                        OpaqueValueExpr(EqualLoc,
    365                                        Param->getType().getNonReferenceType(),
    366                                        VK_RValue));
    367 }
    368 
    369 /// CheckExtraCXXDefaultArguments - Check for any extra default
    370 /// arguments in the declarator, which is not a function declaration
    371 /// or definition and therefore is not permitted to have default
    372 /// arguments. This routine should be invoked for every declarator
    373 /// that is not a function declaration or definition.
    374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
    375   // C++ [dcl.fct.default]p3
    376   //   A default argument expression shall be specified only in the
    377   //   parameter-declaration-clause of a function declaration or in a
    378   //   template-parameter (14.1). It shall not be specified for a
    379   //   parameter pack. If it is specified in a
    380   //   parameter-declaration-clause, it shall not occur within a
    381   //   declarator or abstract-declarator of a parameter-declaration.
    382   bool MightBeFunction = D.isFunctionDeclarationContext();
    383   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
    384     DeclaratorChunk &chunk = D.getTypeObject(i);
    385     if (chunk.Kind == DeclaratorChunk::Function) {
    386       if (MightBeFunction) {
    387         // This is a function declaration. It can have default arguments, but
    388         // keep looking in case its return type is a function type with default
    389         // arguments.
    390         MightBeFunction = false;
    391         continue;
    392       }
    393       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
    394            ++argIdx) {
    395         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
    396         if (Param->hasUnparsedDefaultArg()) {
    397           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
    398           SourceRange SR;
    399           if (Toks->size() > 1)
    400             SR = SourceRange((*Toks)[1].getLocation(),
    401                              Toks->back().getLocation());
    402           else
    403             SR = UnparsedDefaultArgLocs[Param];
    404           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
    405             << SR;
    406           delete Toks;
    407           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
    408         } else if (Param->getDefaultArg()) {
    409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
    410             << Param->getDefaultArg()->getSourceRange();
    411           Param->setDefaultArg(nullptr);
    412         }
    413       }
    414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
    415       MightBeFunction = false;
    416     }
    417   }
    418 }
    419 
    420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
    421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
    422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
    423     if (!PVD->hasDefaultArg())
    424       return false;
    425     if (!PVD->hasInheritedDefaultArg())
    426       return true;
    427   }
    428   return false;
    429 }
    430 
    431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
    432 /// function, once we already know that they have the same
    433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
    434 /// error, false otherwise.
    435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
    436                                 Scope *S) {
    437   bool Invalid = false;
    438 
    439   // The declaration context corresponding to the scope is the semantic
    440   // parent, unless this is a local function declaration, in which case
    441   // it is that surrounding function.
    442   DeclContext *ScopeDC = New->isLocalExternDecl()
    443                              ? New->getLexicalDeclContext()
    444                              : New->getDeclContext();
    445 
    446   // Find the previous declaration for the purpose of default arguments.
    447   FunctionDecl *PrevForDefaultArgs = Old;
    448   for (/**/; PrevForDefaultArgs;
    449        // Don't bother looking back past the latest decl if this is a local
    450        // extern declaration; nothing else could work.
    451        PrevForDefaultArgs = New->isLocalExternDecl()
    452                                 ? nullptr
    453                                 : PrevForDefaultArgs->getPreviousDecl()) {
    454     // Ignore hidden declarations.
    455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
    456       continue;
    457 
    458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
    459         !New->isCXXClassMember()) {
    460       // Ignore default arguments of old decl if they are not in
    461       // the same scope and this is not an out-of-line definition of
    462       // a member function.
    463       continue;
    464     }
    465 
    466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
    467       // If only one of these is a local function declaration, then they are
    468       // declared in different scopes, even though isDeclInScope may think
    469       // they're in the same scope. (If both are local, the scope check is
    470       // sufficent, and if neither is local, then they are in the same scope.)
    471       continue;
    472     }
    473 
    474     // We found our guy.
    475     break;
    476   }
    477 
    478   // C++ [dcl.fct.default]p4:
    479   //   For non-template functions, default arguments can be added in
    480   //   later declarations of a function in the same
    481   //   scope. Declarations in different scopes have completely
    482   //   distinct sets of default arguments. That is, declarations in
    483   //   inner scopes do not acquire default arguments from
    484   //   declarations in outer scopes, and vice versa. In a given
    485   //   function declaration, all parameters subsequent to a
    486   //   parameter with a default argument shall have default
    487   //   arguments supplied in this or previous declarations. A
    488   //   default argument shall not be redefined by a later
    489   //   declaration (not even to the same value).
    490   //
    491   // C++ [dcl.fct.default]p6:
    492   //   Except for member functions of class templates, the default arguments
    493   //   in a member function definition that appears outside of the class
    494   //   definition are added to the set of default arguments provided by the
    495   //   member function declaration in the class definition.
    496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
    497                                        ? PrevForDefaultArgs->getNumParams()
    498                                        : 0;
    499        p < NumParams; ++p) {
    500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
    501     ParmVarDecl *NewParam = New->getParamDecl(p);
    502 
    503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
    504     bool NewParamHasDfl = NewParam->hasDefaultArg();
    505 
    506     if (OldParamHasDfl && NewParamHasDfl) {
    507       unsigned DiagDefaultParamID =
    508         diag::err_param_default_argument_redefinition;
    509 
    510       // MSVC accepts that default parameters be redefined for member functions
    511       // of template class. The new default parameter's value is ignored.
    512       Invalid = true;
    513       if (getLangOpts().MicrosoftExt) {
    514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
    515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
    516           // Merge the old default argument into the new parameter.
    517           NewParam->setHasInheritedDefaultArg();
    518           if (OldParam->hasUninstantiatedDefaultArg())
    519             NewParam->setUninstantiatedDefaultArg(
    520                                       OldParam->getUninstantiatedDefaultArg());
    521           else
    522             NewParam->setDefaultArg(OldParam->getInit());
    523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
    524           Invalid = false;
    525         }
    526       }
    527 
    528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
    529       // hint here. Alternatively, we could walk the type-source information
    530       // for NewParam to find the last source location in the type... but it
    531       // isn't worth the effort right now. This is the kind of test case that
    532       // is hard to get right:
    533       //   int f(int);
    534       //   void g(int (*fp)(int) = f);
    535       //   void g(int (*fp)(int) = &f);
    536       Diag(NewParam->getLocation(), DiagDefaultParamID)
    537         << NewParam->getDefaultArgRange();
    538 
    539       // Look for the function declaration where the default argument was
    540       // actually written, which may be a declaration prior to Old.
    541       for (auto Older = PrevForDefaultArgs;
    542            OldParam->hasInheritedDefaultArg(); /**/) {
    543         Older = Older->getPreviousDecl();
    544         OldParam = Older->getParamDecl(p);
    545       }
    546 
    547       Diag(OldParam->getLocation(), diag::note_previous_definition)
    548         << OldParam->getDefaultArgRange();
    549     } else if (OldParamHasDfl) {
    550       // Merge the old default argument into the new parameter.
    551       // It's important to use getInit() here;  getDefaultArg()
    552       // strips off any top-level ExprWithCleanups.
    553       NewParam->setHasInheritedDefaultArg();
    554       if (OldParam->hasUnparsedDefaultArg())
    555         NewParam->setUnparsedDefaultArg();
    556       else if (OldParam->hasUninstantiatedDefaultArg())
    557         NewParam->setUninstantiatedDefaultArg(
    558                                       OldParam->getUninstantiatedDefaultArg());
    559       else
    560         NewParam->setDefaultArg(OldParam->getInit());
    561     } else if (NewParamHasDfl) {
    562       if (New->getDescribedFunctionTemplate()) {
    563         // Paragraph 4, quoted above, only applies to non-template functions.
    564         Diag(NewParam->getLocation(),
    565              diag::err_param_default_argument_template_redecl)
    566           << NewParam->getDefaultArgRange();
    567         Diag(PrevForDefaultArgs->getLocation(),
    568              diag::note_template_prev_declaration)
    569             << false;
    570       } else if (New->getTemplateSpecializationKind()
    571                    != TSK_ImplicitInstantiation &&
    572                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
    573         // C++ [temp.expr.spec]p21:
    574         //   Default function arguments shall not be specified in a declaration
    575         //   or a definition for one of the following explicit specializations:
    576         //     - the explicit specialization of a function template;
    577         //     - the explicit specialization of a member function template;
    578         //     - the explicit specialization of a member function of a class
    579         //       template where the class template specialization to which the
    580         //       member function specialization belongs is implicitly
    581         //       instantiated.
    582         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
    583           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
    584           << New->getDeclName()
    585           << NewParam->getDefaultArgRange();
    586       } else if (New->getDeclContext()->isDependentContext()) {
    587         // C++ [dcl.fct.default]p6 (DR217):
    588         //   Default arguments for a member function of a class template shall
    589         //   be specified on the initial declaration of the member function
    590         //   within the class template.
    591         //
    592         // Reading the tea leaves a bit in DR217 and its reference to DR205
    593         // leads me to the conclusion that one cannot add default function
    594         // arguments for an out-of-line definition of a member function of a
    595         // dependent type.
    596         int WhichKind = 2;
    597         if (CXXRecordDecl *Record
    598               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
    599           if (Record->getDescribedClassTemplate())
    600             WhichKind = 0;
    601           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
    602             WhichKind = 1;
    603           else
    604             WhichKind = 2;
    605         }
    606 
    607         Diag(NewParam->getLocation(),
    608              diag::err_param_default_argument_member_template_redecl)
    609           << WhichKind
    610           << NewParam->getDefaultArgRange();
    611       }
    612     }
    613   }
    614 
    615   // DR1344: If a default argument is added outside a class definition and that
    616   // default argument makes the function a special member function, the program
    617   // is ill-formed. This can only happen for constructors.
    618   if (isa<CXXConstructorDecl>(New) &&
    619       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
    620     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
    621                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
    622     if (NewSM != OldSM) {
    623       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
    624       assert(NewParam->hasDefaultArg());
    625       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
    626         << NewParam->getDefaultArgRange() << NewSM;
    627       Diag(Old->getLocation(), diag::note_previous_declaration);
    628     }
    629   }
    630 
    631   const FunctionDecl *Def;
    632   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
    633   // template has a constexpr specifier then all its declarations shall
    634   // contain the constexpr specifier.
    635   if (New->isConstexpr() != Old->isConstexpr()) {
    636     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
    637       << New << New->isConstexpr();
    638     Diag(Old->getLocation(), diag::note_previous_declaration);
    639     Invalid = true;
    640   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
    641              Old->isDefined(Def)) {
    642     // C++11 [dcl.fcn.spec]p4:
    643     //   If the definition of a function appears in a translation unit before its
    644     //   first declaration as inline, the program is ill-formed.
    645     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
    646     Diag(Def->getLocation(), diag::note_previous_definition);
    647     Invalid = true;
    648   }
    649 
    650   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
    651   // argument expression, that declaration shall be a definition and shall be
    652   // the only declaration of the function or function template in the
    653   // translation unit.
    654   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
    655       functionDeclHasDefaultArgument(Old)) {
    656     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
    657     Diag(Old->getLocation(), diag::note_previous_declaration);
    658     Invalid = true;
    659   }
    660 
    661   if (CheckEquivalentExceptionSpec(Old, New))
    662     Invalid = true;
    663 
    664   return Invalid;
    665 }
    666 
    667 /// \brief Merge the exception specifications of two variable declarations.
    668 ///
    669 /// This is called when there's a redeclaration of a VarDecl. The function
    670 /// checks if the redeclaration might have an exception specification and
    671 /// validates compatibility and merges the specs if necessary.
    672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
    673   // Shortcut if exceptions are disabled.
    674   if (!getLangOpts().CXXExceptions)
    675     return;
    676 
    677   assert(Context.hasSameType(New->getType(), Old->getType()) &&
    678          "Should only be called if types are otherwise the same.");
    679 
    680   QualType NewType = New->getType();
    681   QualType OldType = Old->getType();
    682 
    683   // We're only interested in pointers and references to functions, as well
    684   // as pointers to member functions.
    685   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
    686     NewType = R->getPointeeType();
    687     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
    688   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
    689     NewType = P->getPointeeType();
    690     OldType = OldType->getAs<PointerType>()->getPointeeType();
    691   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
    692     NewType = M->getPointeeType();
    693     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
    694   }
    695 
    696   if (!NewType->isFunctionProtoType())
    697     return;
    698 
    699   // There's lots of special cases for functions. For function pointers, system
    700   // libraries are hopefully not as broken so that we don't need these
    701   // workarounds.
    702   if (CheckEquivalentExceptionSpec(
    703         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
    704         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
    705     New->setInvalidDecl();
    706   }
    707 }
    708 
    709 /// CheckCXXDefaultArguments - Verify that the default arguments for a
    710 /// function declaration are well-formed according to C++
    711 /// [dcl.fct.default].
    712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
    713   unsigned NumParams = FD->getNumParams();
    714   unsigned p;
    715 
    716   // Find first parameter with a default argument
    717   for (p = 0; p < NumParams; ++p) {
    718     ParmVarDecl *Param = FD->getParamDecl(p);
    719     if (Param->hasDefaultArg())
    720       break;
    721   }
    722 
    723   // C++11 [dcl.fct.default]p4:
    724   //   In a given function declaration, each parameter subsequent to a parameter
    725   //   with a default argument shall have a default argument supplied in this or
    726   //   a previous declaration or shall be a function parameter pack. A default
    727   //   argument shall not be redefined by a later declaration (not even to the
    728   //   same value).
    729   unsigned LastMissingDefaultArg = 0;
    730   for (; p < NumParams; ++p) {
    731     ParmVarDecl *Param = FD->getParamDecl(p);
    732     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
    733       if (Param->isInvalidDecl())
    734         /* We already complained about this parameter. */;
    735       else if (Param->getIdentifier())
    736         Diag(Param->getLocation(),
    737              diag::err_param_default_argument_missing_name)
    738           << Param->getIdentifier();
    739       else
    740         Diag(Param->getLocation(),
    741              diag::err_param_default_argument_missing);
    742 
    743       LastMissingDefaultArg = p;
    744     }
    745   }
    746 
    747   if (LastMissingDefaultArg > 0) {
    748     // Some default arguments were missing. Clear out all of the
    749     // default arguments up to (and including) the last missing
    750     // default argument, so that we leave the function parameters
    751     // in a semantically valid state.
    752     for (p = 0; p <= LastMissingDefaultArg; ++p) {
    753       ParmVarDecl *Param = FD->getParamDecl(p);
    754       if (Param->hasDefaultArg()) {
    755         Param->setDefaultArg(nullptr);
    756       }
    757     }
    758   }
    759 }
    760 
    761 // CheckConstexprParameterTypes - Check whether a function's parameter types
    762 // are all literal types. If so, return true. If not, produce a suitable
    763 // diagnostic and return false.
    764 static bool CheckConstexprParameterTypes(Sema &SemaRef,
    765                                          const FunctionDecl *FD) {
    766   unsigned ArgIndex = 0;
    767   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
    768   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
    769                                               e = FT->param_type_end();
    770        i != e; ++i, ++ArgIndex) {
    771     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
    772     SourceLocation ParamLoc = PD->getLocation();
    773     if (!(*i)->isDependentType() &&
    774         SemaRef.RequireLiteralType(ParamLoc, *i,
    775                                    diag::err_constexpr_non_literal_param,
    776                                    ArgIndex+1, PD->getSourceRange(),
    777                                    isa<CXXConstructorDecl>(FD)))
    778       return false;
    779   }
    780   return true;
    781 }
    782 
    783 /// \brief Get diagnostic %select index for tag kind for
    784 /// record diagnostic message.
    785 /// WARNING: Indexes apply to particular diagnostics only!
    786 ///
    787 /// \returns diagnostic %select index.
    788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
    789   switch (Tag) {
    790   case TTK_Struct: return 0;
    791   case TTK_Interface: return 1;
    792   case TTK_Class:  return 2;
    793   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
    794   }
    795 }
    796 
    797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
    798 // the requirements of a constexpr function definition or a constexpr
    799 // constructor definition. If so, return true. If not, produce appropriate
    800 // diagnostics and return false.
    801 //
    802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
    803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
    804   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
    805   if (MD && MD->isInstance()) {
    806     // C++11 [dcl.constexpr]p4:
    807     //  The definition of a constexpr constructor shall satisfy the following
    808     //  constraints:
    809     //  - the class shall not have any virtual base classes;
    810     const CXXRecordDecl *RD = MD->getParent();
    811     if (RD->getNumVBases()) {
    812       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
    813         << isa<CXXConstructorDecl>(NewFD)
    814         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
    815       for (const auto &I : RD->vbases())
    816         Diag(I.getLocStart(),
    817              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
    818       return false;
    819     }
    820   }
    821 
    822   if (!isa<CXXConstructorDecl>(NewFD)) {
    823     // C++11 [dcl.constexpr]p3:
    824     //  The definition of a constexpr function shall satisfy the following
    825     //  constraints:
    826     // - it shall not be virtual;
    827     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
    828     if (Method && Method->isVirtual()) {
    829       Method = Method->getCanonicalDecl();
    830       Diag(Method->getLocation(), diag::err_constexpr_virtual);
    831 
    832       // If it's not obvious why this function is virtual, find an overridden
    833       // function which uses the 'virtual' keyword.
    834       const CXXMethodDecl *WrittenVirtual = Method;
    835       while (!WrittenVirtual->isVirtualAsWritten())
    836         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
    837       if (WrittenVirtual != Method)
    838         Diag(WrittenVirtual->getLocation(),
    839              diag::note_overridden_virtual_function);
    840       return false;
    841     }
    842 
    843     // - its return type shall be a literal type;
    844     QualType RT = NewFD->getReturnType();
    845     if (!RT->isDependentType() &&
    846         RequireLiteralType(NewFD->getLocation(), RT,
    847                            diag::err_constexpr_non_literal_return))
    848       return false;
    849   }
    850 
    851   // - each of its parameter types shall be a literal type;
    852   if (!CheckConstexprParameterTypes(*this, NewFD))
    853     return false;
    854 
    855   return true;
    856 }
    857 
    858 /// Check the given declaration statement is legal within a constexpr function
    859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
    860 ///
    861 /// \return true if the body is OK (maybe only as an extension), false if we
    862 ///         have diagnosed a problem.
    863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
    864                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
    865   // C++11 [dcl.constexpr]p3 and p4:
    866   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
    867   //  contain only
    868   for (const auto *DclIt : DS->decls()) {
    869     switch (DclIt->getKind()) {
    870     case Decl::StaticAssert:
    871     case Decl::Using:
    872     case Decl::UsingShadow:
    873     case Decl::UsingDirective:
    874     case Decl::UnresolvedUsingTypename:
    875     case Decl::UnresolvedUsingValue:
    876       //   - static_assert-declarations
    877       //   - using-declarations,
    878       //   - using-directives,
    879       continue;
    880 
    881     case Decl::Typedef:
    882     case Decl::TypeAlias: {
    883       //   - typedef declarations and alias-declarations that do not define
    884       //     classes or enumerations,
    885       const auto *TN = cast<TypedefNameDecl>(DclIt);
    886       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
    887         // Don't allow variably-modified types in constexpr functions.
    888         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
    889         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
    890           << TL.getSourceRange() << TL.getType()
    891           << isa<CXXConstructorDecl>(Dcl);
    892         return false;
    893       }
    894       continue;
    895     }
    896 
    897     case Decl::Enum:
    898     case Decl::CXXRecord:
    899       // C++1y allows types to be defined, not just declared.
    900       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
    901         SemaRef.Diag(DS->getLocStart(),
    902                      SemaRef.getLangOpts().CPlusPlus14
    903                        ? diag::warn_cxx11_compat_constexpr_type_definition
    904                        : diag::ext_constexpr_type_definition)
    905           << isa<CXXConstructorDecl>(Dcl);
    906       continue;
    907 
    908     case Decl::EnumConstant:
    909     case Decl::IndirectField:
    910     case Decl::ParmVar:
    911       // These can only appear with other declarations which are banned in
    912       // C++11 and permitted in C++1y, so ignore them.
    913       continue;
    914 
    915     case Decl::Var: {
    916       // C++1y [dcl.constexpr]p3 allows anything except:
    917       //   a definition of a variable of non-literal type or of static or
    918       //   thread storage duration or for which no initialization is performed.
    919       const auto *VD = cast<VarDecl>(DclIt);
    920       if (VD->isThisDeclarationADefinition()) {
    921         if (VD->isStaticLocal()) {
    922           SemaRef.Diag(VD->getLocation(),
    923                        diag::err_constexpr_local_var_static)
    924             << isa<CXXConstructorDecl>(Dcl)
    925             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
    926           return false;
    927         }
    928         if (!VD->getType()->isDependentType() &&
    929             SemaRef.RequireLiteralType(
    930               VD->getLocation(), VD->getType(),
    931               diag::err_constexpr_local_var_non_literal_type,
    932               isa<CXXConstructorDecl>(Dcl)))
    933           return false;
    934         if (!VD->getType()->isDependentType() &&
    935             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
    936           SemaRef.Diag(VD->getLocation(),
    937                        diag::err_constexpr_local_var_no_init)
    938             << isa<CXXConstructorDecl>(Dcl);
    939           return false;
    940         }
    941       }
    942       SemaRef.Diag(VD->getLocation(),
    943                    SemaRef.getLangOpts().CPlusPlus14
    944                     ? diag::warn_cxx11_compat_constexpr_local_var
    945                     : diag::ext_constexpr_local_var)
    946         << isa<CXXConstructorDecl>(Dcl);
    947       continue;
    948     }
    949 
    950     case Decl::NamespaceAlias:
    951     case Decl::Function:
    952       // These are disallowed in C++11 and permitted in C++1y. Allow them
    953       // everywhere as an extension.
    954       if (!Cxx1yLoc.isValid())
    955         Cxx1yLoc = DS->getLocStart();
    956       continue;
    957 
    958     default:
    959       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
    960         << isa<CXXConstructorDecl>(Dcl);
    961       return false;
    962     }
    963   }
    964 
    965   return true;
    966 }
    967 
    968 /// Check that the given field is initialized within a constexpr constructor.
    969 ///
    970 /// \param Dcl The constexpr constructor being checked.
    971 /// \param Field The field being checked. This may be a member of an anonymous
    972 ///        struct or union nested within the class being checked.
    973 /// \param Inits All declarations, including anonymous struct/union members and
    974 ///        indirect members, for which any initialization was provided.
    975 /// \param Diagnosed Set to true if an error is produced.
    976 static void CheckConstexprCtorInitializer(Sema &SemaRef,
    977                                           const FunctionDecl *Dcl,
    978                                           FieldDecl *Field,
    979                                           llvm::SmallSet<Decl*, 16> &Inits,
    980                                           bool &Diagnosed) {
    981   if (Field->isInvalidDecl())
    982     return;
    983 
    984   if (Field->isUnnamedBitfield())
    985     return;
    986 
    987   // Anonymous unions with no variant members and empty anonymous structs do not
    988   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
    989   // indirect fields don't need initializing.
    990   if (Field->isAnonymousStructOrUnion() &&
    991       (Field->getType()->isUnionType()
    992            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
    993            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
    994     return;
    995 
    996   if (!Inits.count(Field)) {
    997     if (!Diagnosed) {
    998       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
    999       Diagnosed = true;
   1000     }
   1001     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
   1002   } else if (Field->isAnonymousStructOrUnion()) {
   1003     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
   1004     for (auto *I : RD->fields())
   1005       // If an anonymous union contains an anonymous struct of which any member
   1006       // is initialized, all members must be initialized.
   1007       if (!RD->isUnion() || Inits.count(I))
   1008         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
   1009   }
   1010 }
   1011 
   1012 /// Check the provided statement is allowed in a constexpr function
   1013 /// definition.
   1014 static bool
   1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
   1016                            SmallVectorImpl<SourceLocation> &ReturnStmts,
   1017                            SourceLocation &Cxx1yLoc) {
   1018   // - its function-body shall be [...] a compound-statement that contains only
   1019   switch (S->getStmtClass()) {
   1020   case Stmt::NullStmtClass:
   1021     //   - null statements,
   1022     return true;
   1023 
   1024   case Stmt::DeclStmtClass:
   1025     //   - static_assert-declarations
   1026     //   - using-declarations,
   1027     //   - using-directives,
   1028     //   - typedef declarations and alias-declarations that do not define
   1029     //     classes or enumerations,
   1030     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
   1031       return false;
   1032     return true;
   1033 
   1034   case Stmt::ReturnStmtClass:
   1035     //   - and exactly one return statement;
   1036     if (isa<CXXConstructorDecl>(Dcl)) {
   1037       // C++1y allows return statements in constexpr constructors.
   1038       if (!Cxx1yLoc.isValid())
   1039         Cxx1yLoc = S->getLocStart();
   1040       return true;
   1041     }
   1042 
   1043     ReturnStmts.push_back(S->getLocStart());
   1044     return true;
   1045 
   1046   case Stmt::CompoundStmtClass: {
   1047     // C++1y allows compound-statements.
   1048     if (!Cxx1yLoc.isValid())
   1049       Cxx1yLoc = S->getLocStart();
   1050 
   1051     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
   1052     for (auto *BodyIt : CompStmt->body()) {
   1053       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
   1054                                       Cxx1yLoc))
   1055         return false;
   1056     }
   1057     return true;
   1058   }
   1059 
   1060   case Stmt::AttributedStmtClass:
   1061     if (!Cxx1yLoc.isValid())
   1062       Cxx1yLoc = S->getLocStart();
   1063     return true;
   1064 
   1065   case Stmt::IfStmtClass: {
   1066     // C++1y allows if-statements.
   1067     if (!Cxx1yLoc.isValid())
   1068       Cxx1yLoc = S->getLocStart();
   1069 
   1070     IfStmt *If = cast<IfStmt>(S);
   1071     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
   1072                                     Cxx1yLoc))
   1073       return false;
   1074     if (If->getElse() &&
   1075         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
   1076                                     Cxx1yLoc))
   1077       return false;
   1078     return true;
   1079   }
   1080 
   1081   case Stmt::WhileStmtClass:
   1082   case Stmt::DoStmtClass:
   1083   case Stmt::ForStmtClass:
   1084   case Stmt::CXXForRangeStmtClass:
   1085   case Stmt::ContinueStmtClass:
   1086     // C++1y allows all of these. We don't allow them as extensions in C++11,
   1087     // because they don't make sense without variable mutation.
   1088     if (!SemaRef.getLangOpts().CPlusPlus14)
   1089       break;
   1090     if (!Cxx1yLoc.isValid())
   1091       Cxx1yLoc = S->getLocStart();
   1092     for (Stmt *SubStmt : S->children())
   1093       if (SubStmt &&
   1094           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
   1095                                       Cxx1yLoc))
   1096         return false;
   1097     return true;
   1098 
   1099   case Stmt::SwitchStmtClass:
   1100   case Stmt::CaseStmtClass:
   1101   case Stmt::DefaultStmtClass:
   1102   case Stmt::BreakStmtClass:
   1103     // C++1y allows switch-statements, and since they don't need variable
   1104     // mutation, we can reasonably allow them in C++11 as an extension.
   1105     if (!Cxx1yLoc.isValid())
   1106       Cxx1yLoc = S->getLocStart();
   1107     for (Stmt *SubStmt : S->children())
   1108       if (SubStmt &&
   1109           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
   1110                                       Cxx1yLoc))
   1111         return false;
   1112     return true;
   1113 
   1114   default:
   1115     if (!isa<Expr>(S))
   1116       break;
   1117 
   1118     // C++1y allows expression-statements.
   1119     if (!Cxx1yLoc.isValid())
   1120       Cxx1yLoc = S->getLocStart();
   1121     return true;
   1122   }
   1123 
   1124   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
   1125     << isa<CXXConstructorDecl>(Dcl);
   1126   return false;
   1127 }
   1128 
   1129 /// Check the body for the given constexpr function declaration only contains
   1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
   1131 ///
   1132 /// \return true if the body is OK, false if we have diagnosed a problem.
   1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
   1134   if (isa<CXXTryStmt>(Body)) {
   1135     // C++11 [dcl.constexpr]p3:
   1136     //  The definition of a constexpr function shall satisfy the following
   1137     //  constraints: [...]
   1138     // - its function-body shall be = delete, = default, or a
   1139     //   compound-statement
   1140     //
   1141     // C++11 [dcl.constexpr]p4:
   1142     //  In the definition of a constexpr constructor, [...]
   1143     // - its function-body shall not be a function-try-block;
   1144     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
   1145       << isa<CXXConstructorDecl>(Dcl);
   1146     return false;
   1147   }
   1148 
   1149   SmallVector<SourceLocation, 4> ReturnStmts;
   1150 
   1151   // - its function-body shall be [...] a compound-statement that contains only
   1152   //   [... list of cases ...]
   1153   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
   1154   SourceLocation Cxx1yLoc;
   1155   for (auto *BodyIt : CompBody->body()) {
   1156     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
   1157       return false;
   1158   }
   1159 
   1160   if (Cxx1yLoc.isValid())
   1161     Diag(Cxx1yLoc,
   1162          getLangOpts().CPlusPlus14
   1163            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
   1164            : diag::ext_constexpr_body_invalid_stmt)
   1165       << isa<CXXConstructorDecl>(Dcl);
   1166 
   1167   if (const CXXConstructorDecl *Constructor
   1168         = dyn_cast<CXXConstructorDecl>(Dcl)) {
   1169     const CXXRecordDecl *RD = Constructor->getParent();
   1170     // DR1359:
   1171     // - every non-variant non-static data member and base class sub-object
   1172     //   shall be initialized;
   1173     // DR1460:
   1174     // - if the class is a union having variant members, exactly one of them
   1175     //   shall be initialized;
   1176     if (RD->isUnion()) {
   1177       if (Constructor->getNumCtorInitializers() == 0 &&
   1178           RD->hasVariantMembers()) {
   1179         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
   1180         return false;
   1181       }
   1182     } else if (!Constructor->isDependentContext() &&
   1183                !Constructor->isDelegatingConstructor()) {
   1184       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
   1185 
   1186       // Skip detailed checking if we have enough initializers, and we would
   1187       // allow at most one initializer per member.
   1188       bool AnyAnonStructUnionMembers = false;
   1189       unsigned Fields = 0;
   1190       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
   1191            E = RD->field_end(); I != E; ++I, ++Fields) {
   1192         if (I->isAnonymousStructOrUnion()) {
   1193           AnyAnonStructUnionMembers = true;
   1194           break;
   1195         }
   1196       }
   1197       // DR1460:
   1198       // - if the class is a union-like class, but is not a union, for each of
   1199       //   its anonymous union members having variant members, exactly one of
   1200       //   them shall be initialized;
   1201       if (AnyAnonStructUnionMembers ||
   1202           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
   1203         // Check initialization of non-static data members. Base classes are
   1204         // always initialized so do not need to be checked. Dependent bases
   1205         // might not have initializers in the member initializer list.
   1206         llvm::SmallSet<Decl*, 16> Inits;
   1207         for (const auto *I: Constructor->inits()) {
   1208           if (FieldDecl *FD = I->getMember())
   1209             Inits.insert(FD);
   1210           else if (IndirectFieldDecl *ID = I->getIndirectMember())
   1211             Inits.insert(ID->chain_begin(), ID->chain_end());
   1212         }
   1213 
   1214         bool Diagnosed = false;
   1215         for (auto *I : RD->fields())
   1216           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
   1217         if (Diagnosed)
   1218           return false;
   1219       }
   1220     }
   1221   } else {
   1222     if (ReturnStmts.empty()) {
   1223       // C++1y doesn't require constexpr functions to contain a 'return'
   1224       // statement. We still do, unless the return type might be void, because
   1225       // otherwise if there's no return statement, the function cannot
   1226       // be used in a core constant expression.
   1227       bool OK = getLangOpts().CPlusPlus14 &&
   1228                 (Dcl->getReturnType()->isVoidType() ||
   1229                  Dcl->getReturnType()->isDependentType());
   1230       Diag(Dcl->getLocation(),
   1231            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
   1232               : diag::err_constexpr_body_no_return);
   1233       if (!OK)
   1234         return false;
   1235     } else if (ReturnStmts.size() > 1) {
   1236       Diag(ReturnStmts.back(),
   1237            getLangOpts().CPlusPlus14
   1238              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
   1239              : diag::ext_constexpr_body_multiple_return);
   1240       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
   1241         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
   1242     }
   1243   }
   1244 
   1245   // C++11 [dcl.constexpr]p5:
   1246   //   if no function argument values exist such that the function invocation
   1247   //   substitution would produce a constant expression, the program is
   1248   //   ill-formed; no diagnostic required.
   1249   // C++11 [dcl.constexpr]p3:
   1250   //   - every constructor call and implicit conversion used in initializing the
   1251   //     return value shall be one of those allowed in a constant expression.
   1252   // C++11 [dcl.constexpr]p4:
   1253   //   - every constructor involved in initializing non-static data members and
   1254   //     base class sub-objects shall be a constexpr constructor.
   1255   SmallVector<PartialDiagnosticAt, 8> Diags;
   1256   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
   1257     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
   1258       << isa<CXXConstructorDecl>(Dcl);
   1259     for (size_t I = 0, N = Diags.size(); I != N; ++I)
   1260       Diag(Diags[I].first, Diags[I].second);
   1261     // Don't return false here: we allow this for compatibility in
   1262     // system headers.
   1263   }
   1264 
   1265   return true;
   1266 }
   1267 
   1268 /// isCurrentClassName - Determine whether the identifier II is the
   1269 /// name of the class type currently being defined. In the case of
   1270 /// nested classes, this will only return true if II is the name of
   1271 /// the innermost class.
   1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
   1273                               const CXXScopeSpec *SS) {
   1274   assert(getLangOpts().CPlusPlus && "No class names in C!");
   1275 
   1276   CXXRecordDecl *CurDecl;
   1277   if (SS && SS->isSet() && !SS->isInvalid()) {
   1278     DeclContext *DC = computeDeclContext(*SS, true);
   1279     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
   1280   } else
   1281     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
   1282 
   1283   if (CurDecl && CurDecl->getIdentifier())
   1284     return &II == CurDecl->getIdentifier();
   1285   return false;
   1286 }
   1287 
   1288 /// \brief Determine whether the identifier II is a typo for the name of
   1289 /// the class type currently being defined. If so, update it to the identifier
   1290 /// that should have been used.
   1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
   1292   assert(getLangOpts().CPlusPlus && "No class names in C!");
   1293 
   1294   if (!getLangOpts().SpellChecking)
   1295     return false;
   1296 
   1297   CXXRecordDecl *CurDecl;
   1298   if (SS && SS->isSet() && !SS->isInvalid()) {
   1299     DeclContext *DC = computeDeclContext(*SS, true);
   1300     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
   1301   } else
   1302     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
   1303 
   1304   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
   1305       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
   1306           < II->getLength()) {
   1307     II = CurDecl->getIdentifier();
   1308     return true;
   1309   }
   1310 
   1311   return false;
   1312 }
   1313 
   1314 /// \brief Determine whether the given class is a base class of the given
   1315 /// class, including looking at dependent bases.
   1316 static bool findCircularInheritance(const CXXRecordDecl *Class,
   1317                                     const CXXRecordDecl *Current) {
   1318   SmallVector<const CXXRecordDecl*, 8> Queue;
   1319 
   1320   Class = Class->getCanonicalDecl();
   1321   while (true) {
   1322     for (const auto &I : Current->bases()) {
   1323       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
   1324       if (!Base)
   1325         continue;
   1326 
   1327       Base = Base->getDefinition();
   1328       if (!Base)
   1329         continue;
   1330 
   1331       if (Base->getCanonicalDecl() == Class)
   1332         return true;
   1333 
   1334       Queue.push_back(Base);
   1335     }
   1336 
   1337     if (Queue.empty())
   1338       return false;
   1339 
   1340     Current = Queue.pop_back_val();
   1341   }
   1342 
   1343   return false;
   1344 }
   1345 
   1346 /// \brief Check the validity of a C++ base class specifier.
   1347 ///
   1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
   1349 /// and returns NULL otherwise.
   1350 CXXBaseSpecifier *
   1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
   1352                          SourceRange SpecifierRange,
   1353                          bool Virtual, AccessSpecifier Access,
   1354                          TypeSourceInfo *TInfo,
   1355                          SourceLocation EllipsisLoc) {
   1356   QualType BaseType = TInfo->getType();
   1357 
   1358   // C++ [class.union]p1:
   1359   //   A union shall not have base classes.
   1360   if (Class->isUnion()) {
   1361     Diag(Class->getLocation(), diag::err_base_clause_on_union)
   1362       << SpecifierRange;
   1363     return nullptr;
   1364   }
   1365 
   1366   if (EllipsisLoc.isValid() &&
   1367       !TInfo->getType()->containsUnexpandedParameterPack()) {
   1368     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
   1369       << TInfo->getTypeLoc().getSourceRange();
   1370     EllipsisLoc = SourceLocation();
   1371   }
   1372 
   1373   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
   1374 
   1375   if (BaseType->isDependentType()) {
   1376     // Make sure that we don't have circular inheritance among our dependent
   1377     // bases. For non-dependent bases, the check for completeness below handles
   1378     // this.
   1379     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
   1380       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
   1381           ((BaseDecl = BaseDecl->getDefinition()) &&
   1382            findCircularInheritance(Class, BaseDecl))) {
   1383         Diag(BaseLoc, diag::err_circular_inheritance)
   1384           << BaseType << Context.getTypeDeclType(Class);
   1385 
   1386         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
   1387           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
   1388             << BaseType;
   1389 
   1390         return nullptr;
   1391       }
   1392     }
   1393 
   1394     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
   1395                                           Class->getTagKind() == TTK_Class,
   1396                                           Access, TInfo, EllipsisLoc);
   1397   }
   1398 
   1399   // Base specifiers must be record types.
   1400   if (!BaseType->isRecordType()) {
   1401     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
   1402     return nullptr;
   1403   }
   1404 
   1405   // C++ [class.union]p1:
   1406   //   A union shall not be used as a base class.
   1407   if (BaseType->isUnionType()) {
   1408     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
   1409     return nullptr;
   1410   }
   1411 
   1412   // For the MS ABI, propagate DLL attributes to base class templates.
   1413   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
   1414     if (Attr *ClassAttr = getDLLAttr(Class)) {
   1415       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
   1416               BaseType->getAsCXXRecordDecl())) {
   1417         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
   1418                                             BaseLoc);
   1419       }
   1420     }
   1421   }
   1422 
   1423   // C++ [class.derived]p2:
   1424   //   The class-name in a base-specifier shall not be an incompletely
   1425   //   defined class.
   1426   if (RequireCompleteType(BaseLoc, BaseType,
   1427                           diag::err_incomplete_base_class, SpecifierRange)) {
   1428     Class->setInvalidDecl();
   1429     return nullptr;
   1430   }
   1431 
   1432   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
   1433   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
   1434   assert(BaseDecl && "Record type has no declaration");
   1435   BaseDecl = BaseDecl->getDefinition();
   1436   assert(BaseDecl && "Base type is not incomplete, but has no definition");
   1437   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
   1438   assert(CXXBaseDecl && "Base type is not a C++ type");
   1439 
   1440   // A class which contains a flexible array member is not suitable for use as a
   1441   // base class:
   1442   //   - If the layout determines that a base comes before another base,
   1443   //     the flexible array member would index into the subsequent base.
   1444   //   - If the layout determines that base comes before the derived class,
   1445   //     the flexible array member would index into the derived class.
   1446   if (CXXBaseDecl->hasFlexibleArrayMember()) {
   1447     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
   1448       << CXXBaseDecl->getDeclName();
   1449     return nullptr;
   1450   }
   1451 
   1452   // C++ [class]p3:
   1453   //   If a class is marked final and it appears as a base-type-specifier in
   1454   //   base-clause, the program is ill-formed.
   1455   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
   1456     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
   1457       << CXXBaseDecl->getDeclName()
   1458       << FA->isSpelledAsSealed();
   1459     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
   1460         << CXXBaseDecl->getDeclName() << FA->getRange();
   1461     return nullptr;
   1462   }
   1463 
   1464   if (BaseDecl->isInvalidDecl())
   1465     Class->setInvalidDecl();
   1466 
   1467   // Create the base specifier.
   1468   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
   1469                                         Class->getTagKind() == TTK_Class,
   1470                                         Access, TInfo, EllipsisLoc);
   1471 }
   1472 
   1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
   1474 /// one entry in the base class list of a class specifier, for
   1475 /// example:
   1476 ///    class foo : public bar, virtual private baz {
   1477 /// 'public bar' and 'virtual private baz' are each base-specifiers.
   1478 BaseResult
   1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
   1480                          ParsedAttributes &Attributes,
   1481                          bool Virtual, AccessSpecifier Access,
   1482                          ParsedType basetype, SourceLocation BaseLoc,
   1483                          SourceLocation EllipsisLoc) {
   1484   if (!classdecl)
   1485     return true;
   1486 
   1487   AdjustDeclIfTemplate(classdecl);
   1488   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
   1489   if (!Class)
   1490     return true;
   1491 
   1492   // We haven't yet attached the base specifiers.
   1493   Class->setIsParsingBaseSpecifiers();
   1494 
   1495   // We do not support any C++11 attributes on base-specifiers yet.
   1496   // Diagnose any attributes we see.
   1497   if (!Attributes.empty()) {
   1498     for (AttributeList *Attr = Attributes.getList(); Attr;
   1499          Attr = Attr->getNext()) {
   1500       if (Attr->isInvalid() ||
   1501           Attr->getKind() == AttributeList::IgnoredAttribute)
   1502         continue;
   1503       Diag(Attr->getLoc(),
   1504            Attr->getKind() == AttributeList::UnknownAttribute
   1505              ? diag::warn_unknown_attribute_ignored
   1506              : diag::err_base_specifier_attribute)
   1507         << Attr->getName();
   1508     }
   1509   }
   1510 
   1511   TypeSourceInfo *TInfo = nullptr;
   1512   GetTypeFromParser(basetype, &TInfo);
   1513 
   1514   if (EllipsisLoc.isInvalid() &&
   1515       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
   1516                                       UPPC_BaseType))
   1517     return true;
   1518 
   1519   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
   1520                                                       Virtual, Access, TInfo,
   1521                                                       EllipsisLoc))
   1522     return BaseSpec;
   1523   else
   1524     Class->setInvalidDecl();
   1525 
   1526   return true;
   1527 }
   1528 
   1529 /// Use small set to collect indirect bases.  As this is only used
   1530 /// locally, there's no need to abstract the small size parameter.
   1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
   1532 
   1533 /// \brief Recursively add the bases of Type.  Don't add Type itself.
   1534 static void
   1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
   1536                   const QualType &Type)
   1537 {
   1538   // Even though the incoming type is a base, it might not be
   1539   // a class -- it could be a template parm, for instance.
   1540   if (auto Rec = Type->getAs<RecordType>()) {
   1541     auto Decl = Rec->getAsCXXRecordDecl();
   1542 
   1543     // Iterate over its bases.
   1544     for (const auto &BaseSpec : Decl->bases()) {
   1545       QualType Base = Context.getCanonicalType(BaseSpec.getType())
   1546         .getUnqualifiedType();
   1547       if (Set.insert(Base).second)
   1548         // If we've not already seen it, recurse.
   1549         NoteIndirectBases(Context, Set, Base);
   1550     }
   1551   }
   1552 }
   1553 
   1554 /// \brief Performs the actual work of attaching the given base class
   1555 /// specifiers to a C++ class.
   1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
   1557                                 unsigned NumBases) {
   1558  if (NumBases == 0)
   1559     return false;
   1560 
   1561   // Used to keep track of which base types we have already seen, so
   1562   // that we can properly diagnose redundant direct base types. Note
   1563   // that the key is always the unqualified canonical type of the base
   1564   // class.
   1565   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
   1566 
   1567   // Used to track indirect bases so we can see if a direct base is
   1568   // ambiguous.
   1569   IndirectBaseSet IndirectBaseTypes;
   1570 
   1571   // Copy non-redundant base specifiers into permanent storage.
   1572   unsigned NumGoodBases = 0;
   1573   bool Invalid = false;
   1574   for (unsigned idx = 0; idx < NumBases; ++idx) {
   1575     QualType NewBaseType
   1576       = Context.getCanonicalType(Bases[idx]->getType());
   1577     NewBaseType = NewBaseType.getLocalUnqualifiedType();
   1578 
   1579     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
   1580     if (KnownBase) {
   1581       // C++ [class.mi]p3:
   1582       //   A class shall not be specified as a direct base class of a
   1583       //   derived class more than once.
   1584       Diag(Bases[idx]->getLocStart(),
   1585            diag::err_duplicate_base_class)
   1586         << KnownBase->getType()
   1587         << Bases[idx]->getSourceRange();
   1588 
   1589       // Delete the duplicate base class specifier; we're going to
   1590       // overwrite its pointer later.
   1591       Context.Deallocate(Bases[idx]);
   1592 
   1593       Invalid = true;
   1594     } else {
   1595       // Okay, add this new base class.
   1596       KnownBase = Bases[idx];
   1597       Bases[NumGoodBases++] = Bases[idx];
   1598 
   1599       // Note this base's direct & indirect bases, if there could be ambiguity.
   1600       if (NumBases > 1)
   1601         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
   1602 
   1603       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
   1604         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
   1605         if (Class->isInterface() &&
   1606               (!RD->isInterface() ||
   1607                KnownBase->getAccessSpecifier() != AS_public)) {
   1608           // The Microsoft extension __interface does not permit bases that
   1609           // are not themselves public interfaces.
   1610           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
   1611             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
   1612             << RD->getSourceRange();
   1613           Invalid = true;
   1614         }
   1615         if (RD->hasAttr<WeakAttr>())
   1616           Class->addAttr(WeakAttr::CreateImplicit(Context));
   1617       }
   1618     }
   1619   }
   1620 
   1621   // Attach the remaining base class specifiers to the derived class.
   1622   Class->setBases(Bases, NumGoodBases);
   1623 
   1624   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
   1625     // Check whether this direct base is inaccessible due to ambiguity.
   1626     QualType BaseType = Bases[idx]->getType();
   1627     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
   1628       .getUnqualifiedType();
   1629 
   1630     if (IndirectBaseTypes.count(CanonicalBase)) {
   1631       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   1632                          /*DetectVirtual=*/true);
   1633       bool found
   1634         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
   1635       assert(found);
   1636       (void)found;
   1637 
   1638       if (Paths.isAmbiguous(CanonicalBase))
   1639         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
   1640           << BaseType << getAmbiguousPathsDisplayString(Paths)
   1641           << Bases[idx]->getSourceRange();
   1642       else
   1643         assert(Bases[idx]->isVirtual());
   1644     }
   1645 
   1646     // Delete the base class specifier, since its data has been copied
   1647     // into the CXXRecordDecl.
   1648     Context.Deallocate(Bases[idx]);
   1649   }
   1650 
   1651   return Invalid;
   1652 }
   1653 
   1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
   1655 /// class, after checking whether there are any duplicate base
   1656 /// classes.
   1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
   1658                                unsigned NumBases) {
   1659   if (!ClassDecl || !Bases || !NumBases)
   1660     return;
   1661 
   1662   AdjustDeclIfTemplate(ClassDecl);
   1663   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
   1664 }
   1665 
   1666 /// \brief Determine whether the type \p Derived is a C++ class that is
   1667 /// derived from the type \p Base.
   1668 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
   1669   if (!getLangOpts().CPlusPlus)
   1670     return false;
   1671 
   1672   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
   1673   if (!DerivedRD)
   1674     return false;
   1675 
   1676   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
   1677   if (!BaseRD)
   1678     return false;
   1679 
   1680   // If either the base or the derived type is invalid, don't try to
   1681   // check whether one is derived from the other.
   1682   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
   1683     return false;
   1684 
   1685   // FIXME: In a modules build, do we need the entire path to be visible for us
   1686   // to be able to use the inheritance relationship?
   1687   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
   1688     return false;
   1689 
   1690   return DerivedRD->isDerivedFrom(BaseRD);
   1691 }
   1692 
   1693 /// \brief Determine whether the type \p Derived is a C++ class that is
   1694 /// derived from the type \p Base.
   1695 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
   1696                          CXXBasePaths &Paths) {
   1697   if (!getLangOpts().CPlusPlus)
   1698     return false;
   1699 
   1700   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
   1701   if (!DerivedRD)
   1702     return false;
   1703 
   1704   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
   1705   if (!BaseRD)
   1706     return false;
   1707 
   1708   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
   1709     return false;
   1710 
   1711   return DerivedRD->isDerivedFrom(BaseRD, Paths);
   1712 }
   1713 
   1714 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
   1715                               CXXCastPath &BasePathArray) {
   1716   assert(BasePathArray.empty() && "Base path array must be empty!");
   1717   assert(Paths.isRecordingPaths() && "Must record paths!");
   1718 
   1719   const CXXBasePath &Path = Paths.front();
   1720 
   1721   // We first go backward and check if we have a virtual base.
   1722   // FIXME: It would be better if CXXBasePath had the base specifier for
   1723   // the nearest virtual base.
   1724   unsigned Start = 0;
   1725   for (unsigned I = Path.size(); I != 0; --I) {
   1726     if (Path[I - 1].Base->isVirtual()) {
   1727       Start = I - 1;
   1728       break;
   1729     }
   1730   }
   1731 
   1732   // Now add all bases.
   1733   for (unsigned I = Start, E = Path.size(); I != E; ++I)
   1734     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
   1735 }
   1736 
   1737 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
   1738 /// conversion (where Derived and Base are class types) is
   1739 /// well-formed, meaning that the conversion is unambiguous (and
   1740 /// that all of the base classes are accessible). Returns true
   1741 /// and emits a diagnostic if the code is ill-formed, returns false
   1742 /// otherwise. Loc is the location where this routine should point to
   1743 /// if there is an error, and Range is the source range to highlight
   1744 /// if there is an error.
   1745 bool
   1746 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
   1747                                    unsigned InaccessibleBaseID,
   1748                                    unsigned AmbigiousBaseConvID,
   1749                                    SourceLocation Loc, SourceRange Range,
   1750                                    DeclarationName Name,
   1751                                    CXXCastPath *BasePath) {
   1752   // First, determine whether the path from Derived to Base is
   1753   // ambiguous. This is slightly more expensive than checking whether
   1754   // the Derived to Base conversion exists, because here we need to
   1755   // explore multiple paths to determine if there is an ambiguity.
   1756   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   1757                      /*DetectVirtual=*/false);
   1758   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
   1759   assert(DerivationOkay &&
   1760          "Can only be used with a derived-to-base conversion");
   1761   (void)DerivationOkay;
   1762 
   1763   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
   1764     if (InaccessibleBaseID) {
   1765       // Check that the base class can be accessed.
   1766       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
   1767                                    InaccessibleBaseID)) {
   1768         case AR_inaccessible:
   1769           return true;
   1770         case AR_accessible:
   1771         case AR_dependent:
   1772         case AR_delayed:
   1773           break;
   1774       }
   1775     }
   1776 
   1777     // Build a base path if necessary.
   1778     if (BasePath)
   1779       BuildBasePathArray(Paths, *BasePath);
   1780     return false;
   1781   }
   1782 
   1783   if (AmbigiousBaseConvID) {
   1784     // We know that the derived-to-base conversion is ambiguous, and
   1785     // we're going to produce a diagnostic. Perform the derived-to-base
   1786     // search just one more time to compute all of the possible paths so
   1787     // that we can print them out. This is more expensive than any of
   1788     // the previous derived-to-base checks we've done, but at this point
   1789     // performance isn't as much of an issue.
   1790     Paths.clear();
   1791     Paths.setRecordingPaths(true);
   1792     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
   1793     assert(StillOkay && "Can only be used with a derived-to-base conversion");
   1794     (void)StillOkay;
   1795 
   1796     // Build up a textual representation of the ambiguous paths, e.g.,
   1797     // D -> B -> A, that will be used to illustrate the ambiguous
   1798     // conversions in the diagnostic. We only print one of the paths
   1799     // to each base class subobject.
   1800     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
   1801 
   1802     Diag(Loc, AmbigiousBaseConvID)
   1803     << Derived << Base << PathDisplayStr << Range << Name;
   1804   }
   1805   return true;
   1806 }
   1807 
   1808 bool
   1809 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
   1810                                    SourceLocation Loc, SourceRange Range,
   1811                                    CXXCastPath *BasePath,
   1812                                    bool IgnoreAccess) {
   1813   return CheckDerivedToBaseConversion(Derived, Base,
   1814                                       IgnoreAccess ? 0
   1815                                        : diag::err_upcast_to_inaccessible_base,
   1816                                       diag::err_ambiguous_derived_to_base_conv,
   1817                                       Loc, Range, DeclarationName(),
   1818                                       BasePath);
   1819 }
   1820 
   1821 
   1822 /// @brief Builds a string representing ambiguous paths from a
   1823 /// specific derived class to different subobjects of the same base
   1824 /// class.
   1825 ///
   1826 /// This function builds a string that can be used in error messages
   1827 /// to show the different paths that one can take through the
   1828 /// inheritance hierarchy to go from the derived class to different
   1829 /// subobjects of a base class. The result looks something like this:
   1830 /// @code
   1831 /// struct D -> struct B -> struct A
   1832 /// struct D -> struct C -> struct A
   1833 /// @endcode
   1834 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
   1835   std::string PathDisplayStr;
   1836   std::set<unsigned> DisplayedPaths;
   1837   for (CXXBasePaths::paths_iterator Path = Paths.begin();
   1838        Path != Paths.end(); ++Path) {
   1839     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
   1840       // We haven't displayed a path to this particular base
   1841       // class subobject yet.
   1842       PathDisplayStr += "\n    ";
   1843       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
   1844       for (CXXBasePath::const_iterator Element = Path->begin();
   1845            Element != Path->end(); ++Element)
   1846         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
   1847     }
   1848   }
   1849 
   1850   return PathDisplayStr;
   1851 }
   1852 
   1853 //===----------------------------------------------------------------------===//
   1854 // C++ class member Handling
   1855 //===----------------------------------------------------------------------===//
   1856 
   1857 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
   1858 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
   1859                                 SourceLocation ASLoc,
   1860                                 SourceLocation ColonLoc,
   1861                                 AttributeList *Attrs) {
   1862   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
   1863   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
   1864                                                   ASLoc, ColonLoc);
   1865   CurContext->addHiddenDecl(ASDecl);
   1866   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
   1867 }
   1868 
   1869 /// CheckOverrideControl - Check C++11 override control semantics.
   1870 void Sema::CheckOverrideControl(NamedDecl *D) {
   1871   if (D->isInvalidDecl())
   1872     return;
   1873 
   1874   // We only care about "override" and "final" declarations.
   1875   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
   1876     return;
   1877 
   1878   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
   1879 
   1880   // We can't check dependent instance methods.
   1881   if (MD && MD->isInstance() &&
   1882       (MD->getParent()->hasAnyDependentBases() ||
   1883        MD->getType()->isDependentType()))
   1884     return;
   1885 
   1886   if (MD && !MD->isVirtual()) {
   1887     // If we have a non-virtual method, check if if hides a virtual method.
   1888     // (In that case, it's most likely the method has the wrong type.)
   1889     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
   1890     FindHiddenVirtualMethods(MD, OverloadedMethods);
   1891 
   1892     if (!OverloadedMethods.empty()) {
   1893       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
   1894         Diag(OA->getLocation(),
   1895              diag::override_keyword_hides_virtual_member_function)
   1896           << "override" << (OverloadedMethods.size() > 1);
   1897       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
   1898         Diag(FA->getLocation(),
   1899              diag::override_keyword_hides_virtual_member_function)
   1900           << (FA->isSpelledAsSealed() ? "sealed" : "final")
   1901           << (OverloadedMethods.size() > 1);
   1902       }
   1903       NoteHiddenVirtualMethods(MD, OverloadedMethods);
   1904       MD->setInvalidDecl();
   1905       return;
   1906     }
   1907     // Fall through into the general case diagnostic.
   1908     // FIXME: We might want to attempt typo correction here.
   1909   }
   1910 
   1911   if (!MD || !MD->isVirtual()) {
   1912     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
   1913       Diag(OA->getLocation(),
   1914            diag::override_keyword_only_allowed_on_virtual_member_functions)
   1915         << "override" << FixItHint::CreateRemoval(OA->getLocation());
   1916       D->dropAttr<OverrideAttr>();
   1917     }
   1918     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
   1919       Diag(FA->getLocation(),
   1920            diag::override_keyword_only_allowed_on_virtual_member_functions)
   1921         << (FA->isSpelledAsSealed() ? "sealed" : "final")
   1922         << FixItHint::CreateRemoval(FA->getLocation());
   1923       D->dropAttr<FinalAttr>();
   1924     }
   1925     return;
   1926   }
   1927 
   1928   // C++11 [class.virtual]p5:
   1929   //   If a function is marked with the virt-specifier override and
   1930   //   does not override a member function of a base class, the program is
   1931   //   ill-formed.
   1932   bool HasOverriddenMethods =
   1933     MD->begin_overridden_methods() != MD->end_overridden_methods();
   1934   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
   1935     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
   1936       << MD->getDeclName();
   1937 }
   1938 
   1939 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
   1940   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
   1941     return;
   1942   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
   1943   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
   1944       isa<CXXDestructorDecl>(MD))
   1945     return;
   1946 
   1947   SourceLocation Loc = MD->getLocation();
   1948   SourceLocation SpellingLoc = Loc;
   1949   if (getSourceManager().isMacroArgExpansion(Loc))
   1950     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
   1951   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
   1952   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
   1953       return;
   1954 
   1955   if (MD->size_overridden_methods() > 0) {
   1956     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
   1957       << MD->getDeclName();
   1958     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
   1959     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
   1960   }
   1961 }
   1962 
   1963 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
   1964 /// function overrides a virtual member function marked 'final', according to
   1965 /// C++11 [class.virtual]p4.
   1966 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
   1967                                                   const CXXMethodDecl *Old) {
   1968   FinalAttr *FA = Old->getAttr<FinalAttr>();
   1969   if (!FA)
   1970     return false;
   1971 
   1972   Diag(New->getLocation(), diag::err_final_function_overridden)
   1973     << New->getDeclName()
   1974     << FA->isSpelledAsSealed();
   1975   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
   1976   return true;
   1977 }
   1978 
   1979 static bool InitializationHasSideEffects(const FieldDecl &FD) {
   1980   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
   1981   // FIXME: Destruction of ObjC lifetime types has side-effects.
   1982   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
   1983     return !RD->isCompleteDefinition() ||
   1984            !RD->hasTrivialDefaultConstructor() ||
   1985            !RD->hasTrivialDestructor();
   1986   return false;
   1987 }
   1988 
   1989 static AttributeList *getMSPropertyAttr(AttributeList *list) {
   1990   for (AttributeList *it = list; it != nullptr; it = it->getNext())
   1991     if (it->isDeclspecPropertyAttribute())
   1992       return it;
   1993   return nullptr;
   1994 }
   1995 
   1996 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
   1997 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
   1998 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
   1999 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
   2000 /// present (but parsing it has been deferred).
   2001 NamedDecl *
   2002 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
   2003                                MultiTemplateParamsArg TemplateParameterLists,
   2004                                Expr *BW, const VirtSpecifiers &VS,
   2005                                InClassInitStyle InitStyle) {
   2006   const DeclSpec &DS = D.getDeclSpec();
   2007   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
   2008   DeclarationName Name = NameInfo.getName();
   2009   SourceLocation Loc = NameInfo.getLoc();
   2010 
   2011   // For anonymous bitfields, the location should point to the type.
   2012   if (Loc.isInvalid())
   2013     Loc = D.getLocStart();
   2014 
   2015   Expr *BitWidth = static_cast<Expr*>(BW);
   2016 
   2017   assert(isa<CXXRecordDecl>(CurContext));
   2018   assert(!DS.isFriendSpecified());
   2019 
   2020   bool isFunc = D.isDeclarationOfFunction();
   2021 
   2022   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
   2023     // The Microsoft extension __interface only permits public member functions
   2024     // and prohibits constructors, destructors, operators, non-public member
   2025     // functions, static methods and data members.
   2026     unsigned InvalidDecl;
   2027     bool ShowDeclName = true;
   2028     if (!isFunc)
   2029       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
   2030     else if (AS != AS_public)
   2031       InvalidDecl = 2;
   2032     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
   2033       InvalidDecl = 3;
   2034     else switch (Name.getNameKind()) {
   2035       case DeclarationName::CXXConstructorName:
   2036         InvalidDecl = 4;
   2037         ShowDeclName = false;
   2038         break;
   2039 
   2040       case DeclarationName::CXXDestructorName:
   2041         InvalidDecl = 5;
   2042         ShowDeclName = false;
   2043         break;
   2044 
   2045       case DeclarationName::CXXOperatorName:
   2046       case DeclarationName::CXXConversionFunctionName:
   2047         InvalidDecl = 6;
   2048         break;
   2049 
   2050       default:
   2051         InvalidDecl = 0;
   2052         break;
   2053     }
   2054 
   2055     if (InvalidDecl) {
   2056       if (ShowDeclName)
   2057         Diag(Loc, diag::err_invalid_member_in_interface)
   2058           << (InvalidDecl-1) << Name;
   2059       else
   2060         Diag(Loc, diag::err_invalid_member_in_interface)
   2061           << (InvalidDecl-1) << "";
   2062       return nullptr;
   2063     }
   2064   }
   2065 
   2066   // C++ 9.2p6: A member shall not be declared to have automatic storage
   2067   // duration (auto, register) or with the extern storage-class-specifier.
   2068   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
   2069   // data members and cannot be applied to names declared const or static,
   2070   // and cannot be applied to reference members.
   2071   switch (DS.getStorageClassSpec()) {
   2072   case DeclSpec::SCS_unspecified:
   2073   case DeclSpec::SCS_typedef:
   2074   case DeclSpec::SCS_static:
   2075     break;
   2076   case DeclSpec::SCS_mutable:
   2077     if (isFunc) {
   2078       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
   2079 
   2080       // FIXME: It would be nicer if the keyword was ignored only for this
   2081       // declarator. Otherwise we could get follow-up errors.
   2082       D.getMutableDeclSpec().ClearStorageClassSpecs();
   2083     }
   2084     break;
   2085   default:
   2086     Diag(DS.getStorageClassSpecLoc(),
   2087          diag::err_storageclass_invalid_for_member);
   2088     D.getMutableDeclSpec().ClearStorageClassSpecs();
   2089     break;
   2090   }
   2091 
   2092   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
   2093                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
   2094                       !isFunc);
   2095 
   2096   if (DS.isConstexprSpecified() && isInstField) {
   2097     SemaDiagnosticBuilder B =
   2098         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
   2099     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
   2100     if (InitStyle == ICIS_NoInit) {
   2101       B << 0 << 0;
   2102       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
   2103         B << FixItHint::CreateRemoval(ConstexprLoc);
   2104       else {
   2105         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
   2106         D.getMutableDeclSpec().ClearConstexprSpec();
   2107         const char *PrevSpec;
   2108         unsigned DiagID;
   2109         bool Failed = D.getMutableDeclSpec().SetTypeQual(
   2110             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
   2111         (void)Failed;
   2112         assert(!Failed && "Making a constexpr member const shouldn't fail");
   2113       }
   2114     } else {
   2115       B << 1;
   2116       const char *PrevSpec;
   2117       unsigned DiagID;
   2118       if (D.getMutableDeclSpec().SetStorageClassSpec(
   2119           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
   2120           Context.getPrintingPolicy())) {
   2121         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
   2122                "This is the only DeclSpec that should fail to be applied");
   2123         B << 1;
   2124       } else {
   2125         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
   2126         isInstField = false;
   2127       }
   2128     }
   2129   }
   2130 
   2131   NamedDecl *Member;
   2132   if (isInstField) {
   2133     CXXScopeSpec &SS = D.getCXXScopeSpec();
   2134 
   2135     // Data members must have identifiers for names.
   2136     if (!Name.isIdentifier()) {
   2137       Diag(Loc, diag::err_bad_variable_name)
   2138         << Name;
   2139       return nullptr;
   2140     }
   2141 
   2142     IdentifierInfo *II = Name.getAsIdentifierInfo();
   2143 
   2144     // Member field could not be with "template" keyword.
   2145     // So TemplateParameterLists should be empty in this case.
   2146     if (TemplateParameterLists.size()) {
   2147       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
   2148       if (TemplateParams->size()) {
   2149         // There is no such thing as a member field template.
   2150         Diag(D.getIdentifierLoc(), diag::err_template_member)
   2151             << II
   2152             << SourceRange(TemplateParams->getTemplateLoc(),
   2153                 TemplateParams->getRAngleLoc());
   2154       } else {
   2155         // There is an extraneous 'template<>' for this member.
   2156         Diag(TemplateParams->getTemplateLoc(),
   2157             diag::err_template_member_noparams)
   2158             << II
   2159             << SourceRange(TemplateParams->getTemplateLoc(),
   2160                 TemplateParams->getRAngleLoc());
   2161       }
   2162       return nullptr;
   2163     }
   2164 
   2165     if (SS.isSet() && !SS.isInvalid()) {
   2166       // The user provided a superfluous scope specifier inside a class
   2167       // definition:
   2168       //
   2169       // class X {
   2170       //   int X::member;
   2171       // };
   2172       if (DeclContext *DC = computeDeclContext(SS, false))
   2173         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
   2174       else
   2175         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
   2176           << Name << SS.getRange();
   2177 
   2178       SS.clear();
   2179     }
   2180 
   2181     AttributeList *MSPropertyAttr =
   2182       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
   2183     if (MSPropertyAttr) {
   2184       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
   2185                                 BitWidth, InitStyle, AS, MSPropertyAttr);
   2186       if (!Member)
   2187         return nullptr;
   2188       isInstField = false;
   2189     } else {
   2190       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
   2191                                 BitWidth, InitStyle, AS);
   2192       assert(Member && "HandleField never returns null");
   2193     }
   2194   } else {
   2195     Member = HandleDeclarator(S, D, TemplateParameterLists);
   2196     if (!Member)
   2197       return nullptr;
   2198 
   2199     // Non-instance-fields can't have a bitfield.
   2200     if (BitWidth) {
   2201       if (Member->isInvalidDecl()) {
   2202         // don't emit another diagnostic.
   2203       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
   2204         // C++ 9.6p3: A bit-field shall not be a static member.
   2205         // "static member 'A' cannot be a bit-field"
   2206         Diag(Loc, diag::err_static_not_bitfield)
   2207           << Name << BitWidth->getSourceRange();
   2208       } else if (isa<TypedefDecl>(Member)) {
   2209         // "typedef member 'x' cannot be a bit-field"
   2210         Diag(Loc, diag::err_typedef_not_bitfield)
   2211           << Name << BitWidth->getSourceRange();
   2212       } else {
   2213         // A function typedef ("typedef int f(); f a;").
   2214         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
   2215         Diag(Loc, diag::err_not_integral_type_bitfield)
   2216           << Name << cast<ValueDecl>(Member)->getType()
   2217           << BitWidth->getSourceRange();
   2218       }
   2219 
   2220       BitWidth = nullptr;
   2221       Member->setInvalidDecl();
   2222     }
   2223 
   2224     Member->setAccess(AS);
   2225 
   2226     // If we have declared a member function template or static data member
   2227     // template, set the access of the templated declaration as well.
   2228     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
   2229       FunTmpl->getTemplatedDecl()->setAccess(AS);
   2230     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
   2231       VarTmpl->getTemplatedDecl()->setAccess(AS);
   2232   }
   2233 
   2234   if (VS.isOverrideSpecified())
   2235     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
   2236   if (VS.isFinalSpecified())
   2237     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
   2238                                             VS.isFinalSpelledSealed()));
   2239 
   2240   if (VS.getLastLocation().isValid()) {
   2241     // Update the end location of a method that has a virt-specifiers.
   2242     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
   2243       MD->setRangeEnd(VS.getLastLocation());
   2244   }
   2245 
   2246   CheckOverrideControl(Member);
   2247 
   2248   assert((Name || isInstField) && "No identifier for non-field ?");
   2249 
   2250   if (isInstField) {
   2251     FieldDecl *FD = cast<FieldDecl>(Member);
   2252     FieldCollector->Add(FD);
   2253 
   2254     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
   2255       // Remember all explicit private FieldDecls that have a name, no side
   2256       // effects and are not part of a dependent type declaration.
   2257       if (!FD->isImplicit() && FD->getDeclName() &&
   2258           FD->getAccess() == AS_private &&
   2259           !FD->hasAttr<UnusedAttr>() &&
   2260           !FD->getParent()->isDependentContext() &&
   2261           !InitializationHasSideEffects(*FD))
   2262         UnusedPrivateFields.insert(FD);
   2263     }
   2264   }
   2265 
   2266   return Member;
   2267 }
   2268 
   2269 namespace {
   2270   class UninitializedFieldVisitor
   2271       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
   2272     Sema &S;
   2273     // List of Decls to generate a warning on.  Also remove Decls that become
   2274     // initialized.
   2275     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
   2276     // List of base classes of the record.  Classes are removed after their
   2277     // initializers.
   2278     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
   2279     // Vector of decls to be removed from the Decl set prior to visiting the
   2280     // nodes.  These Decls may have been initialized in the prior initializer.
   2281     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
   2282     // If non-null, add a note to the warning pointing back to the constructor.
   2283     const CXXConstructorDecl *Constructor;
   2284     // Variables to hold state when processing an initializer list.  When
   2285     // InitList is true, special case initialization of FieldDecls matching
   2286     // InitListFieldDecl.
   2287     bool InitList;
   2288     FieldDecl *InitListFieldDecl;
   2289     llvm::SmallVector<unsigned, 4> InitFieldIndex;
   2290 
   2291   public:
   2292     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
   2293     UninitializedFieldVisitor(Sema &S,
   2294                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
   2295                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
   2296       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
   2297         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
   2298 
   2299     // Returns true if the use of ME is not an uninitialized use.
   2300     bool IsInitListMemberExprInitialized(MemberExpr *ME,
   2301                                          bool CheckReferenceOnly) {
   2302       llvm::SmallVector<FieldDecl*, 4> Fields;
   2303       bool ReferenceField = false;
   2304       while (ME) {
   2305         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
   2306         if (!FD)
   2307           return false;
   2308         Fields.push_back(FD);
   2309         if (FD->getType()->isReferenceType())
   2310           ReferenceField = true;
   2311         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
   2312       }
   2313 
   2314       // Binding a reference to an unintialized field is not an
   2315       // uninitialized use.
   2316       if (CheckReferenceOnly && !ReferenceField)
   2317         return true;
   2318 
   2319       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
   2320       // Discard the first field since it is the field decl that is being
   2321       // initialized.
   2322       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
   2323         UsedFieldIndex.push_back((*I)->getFieldIndex());
   2324       }
   2325 
   2326       for (auto UsedIter = UsedFieldIndex.begin(),
   2327                 UsedEnd = UsedFieldIndex.end(),
   2328                 OrigIter = InitFieldIndex.begin(),
   2329                 OrigEnd = InitFieldIndex.end();
   2330            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
   2331         if (*UsedIter < *OrigIter)
   2332           return true;
   2333         if (*UsedIter > *OrigIter)
   2334           break;
   2335       }
   2336 
   2337       return false;
   2338     }
   2339 
   2340     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
   2341                           bool AddressOf) {
   2342       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
   2343         return;
   2344 
   2345       // FieldME is the inner-most MemberExpr that is not an anonymous struct
   2346       // or union.
   2347       MemberExpr *FieldME = ME;
   2348 
   2349       bool AllPODFields = FieldME->getType().isPODType(S.Context);
   2350 
   2351       Expr *Base = ME;
   2352       while (MemberExpr *SubME =
   2353                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
   2354 
   2355         if (isa<VarDecl>(SubME->getMemberDecl()))
   2356           return;
   2357 
   2358         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
   2359           if (!FD->isAnonymousStructOrUnion())
   2360             FieldME = SubME;
   2361 
   2362         if (!FieldME->getType().isPODType(S.Context))
   2363           AllPODFields = false;
   2364 
   2365         Base = SubME->getBase();
   2366       }
   2367 
   2368       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
   2369         return;
   2370 
   2371       if (AddressOf && AllPODFields)
   2372         return;
   2373 
   2374       ValueDecl* FoundVD = FieldME->getMemberDecl();
   2375 
   2376       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
   2377         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
   2378           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
   2379         }
   2380 
   2381         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
   2382           QualType T = BaseCast->getType();
   2383           if (T->isPointerType() &&
   2384               BaseClasses.count(T->getPointeeType())) {
   2385             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
   2386                 << T->getPointeeType() << FoundVD;
   2387           }
   2388         }
   2389       }
   2390 
   2391       if (!Decls.count(FoundVD))
   2392         return;
   2393 
   2394       const bool IsReference = FoundVD->getType()->isReferenceType();
   2395 
   2396       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
   2397         // Special checking for initializer lists.
   2398         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
   2399           return;
   2400         }
   2401       } else {
   2402         // Prevent double warnings on use of unbounded references.
   2403         if (CheckReferenceOnly && !IsReference)
   2404           return;
   2405       }
   2406 
   2407       unsigned diag = IsReference
   2408           ? diag::warn_reference_field_is_uninit
   2409           : diag::warn_field_is_uninit;
   2410       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
   2411       if (Constructor)
   2412         S.Diag(Constructor->getLocation(),
   2413                diag::note_uninit_in_this_constructor)
   2414           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
   2415 
   2416     }
   2417 
   2418     void HandleValue(Expr *E, bool AddressOf) {
   2419       E = E->IgnoreParens();
   2420 
   2421       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
   2422         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
   2423                          AddressOf /*AddressOf*/);
   2424         return;
   2425       }
   2426 
   2427       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
   2428         Visit(CO->getCond());
   2429         HandleValue(CO->getTrueExpr(), AddressOf);
   2430         HandleValue(CO->getFalseExpr(), AddressOf);
   2431         return;
   2432       }
   2433 
   2434       if (BinaryConditionalOperator *BCO =
   2435               dyn_cast<BinaryConditionalOperator>(E)) {
   2436         Visit(BCO->getCond());
   2437         HandleValue(BCO->getFalseExpr(), AddressOf);
   2438         return;
   2439       }
   2440 
   2441       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
   2442         HandleValue(OVE->getSourceExpr(), AddressOf);
   2443         return;
   2444       }
   2445 
   2446       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
   2447         switch (BO->getOpcode()) {
   2448         default:
   2449           break;
   2450         case(BO_PtrMemD):
   2451         case(BO_PtrMemI):
   2452           HandleValue(BO->getLHS(), AddressOf);
   2453           Visit(BO->getRHS());
   2454           return;
   2455         case(BO_Comma):
   2456           Visit(BO->getLHS());
   2457           HandleValue(BO->getRHS(), AddressOf);
   2458           return;
   2459         }
   2460       }
   2461 
   2462       Visit(E);
   2463     }
   2464 
   2465     void CheckInitListExpr(InitListExpr *ILE) {
   2466       InitFieldIndex.push_back(0);
   2467       for (auto Child : ILE->children()) {
   2468         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
   2469           CheckInitListExpr(SubList);
   2470         } else {
   2471           Visit(Child);
   2472         }
   2473         ++InitFieldIndex.back();
   2474       }
   2475       InitFieldIndex.pop_back();
   2476     }
   2477 
   2478     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
   2479                           FieldDecl *Field, const Type *BaseClass) {
   2480       // Remove Decls that may have been initialized in the previous
   2481       // initializer.
   2482       for (ValueDecl* VD : DeclsToRemove)
   2483         Decls.erase(VD);
   2484       DeclsToRemove.clear();
   2485 
   2486       Constructor = FieldConstructor;
   2487       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
   2488 
   2489       if (ILE && Field) {
   2490         InitList = true;
   2491         InitListFieldDecl = Field;
   2492         InitFieldIndex.clear();
   2493         CheckInitListExpr(ILE);
   2494       } else {
   2495         InitList = false;
   2496         Visit(E);
   2497       }
   2498 
   2499       if (Field)
   2500         Decls.erase(Field);
   2501       if (BaseClass)
   2502         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
   2503     }
   2504 
   2505     void VisitMemberExpr(MemberExpr *ME) {
   2506       // All uses of unbounded reference fields will warn.
   2507       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
   2508     }
   2509 
   2510     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
   2511       if (E->getCastKind() == CK_LValueToRValue) {
   2512         HandleValue(E->getSubExpr(), false /*AddressOf*/);
   2513         return;
   2514       }
   2515 
   2516       Inherited::VisitImplicitCastExpr(E);
   2517     }
   2518 
   2519     void VisitCXXConstructExpr(CXXConstructExpr *E) {
   2520       if (E->getConstructor()->isCopyConstructor()) {
   2521         Expr *ArgExpr = E->getArg(0);
   2522         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
   2523           if (ILE->getNumInits() == 1)
   2524             ArgExpr = ILE->getInit(0);
   2525         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
   2526           if (ICE->getCastKind() == CK_NoOp)
   2527             ArgExpr = ICE->getSubExpr();
   2528         HandleValue(ArgExpr, false /*AddressOf*/);
   2529         return;
   2530       }
   2531       Inherited::VisitCXXConstructExpr(E);
   2532     }
   2533 
   2534     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
   2535       Expr *Callee = E->getCallee();
   2536       if (isa<MemberExpr>(Callee)) {
   2537         HandleValue(Callee, false /*AddressOf*/);
   2538         for (auto Arg : E->arguments())
   2539           Visit(Arg);
   2540         return;
   2541       }
   2542 
   2543       Inherited::VisitCXXMemberCallExpr(E);
   2544     }
   2545 
   2546     void VisitCallExpr(CallExpr *E) {
   2547       // Treat std::move as a use.
   2548       if (E->getNumArgs() == 1) {
   2549         if (FunctionDecl *FD = E->getDirectCallee()) {
   2550           if (FD->isInStdNamespace() && FD->getIdentifier() &&
   2551               FD->getIdentifier()->isStr("move")) {
   2552             HandleValue(E->getArg(0), false /*AddressOf*/);
   2553             return;
   2554           }
   2555         }
   2556       }
   2557 
   2558       Inherited::VisitCallExpr(E);
   2559     }
   2560 
   2561     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
   2562       Expr *Callee = E->getCallee();
   2563 
   2564       if (isa<UnresolvedLookupExpr>(Callee))
   2565         return Inherited::VisitCXXOperatorCallExpr(E);
   2566 
   2567       Visit(Callee);
   2568       for (auto Arg : E->arguments())
   2569         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
   2570     }
   2571 
   2572     void VisitBinaryOperator(BinaryOperator *E) {
   2573       // If a field assignment is detected, remove the field from the
   2574       // uninitiailized field set.
   2575       if (E->getOpcode() == BO_Assign)
   2576         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
   2577           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
   2578             if (!FD->getType()->isReferenceType())
   2579               DeclsToRemove.push_back(FD);
   2580 
   2581       if (E->isCompoundAssignmentOp()) {
   2582         HandleValue(E->getLHS(), false /*AddressOf*/);
   2583         Visit(E->getRHS());
   2584         return;
   2585       }
   2586 
   2587       Inherited::VisitBinaryOperator(E);
   2588     }
   2589 
   2590     void VisitUnaryOperator(UnaryOperator *E) {
   2591       if (E->isIncrementDecrementOp()) {
   2592         HandleValue(E->getSubExpr(), false /*AddressOf*/);
   2593         return;
   2594       }
   2595       if (E->getOpcode() == UO_AddrOf) {
   2596         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
   2597           HandleValue(ME->getBase(), true /*AddressOf*/);
   2598           return;
   2599         }
   2600       }
   2601 
   2602       Inherited::VisitUnaryOperator(E);
   2603     }
   2604   };
   2605 
   2606   // Diagnose value-uses of fields to initialize themselves, e.g.
   2607   //   foo(foo)
   2608   // where foo is not also a parameter to the constructor.
   2609   // Also diagnose across field uninitialized use such as
   2610   //   x(y), y(x)
   2611   // TODO: implement -Wuninitialized and fold this into that framework.
   2612   static void DiagnoseUninitializedFields(
   2613       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
   2614 
   2615     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
   2616                                            Constructor->getLocation())) {
   2617       return;
   2618     }
   2619 
   2620     if (Constructor->isInvalidDecl())
   2621       return;
   2622 
   2623     const CXXRecordDecl *RD = Constructor->getParent();
   2624 
   2625     if (RD->getDescribedClassTemplate())
   2626       return;
   2627 
   2628     // Holds fields that are uninitialized.
   2629     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
   2630 
   2631     // At the beginning, all fields are uninitialized.
   2632     for (auto *I : RD->decls()) {
   2633       if (auto *FD = dyn_cast<FieldDecl>(I)) {
   2634         UninitializedFields.insert(FD);
   2635       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
   2636         UninitializedFields.insert(IFD->getAnonField());
   2637       }
   2638     }
   2639 
   2640     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
   2641     for (auto I : RD->bases())
   2642       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
   2643 
   2644     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
   2645       return;
   2646 
   2647     UninitializedFieldVisitor UninitializedChecker(SemaRef,
   2648                                                    UninitializedFields,
   2649                                                    UninitializedBaseClasses);
   2650 
   2651     for (const auto *FieldInit : Constructor->inits()) {
   2652       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
   2653         break;
   2654 
   2655       Expr *InitExpr = FieldInit->getInit();
   2656       if (!InitExpr)
   2657         continue;
   2658 
   2659       if (CXXDefaultInitExpr *Default =
   2660               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
   2661         InitExpr = Default->getExpr();
   2662         if (!InitExpr)
   2663           continue;
   2664         // In class initializers will point to the constructor.
   2665         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
   2666                                               FieldInit->getAnyMember(),
   2667                                               FieldInit->getBaseClass());
   2668       } else {
   2669         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
   2670                                               FieldInit->getAnyMember(),
   2671                                               FieldInit->getBaseClass());
   2672       }
   2673     }
   2674   }
   2675 } // namespace
   2676 
   2677 /// \brief Enter a new C++ default initializer scope. After calling this, the
   2678 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
   2679 /// parsing or instantiating the initializer failed.
   2680 void Sema::ActOnStartCXXInClassMemberInitializer() {
   2681   // Create a synthetic function scope to represent the call to the constructor
   2682   // that notionally surrounds a use of this initializer.
   2683   PushFunctionScope();
   2684 }
   2685 
   2686 /// \brief This is invoked after parsing an in-class initializer for a
   2687 /// non-static C++ class member, and after instantiating an in-class initializer
   2688 /// in a class template. Such actions are deferred until the class is complete.
   2689 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
   2690                                                   SourceLocation InitLoc,
   2691                                                   Expr *InitExpr) {
   2692   // Pop the notional constructor scope we created earlier.
   2693   PopFunctionScopeInfo(nullptr, D);
   2694 
   2695   FieldDecl *FD = dyn_cast<FieldDecl>(D);
   2696   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
   2697          "must set init style when field is created");
   2698 
   2699   if (!InitExpr) {
   2700     D->setInvalidDecl();
   2701     if (FD)
   2702       FD->removeInClassInitializer();
   2703     return;
   2704   }
   2705 
   2706   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
   2707     FD->setInvalidDecl();
   2708     FD->removeInClassInitializer();
   2709     return;
   2710   }
   2711 
   2712   ExprResult Init = InitExpr;
   2713   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
   2714     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
   2715     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
   2716         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
   2717         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
   2718     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
   2719     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
   2720     if (Init.isInvalid()) {
   2721       FD->setInvalidDecl();
   2722       return;
   2723     }
   2724   }
   2725 
   2726   // C++11 [class.base.init]p7:
   2727   //   The initialization of each base and member constitutes a
   2728   //   full-expression.
   2729   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
   2730   if (Init.isInvalid()) {
   2731     FD->setInvalidDecl();
   2732     return;
   2733   }
   2734 
   2735   InitExpr = Init.get();
   2736 
   2737   FD->setInClassInitializer(InitExpr);
   2738 }
   2739 
   2740 /// \brief Find the direct and/or virtual base specifiers that
   2741 /// correspond to the given base type, for use in base initialization
   2742 /// within a constructor.
   2743 static bool FindBaseInitializer(Sema &SemaRef,
   2744                                 CXXRecordDecl *ClassDecl,
   2745                                 QualType BaseType,
   2746                                 const CXXBaseSpecifier *&DirectBaseSpec,
   2747                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
   2748   // First, check for a direct base class.
   2749   DirectBaseSpec = nullptr;
   2750   for (const auto &Base : ClassDecl->bases()) {
   2751     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
   2752       // We found a direct base of this type. That's what we're
   2753       // initializing.
   2754       DirectBaseSpec = &Base;
   2755       break;
   2756     }
   2757   }
   2758 
   2759   // Check for a virtual base class.
   2760   // FIXME: We might be able to short-circuit this if we know in advance that
   2761   // there are no virtual bases.
   2762   VirtualBaseSpec = nullptr;
   2763   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
   2764     // We haven't found a base yet; search the class hierarchy for a
   2765     // virtual base class.
   2766     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   2767                        /*DetectVirtual=*/false);
   2768     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
   2769                               SemaRef.Context.getTypeDeclType(ClassDecl),
   2770                               BaseType, Paths)) {
   2771       for (CXXBasePaths::paths_iterator Path = Paths.begin();
   2772            Path != Paths.end(); ++Path) {
   2773         if (Path->back().Base->isVirtual()) {
   2774           VirtualBaseSpec = Path->back().Base;
   2775           break;
   2776         }
   2777       }
   2778     }
   2779   }
   2780 
   2781   return DirectBaseSpec || VirtualBaseSpec;
   2782 }
   2783 
   2784 /// \brief Handle a C++ member initializer using braced-init-list syntax.
   2785 MemInitResult
   2786 Sema::ActOnMemInitializer(Decl *ConstructorD,
   2787                           Scope *S,
   2788                           CXXScopeSpec &SS,
   2789                           IdentifierInfo *MemberOrBase,
   2790                           ParsedType TemplateTypeTy,
   2791                           const DeclSpec &DS,
   2792                           SourceLocation IdLoc,
   2793                           Expr *InitList,
   2794                           SourceLocation EllipsisLoc) {
   2795   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
   2796                              DS, IdLoc, InitList,
   2797                              EllipsisLoc);
   2798 }
   2799 
   2800 /// \brief Handle a C++ member initializer using parentheses syntax.
   2801 MemInitResult
   2802 Sema::ActOnMemInitializer(Decl *ConstructorD,
   2803                           Scope *S,
   2804                           CXXScopeSpec &SS,
   2805                           IdentifierInfo *MemberOrBase,
   2806                           ParsedType TemplateTypeTy,
   2807                           const DeclSpec &DS,
   2808                           SourceLocation IdLoc,
   2809                           SourceLocation LParenLoc,
   2810                           ArrayRef<Expr *> Args,
   2811                           SourceLocation RParenLoc,
   2812                           SourceLocation EllipsisLoc) {
   2813   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
   2814                                            Args, RParenLoc);
   2815   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
   2816                              DS, IdLoc, List, EllipsisLoc);
   2817 }
   2818 
   2819 namespace {
   2820 
   2821 // Callback to only accept typo corrections that can be a valid C++ member
   2822 // intializer: either a non-static field member or a base class.
   2823 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
   2824 public:
   2825   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
   2826       : ClassDecl(ClassDecl) {}
   2827 
   2828   bool ValidateCandidate(const TypoCorrection &candidate) override {
   2829     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
   2830       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
   2831         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
   2832       return isa<TypeDecl>(ND);
   2833     }
   2834     return false;
   2835   }
   2836 
   2837 private:
   2838   CXXRecordDecl *ClassDecl;
   2839 };
   2840 
   2841 }
   2842 
   2843 /// \brief Handle a C++ member initializer.
   2844 MemInitResult
   2845 Sema::BuildMemInitializer(Decl *ConstructorD,
   2846                           Scope *S,
   2847                           CXXScopeSpec &SS,
   2848                           IdentifierInfo *MemberOrBase,
   2849                           ParsedType TemplateTypeTy,
   2850                           const DeclSpec &DS,
   2851                           SourceLocation IdLoc,
   2852                           Expr *Init,
   2853                           SourceLocation EllipsisLoc) {
   2854   ExprResult Res = CorrectDelayedTyposInExpr(Init);
   2855   if (!Res.isUsable())
   2856     return true;
   2857   Init = Res.get();
   2858 
   2859   if (!ConstructorD)
   2860     return true;
   2861 
   2862   AdjustDeclIfTemplate(ConstructorD);
   2863 
   2864   CXXConstructorDecl *Constructor
   2865     = dyn_cast<CXXConstructorDecl>(ConstructorD);
   2866   if (!Constructor) {
   2867     // The user wrote a constructor initializer on a function that is
   2868     // not a C++ constructor. Ignore the error for now, because we may
   2869     // have more member initializers coming; we'll diagnose it just
   2870     // once in ActOnMemInitializers.
   2871     return true;
   2872   }
   2873 
   2874   CXXRecordDecl *ClassDecl = Constructor->getParent();
   2875 
   2876   // C++ [class.base.init]p2:
   2877   //   Names in a mem-initializer-id are looked up in the scope of the
   2878   //   constructor's class and, if not found in that scope, are looked
   2879   //   up in the scope containing the constructor's definition.
   2880   //   [Note: if the constructor's class contains a member with the
   2881   //   same name as a direct or virtual base class of the class, a
   2882   //   mem-initializer-id naming the member or base class and composed
   2883   //   of a single identifier refers to the class member. A
   2884   //   mem-initializer-id for the hidden base class may be specified
   2885   //   using a qualified name. ]
   2886   if (!SS.getScopeRep() && !TemplateTypeTy) {
   2887     // Look for a member, first.
   2888     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
   2889     if (!Result.empty()) {
   2890       ValueDecl *Member;
   2891       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
   2892           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
   2893         if (EllipsisLoc.isValid())
   2894           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
   2895             << MemberOrBase
   2896             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
   2897 
   2898         return BuildMemberInitializer(Member, Init, IdLoc);
   2899       }
   2900     }
   2901   }
   2902   // It didn't name a member, so see if it names a class.
   2903   QualType BaseType;
   2904   TypeSourceInfo *TInfo = nullptr;
   2905 
   2906   if (TemplateTypeTy) {
   2907     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
   2908   } else if (DS.getTypeSpecType() == TST_decltype) {
   2909     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
   2910   } else {
   2911     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
   2912     LookupParsedName(R, S, &SS);
   2913 
   2914     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
   2915     if (!TyD) {
   2916       if (R.isAmbiguous()) return true;
   2917 
   2918       // We don't want access-control diagnostics here.
   2919       R.suppressDiagnostics();
   2920 
   2921       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
   2922         bool NotUnknownSpecialization = false;
   2923         DeclContext *DC = computeDeclContext(SS, false);
   2924         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
   2925           NotUnknownSpecialization = !Record->hasAnyDependentBases();
   2926 
   2927         if (!NotUnknownSpecialization) {
   2928           // When the scope specifier can refer to a member of an unknown
   2929           // specialization, we take it as a type name.
   2930           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
   2931                                        SS.getWithLocInContext(Context),
   2932                                        *MemberOrBase, IdLoc);
   2933           if (BaseType.isNull())
   2934             return true;
   2935 
   2936           R.clear();
   2937           R.setLookupName(MemberOrBase);
   2938         }
   2939       }
   2940 
   2941       // If no results were found, try to correct typos.
   2942       TypoCorrection Corr;
   2943       if (R.empty() && BaseType.isNull() &&
   2944           (Corr = CorrectTypo(
   2945                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
   2946                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
   2947                CTK_ErrorRecovery, ClassDecl))) {
   2948         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
   2949           // We have found a non-static data member with a similar
   2950           // name to what was typed; complain and initialize that
   2951           // member.
   2952           diagnoseTypo(Corr,
   2953                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
   2954                          << MemberOrBase << true);
   2955           return BuildMemberInitializer(Member, Init, IdLoc);
   2956         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
   2957           const CXXBaseSpecifier *DirectBaseSpec;
   2958           const CXXBaseSpecifier *VirtualBaseSpec;
   2959           if (FindBaseInitializer(*this, ClassDecl,
   2960                                   Context.getTypeDeclType(Type),
   2961                                   DirectBaseSpec, VirtualBaseSpec)) {
   2962             // We have found a direct or virtual base class with a
   2963             // similar name to what was typed; complain and initialize
   2964             // that base class.
   2965             diagnoseTypo(Corr,
   2966                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
   2967                            << MemberOrBase << false,
   2968                          PDiag() /*Suppress note, we provide our own.*/);
   2969 
   2970             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
   2971                                                               : VirtualBaseSpec;
   2972             Diag(BaseSpec->getLocStart(),
   2973                  diag::note_base_class_specified_here)
   2974               << BaseSpec->getType()
   2975               << BaseSpec->getSourceRange();
   2976 
   2977             TyD = Type;
   2978           }
   2979         }
   2980       }
   2981 
   2982       if (!TyD && BaseType.isNull()) {
   2983         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
   2984           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
   2985         return true;
   2986       }
   2987     }
   2988 
   2989     if (BaseType.isNull()) {
   2990       BaseType = Context.getTypeDeclType(TyD);
   2991       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
   2992       if (SS.isSet()) {
   2993         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
   2994                                              BaseType);
   2995         TInfo = Context.CreateTypeSourceInfo(BaseType);
   2996         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
   2997         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
   2998         TL.setElaboratedKeywordLoc(SourceLocation());
   2999         TL.setQualifierLoc(SS.getWithLocInContext(Context));
   3000       }
   3001     }
   3002   }
   3003 
   3004   if (!TInfo)
   3005     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
   3006 
   3007   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
   3008 }
   3009 
   3010 /// Checks a member initializer expression for cases where reference (or
   3011 /// pointer) members are bound to by-value parameters (or their addresses).
   3012 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
   3013                                                Expr *Init,
   3014                                                SourceLocation IdLoc) {
   3015   QualType MemberTy = Member->getType();
   3016 
   3017   // We only handle pointers and references currently.
   3018   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
   3019   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
   3020     return;
   3021 
   3022   const bool IsPointer = MemberTy->isPointerType();
   3023   if (IsPointer) {
   3024     if (const UnaryOperator *Op
   3025           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
   3026       // The only case we're worried about with pointers requires taking the
   3027       // address.
   3028       if (Op->getOpcode() != UO_AddrOf)
   3029         return;
   3030 
   3031       Init = Op->getSubExpr();
   3032     } else {
   3033       // We only handle address-of expression initializers for pointers.
   3034       return;
   3035     }
   3036   }
   3037 
   3038   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
   3039     // We only warn when referring to a non-reference parameter declaration.
   3040     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
   3041     if (!Parameter || Parameter->getType()->isReferenceType())
   3042       return;
   3043 
   3044     S.Diag(Init->getExprLoc(),
   3045            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
   3046                      : diag::warn_bind_ref_member_to_parameter)
   3047       << Member << Parameter << Init->getSourceRange();
   3048   } else {
   3049     // Other initializers are fine.
   3050     return;
   3051   }
   3052 
   3053   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
   3054     << (unsigned)IsPointer;
   3055 }
   3056 
   3057 MemInitResult
   3058 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
   3059                              SourceLocation IdLoc) {
   3060   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
   3061   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
   3062   assert((DirectMember || IndirectMember) &&
   3063          "Member must be a FieldDecl or IndirectFieldDecl");
   3064 
   3065   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
   3066     return true;
   3067 
   3068   if (Member->isInvalidDecl())
   3069     return true;
   3070 
   3071   MultiExprArg Args;
   3072   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
   3073     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
   3074   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
   3075     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
   3076   } else {
   3077     // Template instantiation doesn't reconstruct ParenListExprs for us.
   3078     Args = Init;
   3079   }
   3080 
   3081   SourceRange InitRange = Init->getSourceRange();
   3082 
   3083   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
   3084     // Can't check initialization for a member of dependent type or when
   3085     // any of the arguments are type-dependent expressions.
   3086     DiscardCleanupsInEvaluationContext();
   3087   } else {
   3088     bool InitList = false;
   3089     if (isa<InitListExpr>(Init)) {
   3090       InitList = true;
   3091       Args = Init;
   3092     }
   3093 
   3094     // Initialize the member.
   3095     InitializedEntity MemberEntity =
   3096       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
   3097                    : InitializedEntity::InitializeMember(IndirectMember,
   3098                                                          nullptr);
   3099     InitializationKind Kind =
   3100       InitList ? InitializationKind::CreateDirectList(IdLoc)
   3101                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
   3102                                                   InitRange.getEnd());
   3103 
   3104     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
   3105     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
   3106                                             nullptr);
   3107     if (MemberInit.isInvalid())
   3108       return true;
   3109 
   3110     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
   3111 
   3112     // C++11 [class.base.init]p7:
   3113     //   The initialization of each base and member constitutes a
   3114     //   full-expression.
   3115     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
   3116     if (MemberInit.isInvalid())
   3117       return true;
   3118 
   3119     Init = MemberInit.get();
   3120   }
   3121 
   3122   if (DirectMember) {
   3123     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
   3124                                             InitRange.getBegin(), Init,
   3125                                             InitRange.getEnd());
   3126   } else {
   3127     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
   3128                                             InitRange.getBegin(), Init,
   3129                                             InitRange.getEnd());
   3130   }
   3131 }
   3132 
   3133 MemInitResult
   3134 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
   3135                                  CXXRecordDecl *ClassDecl) {
   3136   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
   3137   if (!LangOpts.CPlusPlus11)
   3138     return Diag(NameLoc, diag::err_delegating_ctor)
   3139       << TInfo->getTypeLoc().getLocalSourceRange();
   3140   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
   3141 
   3142   bool InitList = true;
   3143   MultiExprArg Args = Init;
   3144   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
   3145     InitList = false;
   3146     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
   3147   }
   3148 
   3149   SourceRange InitRange = Init->getSourceRange();
   3150   // Initialize the object.
   3151   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
   3152                                      QualType(ClassDecl->getTypeForDecl(), 0));
   3153   InitializationKind Kind =
   3154     InitList ? InitializationKind::CreateDirectList(NameLoc)
   3155              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
   3156                                                 InitRange.getEnd());
   3157   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
   3158   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
   3159                                               Args, nullptr);
   3160   if (DelegationInit.isInvalid())
   3161     return true;
   3162 
   3163   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
   3164          "Delegating constructor with no target?");
   3165 
   3166   // C++11 [class.base.init]p7:
   3167   //   The initialization of each base and member constitutes a
   3168   //   full-expression.
   3169   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
   3170                                        InitRange.getBegin());
   3171   if (DelegationInit.isInvalid())
   3172     return true;
   3173 
   3174   // If we are in a dependent context, template instantiation will
   3175   // perform this type-checking again. Just save the arguments that we
   3176   // received in a ParenListExpr.
   3177   // FIXME: This isn't quite ideal, since our ASTs don't capture all
   3178   // of the information that we have about the base
   3179   // initializer. However, deconstructing the ASTs is a dicey process,
   3180   // and this approach is far more likely to get the corner cases right.
   3181   if (CurContext->isDependentContext())
   3182     DelegationInit = Init;
   3183 
   3184   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
   3185                                           DelegationInit.getAs<Expr>(),
   3186                                           InitRange.getEnd());
   3187 }
   3188 
   3189 MemInitResult
   3190 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
   3191                            Expr *Init, CXXRecordDecl *ClassDecl,
   3192                            SourceLocation EllipsisLoc) {
   3193   SourceLocation BaseLoc
   3194     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
   3195 
   3196   if (!BaseType->isDependentType() && !BaseType->isRecordType())
   3197     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
   3198              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
   3199 
   3200   // C++ [class.base.init]p2:
   3201   //   [...] Unless the mem-initializer-id names a nonstatic data
   3202   //   member of the constructor's class or a direct or virtual base
   3203   //   of that class, the mem-initializer is ill-formed. A
   3204   //   mem-initializer-list can initialize a base class using any
   3205   //   name that denotes that base class type.
   3206   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
   3207 
   3208   SourceRange InitRange = Init->getSourceRange();
   3209   if (EllipsisLoc.isValid()) {
   3210     // This is a pack expansion.
   3211     if (!BaseType->containsUnexpandedParameterPack())  {
   3212       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
   3213         << SourceRange(BaseLoc, InitRange.getEnd());
   3214 
   3215       EllipsisLoc = SourceLocation();
   3216     }
   3217   } else {
   3218     // Check for any unexpanded parameter packs.
   3219     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
   3220       return true;
   3221 
   3222     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
   3223       return true;
   3224   }
   3225 
   3226   // Check for direct and virtual base classes.
   3227   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
   3228   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
   3229   if (!Dependent) {
   3230     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
   3231                                        BaseType))
   3232       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
   3233 
   3234     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
   3235                         VirtualBaseSpec);
   3236 
   3237     // C++ [base.class.init]p2:
   3238     // Unless the mem-initializer-id names a nonstatic data member of the
   3239     // constructor's class or a direct or virtual base of that class, the
   3240     // mem-initializer is ill-formed.
   3241     if (!DirectBaseSpec && !VirtualBaseSpec) {
   3242       // If the class has any dependent bases, then it's possible that
   3243       // one of those types will resolve to the same type as
   3244       // BaseType. Therefore, just treat this as a dependent base
   3245       // class initialization.  FIXME: Should we try to check the
   3246       // initialization anyway? It seems odd.
   3247       if (ClassDecl->hasAnyDependentBases())
   3248         Dependent = true;
   3249       else
   3250         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
   3251           << BaseType << Context.getTypeDeclType(ClassDecl)
   3252           << BaseTInfo->getTypeLoc().getLocalSourceRange();
   3253     }
   3254   }
   3255 
   3256   if (Dependent) {
   3257     DiscardCleanupsInEvaluationContext();
   3258 
   3259     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
   3260                                             /*IsVirtual=*/false,
   3261                                             InitRange.getBegin(), Init,
   3262                                             InitRange.getEnd(), EllipsisLoc);
   3263   }
   3264 
   3265   // C++ [base.class.init]p2:
   3266   //   If a mem-initializer-id is ambiguous because it designates both
   3267   //   a direct non-virtual base class and an inherited virtual base
   3268   //   class, the mem-initializer is ill-formed.
   3269   if (DirectBaseSpec && VirtualBaseSpec)
   3270     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
   3271       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
   3272 
   3273   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
   3274   if (!BaseSpec)
   3275     BaseSpec = VirtualBaseSpec;
   3276 
   3277   // Initialize the base.
   3278   bool InitList = true;
   3279   MultiExprArg Args = Init;
   3280   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
   3281     InitList = false;
   3282     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
   3283   }
   3284 
   3285   InitializedEntity BaseEntity =
   3286     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
   3287   InitializationKind Kind =
   3288     InitList ? InitializationKind::CreateDirectList(BaseLoc)
   3289              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
   3290                                                 InitRange.getEnd());
   3291   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
   3292   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
   3293   if (BaseInit.isInvalid())
   3294     return true;
   3295 
   3296   // C++11 [class.base.init]p7:
   3297   //   The initialization of each base and member constitutes a
   3298   //   full-expression.
   3299   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
   3300   if (BaseInit.isInvalid())
   3301     return true;
   3302 
   3303   // If we are in a dependent context, template instantiation will
   3304   // perform this type-checking again. Just save the arguments that we
   3305   // received in a ParenListExpr.
   3306   // FIXME: This isn't quite ideal, since our ASTs don't capture all
   3307   // of the information that we have about the base
   3308   // initializer. However, deconstructing the ASTs is a dicey process,
   3309   // and this approach is far more likely to get the corner cases right.
   3310   if (CurContext->isDependentContext())
   3311     BaseInit = Init;
   3312 
   3313   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
   3314                                           BaseSpec->isVirtual(),
   3315                                           InitRange.getBegin(),
   3316                                           BaseInit.getAs<Expr>(),
   3317                                           InitRange.getEnd(), EllipsisLoc);
   3318 }
   3319 
   3320 // Create a static_cast\<T&&>(expr).
   3321 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
   3322   if (T.isNull()) T = E->getType();
   3323   QualType TargetType = SemaRef.BuildReferenceType(
   3324       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
   3325   SourceLocation ExprLoc = E->getLocStart();
   3326   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
   3327       TargetType, ExprLoc);
   3328 
   3329   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
   3330                                    SourceRange(ExprLoc, ExprLoc),
   3331                                    E->getSourceRange()).get();
   3332 }
   3333 
   3334 /// ImplicitInitializerKind - How an implicit base or member initializer should
   3335 /// initialize its base or member.
   3336 enum ImplicitInitializerKind {
   3337   IIK_Default,
   3338   IIK_Copy,
   3339   IIK_Move,
   3340   IIK_Inherit
   3341 };
   3342 
   3343 static bool
   3344 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
   3345                              ImplicitInitializerKind ImplicitInitKind,
   3346                              CXXBaseSpecifier *BaseSpec,
   3347                              bool IsInheritedVirtualBase,
   3348                              CXXCtorInitializer *&CXXBaseInit) {
   3349   InitializedEntity InitEntity
   3350     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
   3351                                         IsInheritedVirtualBase);
   3352 
   3353   ExprResult BaseInit;
   3354 
   3355   switch (ImplicitInitKind) {
   3356   case IIK_Inherit: {
   3357     const CXXRecordDecl *Inherited =
   3358         Constructor->getInheritedConstructor()->getParent();
   3359     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
   3360     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
   3361       // C++11 [class.inhctor]p8:
   3362       //   Each expression in the expression-list is of the form
   3363       //   static_cast<T&&>(p), where p is the name of the corresponding
   3364       //   constructor parameter and T is the declared type of p.
   3365       SmallVector<Expr*, 16> Args;
   3366       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
   3367         ParmVarDecl *PD = Constructor->getParamDecl(I);
   3368         ExprResult ArgExpr =
   3369             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
   3370                                      VK_LValue, SourceLocation());
   3371         if (ArgExpr.isInvalid())
   3372           return true;
   3373         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
   3374       }
   3375 
   3376       InitializationKind InitKind = InitializationKind::CreateDirect(
   3377           Constructor->getLocation(), SourceLocation(), SourceLocation());
   3378       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
   3379       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
   3380       break;
   3381     }
   3382   }
   3383   // Fall through.
   3384   case IIK_Default: {
   3385     InitializationKind InitKind
   3386       = InitializationKind::CreateDefault(Constructor->getLocation());
   3387     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
   3388     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
   3389     break;
   3390   }
   3391 
   3392   case IIK_Move:
   3393   case IIK_Copy: {
   3394     bool Moving = ImplicitInitKind == IIK_Move;
   3395     ParmVarDecl *Param = Constructor->getParamDecl(0);
   3396     QualType ParamType = Param->getType().getNonReferenceType();
   3397 
   3398     Expr *CopyCtorArg =
   3399       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
   3400                           SourceLocation(), Param, false,
   3401                           Constructor->getLocation(), ParamType,
   3402                           VK_LValue, nullptr);
   3403 
   3404     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
   3405 
   3406     // Cast to the base class to avoid ambiguities.
   3407     QualType ArgTy =
   3408       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
   3409                                        ParamType.getQualifiers());
   3410 
   3411     if (Moving) {
   3412       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
   3413     }
   3414 
   3415     CXXCastPath BasePath;
   3416     BasePath.push_back(BaseSpec);
   3417     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
   3418                                             CK_UncheckedDerivedToBase,
   3419                                             Moving ? VK_XValue : VK_LValue,
   3420                                             &BasePath).get();
   3421 
   3422     InitializationKind InitKind
   3423       = InitializationKind::CreateDirect(Constructor->getLocation(),
   3424                                          SourceLocation(), SourceLocation());
   3425     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
   3426     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
   3427     break;
   3428   }
   3429   }
   3430 
   3431   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
   3432   if (BaseInit.isInvalid())
   3433     return true;
   3434 
   3435   CXXBaseInit =
   3436     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
   3437                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
   3438                                                         SourceLocation()),
   3439                                              BaseSpec->isVirtual(),
   3440                                              SourceLocation(),
   3441                                              BaseInit.getAs<Expr>(),
   3442                                              SourceLocation(),
   3443                                              SourceLocation());
   3444 
   3445   return false;
   3446 }
   3447 
   3448 static bool RefersToRValueRef(Expr *MemRef) {
   3449   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
   3450   return Referenced->getType()->isRValueReferenceType();
   3451 }
   3452 
   3453 static bool
   3454 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
   3455                                ImplicitInitializerKind ImplicitInitKind,
   3456                                FieldDecl *Field, IndirectFieldDecl *Indirect,
   3457                                CXXCtorInitializer *&CXXMemberInit) {
   3458   if (Field->isInvalidDecl())
   3459     return true;
   3460 
   3461   SourceLocation Loc = Constructor->getLocation();
   3462 
   3463   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
   3464     bool Moving = ImplicitInitKind == IIK_Move;
   3465     ParmVarDecl *Param = Constructor->getParamDecl(0);
   3466     QualType ParamType = Param->getType().getNonReferenceType();
   3467 
   3468     // Suppress copying zero-width bitfields.
   3469     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
   3470       return false;
   3471 
   3472     Expr *MemberExprBase =
   3473       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
   3474                           SourceLocation(), Param, false,
   3475                           Loc, ParamType, VK_LValue, nullptr);
   3476 
   3477     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
   3478 
   3479     if (Moving) {
   3480       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
   3481     }
   3482 
   3483     // Build a reference to this field within the parameter.
   3484     CXXScopeSpec SS;
   3485     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
   3486                               Sema::LookupMemberName);
   3487     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
   3488                                   : cast<ValueDecl>(Field), AS_public);
   3489     MemberLookup.resolveKind();
   3490     ExprResult CtorArg
   3491       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
   3492                                          ParamType, Loc,
   3493                                          /*IsArrow=*/false,
   3494                                          SS,
   3495                                          /*TemplateKWLoc=*/SourceLocation(),
   3496                                          /*FirstQualifierInScope=*/nullptr,
   3497                                          MemberLookup,
   3498                                          /*TemplateArgs=*/nullptr,
   3499                                          /*S*/nullptr);
   3500     if (CtorArg.isInvalid())
   3501       return true;
   3502 
   3503     // C++11 [class.copy]p15:
   3504     //   - if a member m has rvalue reference type T&&, it is direct-initialized
   3505     //     with static_cast<T&&>(x.m);
   3506     if (RefersToRValueRef(CtorArg.get())) {
   3507       CtorArg = CastForMoving(SemaRef, CtorArg.get());
   3508     }
   3509 
   3510     // When the field we are copying is an array, create index variables for
   3511     // each dimension of the array. We use these index variables to subscript
   3512     // the source array, and other clients (e.g., CodeGen) will perform the
   3513     // necessary iteration with these index variables.
   3514     SmallVector<VarDecl *, 4> IndexVariables;
   3515     QualType BaseType = Field->getType();
   3516     QualType SizeType = SemaRef.Context.getSizeType();
   3517     bool InitializingArray = false;
   3518     while (const ConstantArrayType *Array
   3519                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
   3520       InitializingArray = true;
   3521       // Create the iteration variable for this array index.
   3522       IdentifierInfo *IterationVarName = nullptr;
   3523       {
   3524         SmallString<8> Str;
   3525         llvm::raw_svector_ostream OS(Str);
   3526         OS << "__i" << IndexVariables.size();
   3527         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
   3528       }
   3529       VarDecl *IterationVar
   3530         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
   3531                           IterationVarName, SizeType,
   3532                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
   3533                           SC_None);
   3534       IndexVariables.push_back(IterationVar);
   3535 
   3536       // Create a reference to the iteration variable.
   3537       ExprResult IterationVarRef
   3538         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
   3539       assert(!IterationVarRef.isInvalid() &&
   3540              "Reference to invented variable cannot fail!");
   3541       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
   3542       assert(!IterationVarRef.isInvalid() &&
   3543              "Conversion of invented variable cannot fail!");
   3544 
   3545       // Subscript the array with this iteration variable.
   3546       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
   3547                                                         IterationVarRef.get(),
   3548                                                         Loc);
   3549       if (CtorArg.isInvalid())
   3550         return true;
   3551 
   3552       BaseType = Array->getElementType();
   3553     }
   3554 
   3555     // The array subscript expression is an lvalue, which is wrong for moving.
   3556     if (Moving && InitializingArray)
   3557       CtorArg = CastForMoving(SemaRef, CtorArg.get());
   3558 
   3559     // Construct the entity that we will be initializing. For an array, this
   3560     // will be first element in the array, which may require several levels
   3561     // of array-subscript entities.
   3562     SmallVector<InitializedEntity, 4> Entities;
   3563     Entities.reserve(1 + IndexVariables.size());
   3564     if (Indirect)
   3565       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
   3566     else
   3567       Entities.push_back(InitializedEntity::InitializeMember(Field));
   3568     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
   3569       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
   3570                                                               0,
   3571                                                               Entities.back()));
   3572 
   3573     // Direct-initialize to use the copy constructor.
   3574     InitializationKind InitKind =
   3575       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
   3576 
   3577     Expr *CtorArgE = CtorArg.getAs<Expr>();
   3578     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
   3579                                    CtorArgE);
   3580 
   3581     ExprResult MemberInit
   3582       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
   3583                         MultiExprArg(&CtorArgE, 1));
   3584     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
   3585     if (MemberInit.isInvalid())
   3586       return true;
   3587 
   3588     if (Indirect) {
   3589       assert(IndexVariables.size() == 0 &&
   3590              "Indirect field improperly initialized");
   3591       CXXMemberInit
   3592         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
   3593                                                    Loc, Loc,
   3594                                                    MemberInit.getAs<Expr>(),
   3595                                                    Loc);
   3596     } else
   3597       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
   3598                                                  Loc, MemberInit.getAs<Expr>(),
   3599                                                  Loc,
   3600                                                  IndexVariables.data(),
   3601                                                  IndexVariables.size());
   3602     return false;
   3603   }
   3604 
   3605   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
   3606          "Unhandled implicit init kind!");
   3607 
   3608   QualType FieldBaseElementType =
   3609     SemaRef.Context.getBaseElementType(Field->getType());
   3610 
   3611   if (FieldBaseElementType->isRecordType()) {
   3612     InitializedEntity InitEntity
   3613       = Indirect? InitializedEntity::InitializeMember(Indirect)
   3614                 : InitializedEntity::InitializeMember(Field);
   3615     InitializationKind InitKind =
   3616       InitializationKind::CreateDefault(Loc);
   3617 
   3618     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
   3619     ExprResult MemberInit =
   3620       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
   3621 
   3622     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
   3623     if (MemberInit.isInvalid())
   3624       return true;
   3625 
   3626     if (Indirect)
   3627       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
   3628                                                                Indirect, Loc,
   3629                                                                Loc,
   3630                                                                MemberInit.get(),
   3631                                                                Loc);
   3632     else
   3633       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
   3634                                                                Field, Loc, Loc,
   3635                                                                MemberInit.get(),
   3636                                                                Loc);
   3637     return false;
   3638   }
   3639 
   3640   if (!Field->getParent()->isUnion()) {
   3641     if (FieldBaseElementType->isReferenceType()) {
   3642       SemaRef.Diag(Constructor->getLocation(),
   3643                    diag::err_uninitialized_member_in_ctor)
   3644       << (int)Constructor->isImplicit()
   3645       << SemaRef.Context.getTagDeclType(Constructor->getParent())
   3646       << 0 << Field->getDeclName();
   3647       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
   3648       return true;
   3649     }
   3650 
   3651     if (FieldBaseElementType.isConstQualified()) {
   3652       SemaRef.Diag(Constructor->getLocation(),
   3653                    diag::err_uninitialized_member_in_ctor)
   3654       << (int)Constructor->isImplicit()
   3655       << SemaRef.Context.getTagDeclType(Constructor->getParent())
   3656       << 1 << Field->getDeclName();
   3657       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
   3658       return true;
   3659     }
   3660   }
   3661 
   3662   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
   3663       FieldBaseElementType->isObjCRetainableType() &&
   3664       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
   3665       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
   3666     // ARC:
   3667     //   Default-initialize Objective-C pointers to NULL.
   3668     CXXMemberInit
   3669       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
   3670                                                  Loc, Loc,
   3671                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
   3672                                                  Loc);
   3673     return false;
   3674   }
   3675 
   3676   // Nothing to initialize.
   3677   CXXMemberInit = nullptr;
   3678   return false;
   3679 }
   3680 
   3681 namespace {
   3682 struct BaseAndFieldInfo {
   3683   Sema &S;
   3684   CXXConstructorDecl *Ctor;
   3685   bool AnyErrorsInInits;
   3686   ImplicitInitializerKind IIK;
   3687   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
   3688   SmallVector<CXXCtorInitializer*, 8> AllToInit;
   3689   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
   3690 
   3691   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
   3692     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
   3693     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
   3694     if (Generated && Ctor->isCopyConstructor())
   3695       IIK = IIK_Copy;
   3696     else if (Generated && Ctor->isMoveConstructor())
   3697       IIK = IIK_Move;
   3698     else if (Ctor->getInheritedConstructor())
   3699       IIK = IIK_Inherit;
   3700     else
   3701       IIK = IIK_Default;
   3702   }
   3703 
   3704   bool isImplicitCopyOrMove() const {
   3705     switch (IIK) {
   3706     case IIK_Copy:
   3707     case IIK_Move:
   3708       return true;
   3709 
   3710     case IIK_Default:
   3711     case IIK_Inherit:
   3712       return false;
   3713     }
   3714 
   3715     llvm_unreachable("Invalid ImplicitInitializerKind!");
   3716   }
   3717 
   3718   bool addFieldInitializer(CXXCtorInitializer *Init) {
   3719     AllToInit.push_back(Init);
   3720 
   3721     // Check whether this initializer makes the field "used".
   3722     if (Init->getInit()->HasSideEffects(S.Context))
   3723       S.UnusedPrivateFields.remove(Init->getAnyMember());
   3724 
   3725     return false;
   3726   }
   3727 
   3728   bool isInactiveUnionMember(FieldDecl *Field) {
   3729     RecordDecl *Record = Field->getParent();
   3730     if (!Record->isUnion())
   3731       return false;
   3732 
   3733     if (FieldDecl *Active =
   3734             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
   3735       return Active != Field->getCanonicalDecl();
   3736 
   3737     // In an implicit copy or move constructor, ignore any in-class initializer.
   3738     if (isImplicitCopyOrMove())
   3739       return true;
   3740 
   3741     // If there's no explicit initialization, the field is active only if it
   3742     // has an in-class initializer...
   3743     if (Field->hasInClassInitializer())
   3744       return false;
   3745     // ... or it's an anonymous struct or union whose class has an in-class
   3746     // initializer.
   3747     if (!Field->isAnonymousStructOrUnion())
   3748       return true;
   3749     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
   3750     return !FieldRD->hasInClassInitializer();
   3751   }
   3752 
   3753   /// \brief Determine whether the given field is, or is within, a union member
   3754   /// that is inactive (because there was an initializer given for a different
   3755   /// member of the union, or because the union was not initialized at all).
   3756   bool isWithinInactiveUnionMember(FieldDecl *Field,
   3757                                    IndirectFieldDecl *Indirect) {
   3758     if (!Indirect)
   3759       return isInactiveUnionMember(Field);
   3760 
   3761     for (auto *C : Indirect->chain()) {
   3762       FieldDecl *Field = dyn_cast<FieldDecl>(C);
   3763       if (Field && isInactiveUnionMember(Field))
   3764         return true;
   3765     }
   3766     return false;
   3767   }
   3768 };
   3769 }
   3770 
   3771 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
   3772 /// array type.
   3773 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
   3774   if (T->isIncompleteArrayType())
   3775     return true;
   3776 
   3777   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
   3778     if (!ArrayT->getSize())
   3779       return true;
   3780 
   3781     T = ArrayT->getElementType();
   3782   }
   3783 
   3784   return false;
   3785 }
   3786 
   3787 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
   3788                                     FieldDecl *Field,
   3789                                     IndirectFieldDecl *Indirect = nullptr) {
   3790   if (Field->isInvalidDecl())
   3791     return false;
   3792 
   3793   // Overwhelmingly common case: we have a direct initializer for this field.
   3794   if (CXXCtorInitializer *Init =
   3795           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
   3796     return Info.addFieldInitializer(Init);
   3797 
   3798   // C++11 [class.base.init]p8:
   3799   //   if the entity is a non-static data member that has a
   3800   //   brace-or-equal-initializer and either
   3801   //   -- the constructor's class is a union and no other variant member of that
   3802   //      union is designated by a mem-initializer-id or
   3803   //   -- the constructor's class is not a union, and, if the entity is a member
   3804   //      of an anonymous union, no other member of that union is designated by
   3805   //      a mem-initializer-id,
   3806   //   the entity is initialized as specified in [dcl.init].
   3807   //
   3808   // We also apply the same rules to handle anonymous structs within anonymous
   3809   // unions.
   3810   if (Info.isWithinInactiveUnionMember(Field, Indirect))
   3811     return false;
   3812 
   3813   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
   3814     ExprResult DIE =
   3815         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
   3816     if (DIE.isInvalid())
   3817       return true;
   3818     CXXCtorInitializer *Init;
   3819     if (Indirect)
   3820       Init = new (SemaRef.Context)
   3821           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
   3822                              SourceLocation(), DIE.get(), SourceLocation());
   3823     else
   3824       Init = new (SemaRef.Context)
   3825           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
   3826                              SourceLocation(), DIE.get(), SourceLocation());
   3827     return Info.addFieldInitializer(Init);
   3828   }
   3829 
   3830   // Don't initialize incomplete or zero-length arrays.
   3831   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
   3832     return false;
   3833 
   3834   // Don't try to build an implicit initializer if there were semantic
   3835   // errors in any of the initializers (and therefore we might be
   3836   // missing some that the user actually wrote).
   3837   if (Info.AnyErrorsInInits)
   3838     return false;
   3839 
   3840   CXXCtorInitializer *Init = nullptr;
   3841   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
   3842                                      Indirect, Init))
   3843     return true;
   3844 
   3845   if (!Init)
   3846     return false;
   3847 
   3848   return Info.addFieldInitializer(Init);
   3849 }
   3850 
   3851 bool
   3852 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
   3853                                CXXCtorInitializer *Initializer) {
   3854   assert(Initializer->isDelegatingInitializer());
   3855   Constructor->setNumCtorInitializers(1);
   3856   CXXCtorInitializer **initializer =
   3857     new (Context) CXXCtorInitializer*[1];
   3858   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
   3859   Constructor->setCtorInitializers(initializer);
   3860 
   3861   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
   3862     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
   3863     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
   3864   }
   3865 
   3866   DelegatingCtorDecls.push_back(Constructor);
   3867 
   3868   DiagnoseUninitializedFields(*this, Constructor);
   3869 
   3870   return false;
   3871 }
   3872 
   3873 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
   3874                                ArrayRef<CXXCtorInitializer *> Initializers) {
   3875   if (Constructor->isDependentContext()) {
   3876     // Just store the initializers as written, they will be checked during
   3877     // instantiation.
   3878     if (!Initializers.empty()) {
   3879       Constructor->setNumCtorInitializers(Initializers.size());
   3880       CXXCtorInitializer **baseOrMemberInitializers =
   3881         new (Context) CXXCtorInitializer*[Initializers.size()];
   3882       memcpy(baseOrMemberInitializers, Initializers.data(),
   3883              Initializers.size() * sizeof(CXXCtorInitializer*));
   3884       Constructor->setCtorInitializers(baseOrMemberInitializers);
   3885     }
   3886 
   3887     // Let template instantiation know whether we had errors.
   3888     if (AnyErrors)
   3889       Constructor->setInvalidDecl();
   3890 
   3891     return false;
   3892   }
   3893 
   3894   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
   3895 
   3896   // We need to build the initializer AST according to order of construction
   3897   // and not what user specified in the Initializers list.
   3898   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
   3899   if (!ClassDecl)
   3900     return true;
   3901 
   3902   bool HadError = false;
   3903 
   3904   for (unsigned i = 0; i < Initializers.size(); i++) {
   3905     CXXCtorInitializer *Member = Initializers[i];
   3906 
   3907     if (Member->isBaseInitializer())
   3908       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
   3909     else {
   3910       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
   3911 
   3912       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
   3913         for (auto *C : F->chain()) {
   3914           FieldDecl *FD = dyn_cast<FieldDecl>(C);
   3915           if (FD && FD->getParent()->isUnion())
   3916             Info.ActiveUnionMember.insert(std::make_pair(
   3917                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
   3918         }
   3919       } else if (FieldDecl *FD = Member->getMember()) {
   3920         if (FD->getParent()->isUnion())
   3921           Info.ActiveUnionMember.insert(std::make_pair(
   3922               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
   3923       }
   3924     }
   3925   }
   3926 
   3927   // Keep track of the direct virtual bases.
   3928   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
   3929   for (auto &I : ClassDecl->bases()) {
   3930     if (I.isVirtual())
   3931       DirectVBases.insert(&I);
   3932   }
   3933 
   3934   // Push virtual bases before others.
   3935   for (auto &VBase : ClassDecl->vbases()) {
   3936     if (CXXCtorInitializer *Value
   3937         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
   3938       // [class.base.init]p7, per DR257:
   3939       //   A mem-initializer where the mem-initializer-id names a virtual base
   3940       //   class is ignored during execution of a constructor of any class that
   3941       //   is not the most derived class.
   3942       if (ClassDecl->isAbstract()) {
   3943         // FIXME: Provide a fixit to remove the base specifier. This requires
   3944         // tracking the location of the associated comma for a base specifier.
   3945         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
   3946           << VBase.getType() << ClassDecl;
   3947         DiagnoseAbstractType(ClassDecl);
   3948       }
   3949 
   3950       Info.AllToInit.push_back(Value);
   3951     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
   3952       // [class.base.init]p8, per DR257:
   3953       //   If a given [...] base class is not named by a mem-initializer-id
   3954       //   [...] and the entity is not a virtual base class of an abstract
   3955       //   class, then [...] the entity is default-initialized.
   3956       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
   3957       CXXCtorInitializer *CXXBaseInit;
   3958       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
   3959                                        &VBase, IsInheritedVirtualBase,
   3960                                        CXXBaseInit)) {
   3961         HadError = true;
   3962         continue;
   3963       }
   3964 
   3965       Info.AllToInit.push_back(CXXBaseInit);
   3966     }
   3967   }
   3968 
   3969   // Non-virtual bases.
   3970   for (auto &Base : ClassDecl->bases()) {
   3971     // Virtuals are in the virtual base list and already constructed.
   3972     if (Base.isVirtual())
   3973       continue;
   3974 
   3975     if (CXXCtorInitializer *Value
   3976           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
   3977       Info.AllToInit.push_back(Value);
   3978     } else if (!AnyErrors) {
   3979       CXXCtorInitializer *CXXBaseInit;
   3980       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
   3981                                        &Base, /*IsInheritedVirtualBase=*/false,
   3982                                        CXXBaseInit)) {
   3983         HadError = true;
   3984         continue;
   3985       }
   3986 
   3987       Info.AllToInit.push_back(CXXBaseInit);
   3988     }
   3989   }
   3990 
   3991   // Fields.
   3992   for (auto *Mem : ClassDecl->decls()) {
   3993     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
   3994       // C++ [class.bit]p2:
   3995       //   A declaration for a bit-field that omits the identifier declares an
   3996       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
   3997       //   initialized.
   3998       if (F->isUnnamedBitfield())
   3999         continue;
   4000 
   4001       // If we're not generating the implicit copy/move constructor, then we'll
   4002       // handle anonymous struct/union fields based on their individual
   4003       // indirect fields.
   4004       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
   4005         continue;
   4006 
   4007       if (CollectFieldInitializer(*this, Info, F))
   4008         HadError = true;
   4009       continue;
   4010     }
   4011 
   4012     // Beyond this point, we only consider default initialization.
   4013     if (Info.isImplicitCopyOrMove())
   4014       continue;
   4015 
   4016     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
   4017       if (F->getType()->isIncompleteArrayType()) {
   4018         assert(ClassDecl->hasFlexibleArrayMember() &&
   4019                "Incomplete array type is not valid");
   4020         continue;
   4021       }
   4022 
   4023       // Initialize each field of an anonymous struct individually.
   4024       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
   4025         HadError = true;
   4026 
   4027       continue;
   4028     }
   4029   }
   4030 
   4031   unsigned NumInitializers = Info.AllToInit.size();
   4032   if (NumInitializers > 0) {
   4033     Constructor->setNumCtorInitializers(NumInitializers);
   4034     CXXCtorInitializer **baseOrMemberInitializers =
   4035       new (Context) CXXCtorInitializer*[NumInitializers];
   4036     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
   4037            NumInitializers * sizeof(CXXCtorInitializer*));
   4038     Constructor->setCtorInitializers(baseOrMemberInitializers);
   4039 
   4040     // Constructors implicitly reference the base and member
   4041     // destructors.
   4042     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
   4043                                            Constructor->getParent());
   4044   }
   4045 
   4046   return HadError;
   4047 }
   4048 
   4049 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
   4050   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
   4051     const RecordDecl *RD = RT->getDecl();
   4052     if (RD->isAnonymousStructOrUnion()) {
   4053       for (auto *Field : RD->fields())
   4054         PopulateKeysForFields(Field, IdealInits);
   4055       return;
   4056     }
   4057   }
   4058   IdealInits.push_back(Field->getCanonicalDecl());
   4059 }
   4060 
   4061 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
   4062   return Context.getCanonicalType(BaseType).getTypePtr();
   4063 }
   4064 
   4065 static const void *GetKeyForMember(ASTContext &Context,
   4066                                    CXXCtorInitializer *Member) {
   4067   if (!Member->isAnyMemberInitializer())
   4068     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
   4069 
   4070   return Member->getAnyMember()->getCanonicalDecl();
   4071 }
   4072 
   4073 static void DiagnoseBaseOrMemInitializerOrder(
   4074     Sema &SemaRef, const CXXConstructorDecl *Constructor,
   4075     ArrayRef<CXXCtorInitializer *> Inits) {
   4076   if (Constructor->getDeclContext()->isDependentContext())
   4077     return;
   4078 
   4079   // Don't check initializers order unless the warning is enabled at the
   4080   // location of at least one initializer.
   4081   bool ShouldCheckOrder = false;
   4082   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
   4083     CXXCtorInitializer *Init = Inits[InitIndex];
   4084     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
   4085                                  Init->getSourceLocation())) {
   4086       ShouldCheckOrder = true;
   4087       break;
   4088     }
   4089   }
   4090   if (!ShouldCheckOrder)
   4091     return;
   4092 
   4093   // Build the list of bases and members in the order that they'll
   4094   // actually be initialized.  The explicit initializers should be in
   4095   // this same order but may be missing things.
   4096   SmallVector<const void*, 32> IdealInitKeys;
   4097 
   4098   const CXXRecordDecl *ClassDecl = Constructor->getParent();
   4099 
   4100   // 1. Virtual bases.
   4101   for (const auto &VBase : ClassDecl->vbases())
   4102     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
   4103 
   4104   // 2. Non-virtual bases.
   4105   for (const auto &Base : ClassDecl->bases()) {
   4106     if (Base.isVirtual())
   4107       continue;
   4108     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
   4109   }
   4110 
   4111   // 3. Direct fields.
   4112   for (auto *Field : ClassDecl->fields()) {
   4113     if (Field->isUnnamedBitfield())
   4114       continue;
   4115 
   4116     PopulateKeysForFields(Field, IdealInitKeys);
   4117   }
   4118 
   4119   unsigned NumIdealInits = IdealInitKeys.size();
   4120   unsigned IdealIndex = 0;
   4121 
   4122   CXXCtorInitializer *PrevInit = nullptr;
   4123   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
   4124     CXXCtorInitializer *Init = Inits[InitIndex];
   4125     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
   4126 
   4127     // Scan forward to try to find this initializer in the idealized
   4128     // initializers list.
   4129     for (; IdealIndex != NumIdealInits; ++IdealIndex)
   4130       if (InitKey == IdealInitKeys[IdealIndex])
   4131         break;
   4132 
   4133     // If we didn't find this initializer, it must be because we
   4134     // scanned past it on a previous iteration.  That can only
   4135     // happen if we're out of order;  emit a warning.
   4136     if (IdealIndex == NumIdealInits && PrevInit) {
   4137       Sema::SemaDiagnosticBuilder D =
   4138         SemaRef.Diag(PrevInit->getSourceLocation(),
   4139                      diag::warn_initializer_out_of_order);
   4140 
   4141       if (PrevInit->isAnyMemberInitializer())
   4142         D << 0 << PrevInit->getAnyMember()->getDeclName();
   4143       else
   4144         D << 1 << PrevInit->getTypeSourceInfo()->getType();
   4145 
   4146       if (Init->isAnyMemberInitializer())
   4147         D << 0 << Init->getAnyMember()->getDeclName();
   4148       else
   4149         D << 1 << Init->getTypeSourceInfo()->getType();
   4150 
   4151       // Move back to the initializer's location in the ideal list.
   4152       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
   4153         if (InitKey == IdealInitKeys[IdealIndex])
   4154           break;
   4155 
   4156       assert(IdealIndex < NumIdealInits &&
   4157              "initializer not found in initializer list");
   4158     }
   4159 
   4160     PrevInit = Init;
   4161   }
   4162 }
   4163 
   4164 namespace {
   4165 bool CheckRedundantInit(Sema &S,
   4166                         CXXCtorInitializer *Init,
   4167                         CXXCtorInitializer *&PrevInit) {
   4168   if (!PrevInit) {
   4169     PrevInit = Init;
   4170     return false;
   4171   }
   4172 
   4173   if (FieldDecl *Field = Init->getAnyMember())
   4174     S.Diag(Init->getSourceLocation(),
   4175            diag::err_multiple_mem_initialization)
   4176       << Field->getDeclName()
   4177       << Init->getSourceRange();
   4178   else {
   4179     const Type *BaseClass = Init->getBaseClass();
   4180     assert(BaseClass && "neither field nor base");
   4181     S.Diag(Init->getSourceLocation(),
   4182            diag::err_multiple_base_initialization)
   4183       << QualType(BaseClass, 0)
   4184       << Init->getSourceRange();
   4185   }
   4186   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
   4187     << 0 << PrevInit->getSourceRange();
   4188 
   4189   return true;
   4190 }
   4191 
   4192 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
   4193 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
   4194 
   4195 bool CheckRedundantUnionInit(Sema &S,
   4196                              CXXCtorInitializer *Init,
   4197                              RedundantUnionMap &Unions) {
   4198   FieldDecl *Field = Init->getAnyMember();
   4199   RecordDecl *Parent = Field->getParent();
   4200   NamedDecl *Child = Field;
   4201 
   4202   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
   4203     if (Parent->isUnion()) {
   4204       UnionEntry &En = Unions[Parent];
   4205       if (En.first && En.first != Child) {
   4206         S.Diag(Init->getSourceLocation(),
   4207                diag::err_multiple_mem_union_initialization)
   4208           << Field->getDeclName()
   4209           << Init->getSourceRange();
   4210         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
   4211           << 0 << En.second->getSourceRange();
   4212         return true;
   4213       }
   4214       if (!En.first) {
   4215         En.first = Child;
   4216         En.second = Init;
   4217       }
   4218       if (!Parent->isAnonymousStructOrUnion())
   4219         return false;
   4220     }
   4221 
   4222     Child = Parent;
   4223     Parent = cast<RecordDecl>(Parent->getDeclContext());
   4224   }
   4225 
   4226   return false;
   4227 }
   4228 }
   4229 
   4230 /// ActOnMemInitializers - Handle the member initializers for a constructor.
   4231 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
   4232                                 SourceLocation ColonLoc,
   4233                                 ArrayRef<CXXCtorInitializer*> MemInits,
   4234                                 bool AnyErrors) {
   4235   if (!ConstructorDecl)
   4236     return;
   4237 
   4238   AdjustDeclIfTemplate(ConstructorDecl);
   4239 
   4240   CXXConstructorDecl *Constructor
   4241     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
   4242 
   4243   if (!Constructor) {
   4244     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
   4245     return;
   4246   }
   4247 
   4248   // Mapping for the duplicate initializers check.
   4249   // For member initializers, this is keyed with a FieldDecl*.
   4250   // For base initializers, this is keyed with a Type*.
   4251   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
   4252 
   4253   // Mapping for the inconsistent anonymous-union initializers check.
   4254   RedundantUnionMap MemberUnions;
   4255 
   4256   bool HadError = false;
   4257   for (unsigned i = 0; i < MemInits.size(); i++) {
   4258     CXXCtorInitializer *Init = MemInits[i];
   4259 
   4260     // Set the source order index.
   4261     Init->setSourceOrder(i);
   4262 
   4263     if (Init->isAnyMemberInitializer()) {
   4264       const void *Key = GetKeyForMember(Context, Init);
   4265       if (CheckRedundantInit(*this, Init, Members[Key]) ||
   4266           CheckRedundantUnionInit(*this, Init, MemberUnions))
   4267         HadError = true;
   4268     } else if (Init->isBaseInitializer()) {
   4269       const void *Key = GetKeyForMember(Context, Init);
   4270       if (CheckRedundantInit(*this, Init, Members[Key]))
   4271         HadError = true;
   4272     } else {
   4273       assert(Init->isDelegatingInitializer());
   4274       // This must be the only initializer
   4275       if (MemInits.size() != 1) {
   4276         Diag(Init->getSourceLocation(),
   4277              diag::err_delegating_initializer_alone)
   4278           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
   4279         // We will treat this as being the only initializer.
   4280       }
   4281       SetDelegatingInitializer(Constructor, MemInits[i]);
   4282       // Return immediately as the initializer is set.
   4283       return;
   4284     }
   4285   }
   4286 
   4287   if (HadError)
   4288     return;
   4289 
   4290   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
   4291 
   4292   SetCtorInitializers(Constructor, AnyErrors, MemInits);
   4293 
   4294   DiagnoseUninitializedFields(*this, Constructor);
   4295 }
   4296 
   4297 void
   4298 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
   4299                                              CXXRecordDecl *ClassDecl) {
   4300   // Ignore dependent contexts. Also ignore unions, since their members never
   4301   // have destructors implicitly called.
   4302   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
   4303     return;
   4304 
   4305   // FIXME: all the access-control diagnostics are positioned on the
   4306   // field/base declaration.  That's probably good; that said, the
   4307   // user might reasonably want to know why the destructor is being
   4308   // emitted, and we currently don't say.
   4309 
   4310   // Non-static data members.
   4311   for (auto *Field : ClassDecl->fields()) {
   4312     if (Field->isInvalidDecl())
   4313       continue;
   4314 
   4315     // Don't destroy incomplete or zero-length arrays.
   4316     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
   4317       continue;
   4318 
   4319     QualType FieldType = Context.getBaseElementType(Field->getType());
   4320 
   4321     const RecordType* RT = FieldType->getAs<RecordType>();
   4322     if (!RT)
   4323       continue;
   4324 
   4325     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
   4326     if (FieldClassDecl->isInvalidDecl())
   4327       continue;
   4328     if (FieldClassDecl->hasIrrelevantDestructor())
   4329       continue;
   4330     // The destructor for an implicit anonymous union member is never invoked.
   4331     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
   4332       continue;
   4333 
   4334     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
   4335     assert(Dtor && "No dtor found for FieldClassDecl!");
   4336     CheckDestructorAccess(Field->getLocation(), Dtor,
   4337                           PDiag(diag::err_access_dtor_field)
   4338                             << Field->getDeclName()
   4339                             << FieldType);
   4340 
   4341     MarkFunctionReferenced(Location, Dtor);
   4342     DiagnoseUseOfDecl(Dtor, Location);
   4343   }
   4344 
   4345   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
   4346 
   4347   // Bases.
   4348   for (const auto &Base : ClassDecl->bases()) {
   4349     // Bases are always records in a well-formed non-dependent class.
   4350     const RecordType *RT = Base.getType()->getAs<RecordType>();
   4351 
   4352     // Remember direct virtual bases.
   4353     if (Base.isVirtual())
   4354       DirectVirtualBases.insert(RT);
   4355 
   4356     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
   4357     // If our base class is invalid, we probably can't get its dtor anyway.
   4358     if (BaseClassDecl->isInvalidDecl())
   4359       continue;
   4360     if (BaseClassDecl->hasIrrelevantDestructor())
   4361       continue;
   4362 
   4363     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
   4364     assert(Dtor && "No dtor found for BaseClassDecl!");
   4365 
   4366     // FIXME: caret should be on the start of the class name
   4367     CheckDestructorAccess(Base.getLocStart(), Dtor,
   4368                           PDiag(diag::err_access_dtor_base)
   4369                             << Base.getType()
   4370                             << Base.getSourceRange(),
   4371                           Context.getTypeDeclType(ClassDecl));
   4372 
   4373     MarkFunctionReferenced(Location, Dtor);
   4374     DiagnoseUseOfDecl(Dtor, Location);
   4375   }
   4376 
   4377   // Virtual bases.
   4378   for (const auto &VBase : ClassDecl->vbases()) {
   4379     // Bases are always records in a well-formed non-dependent class.
   4380     const RecordType *RT = VBase.getType()->castAs<RecordType>();
   4381 
   4382     // Ignore direct virtual bases.
   4383     if (DirectVirtualBases.count(RT))
   4384       continue;
   4385 
   4386     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
   4387     // If our base class is invalid, we probably can't get its dtor anyway.
   4388     if (BaseClassDecl->isInvalidDecl())
   4389       continue;
   4390     if (BaseClassDecl->hasIrrelevantDestructor())
   4391       continue;
   4392 
   4393     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
   4394     assert(Dtor && "No dtor found for BaseClassDecl!");
   4395     if (CheckDestructorAccess(
   4396             ClassDecl->getLocation(), Dtor,
   4397             PDiag(diag::err_access_dtor_vbase)
   4398                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
   4399             Context.getTypeDeclType(ClassDecl)) ==
   4400         AR_accessible) {
   4401       CheckDerivedToBaseConversion(
   4402           Context.getTypeDeclType(ClassDecl), VBase.getType(),
   4403           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
   4404           SourceRange(), DeclarationName(), nullptr);
   4405     }
   4406 
   4407     MarkFunctionReferenced(Location, Dtor);
   4408     DiagnoseUseOfDecl(Dtor, Location);
   4409   }
   4410 }
   4411 
   4412 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
   4413   if (!CDtorDecl)
   4414     return;
   4415 
   4416   if (CXXConstructorDecl *Constructor
   4417       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
   4418     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
   4419     DiagnoseUninitializedFields(*this, Constructor);
   4420   }
   4421 }
   4422 
   4423 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
   4424   if (!getLangOpts().CPlusPlus)
   4425     return false;
   4426 
   4427   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
   4428   if (!RD)
   4429     return false;
   4430 
   4431   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
   4432   // class template specialization here, but doing so breaks a lot of code.
   4433 
   4434   // We can't answer whether something is abstract until it has a
   4435   // definition. If it's currently being defined, we'll walk back
   4436   // over all the declarations when we have a full definition.
   4437   const CXXRecordDecl *Def = RD->getDefinition();
   4438   if (!Def || Def->isBeingDefined())
   4439     return false;
   4440 
   4441   return RD->isAbstract();
   4442 }
   4443 
   4444 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
   4445                                   TypeDiagnoser &Diagnoser) {
   4446   if (!isAbstractType(Loc, T))
   4447     return false;
   4448 
   4449   T = Context.getBaseElementType(T);
   4450   Diagnoser.diagnose(*this, Loc, T);
   4451   DiagnoseAbstractType(T->getAsCXXRecordDecl());
   4452   return true;
   4453 }
   4454 
   4455 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
   4456   // Check if we've already emitted the list of pure virtual functions
   4457   // for this class.
   4458   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
   4459     return;
   4460 
   4461   // If the diagnostic is suppressed, don't emit the notes. We're only
   4462   // going to emit them once, so try to attach them to a diagnostic we're
   4463   // actually going to show.
   4464   if (Diags.isLastDiagnosticIgnored())
   4465     return;
   4466 
   4467   CXXFinalOverriderMap FinalOverriders;
   4468   RD->getFinalOverriders(FinalOverriders);
   4469 
   4470   // Keep a set of seen pure methods so we won't diagnose the same method
   4471   // more than once.
   4472   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
   4473 
   4474   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
   4475                                    MEnd = FinalOverriders.end();
   4476        M != MEnd;
   4477        ++M) {
   4478     for (OverridingMethods::iterator SO = M->second.begin(),
   4479                                   SOEnd = M->second.end();
   4480          SO != SOEnd; ++SO) {
   4481       // C++ [class.abstract]p4:
   4482       //   A class is abstract if it contains or inherits at least one
   4483       //   pure virtual function for which the final overrider is pure
   4484       //   virtual.
   4485 
   4486       //
   4487       if (SO->second.size() != 1)
   4488         continue;
   4489 
   4490       if (!SO->second.front().Method->isPure())
   4491         continue;
   4492 
   4493       if (!SeenPureMethods.insert(SO->second.front().Method).second)
   4494         continue;
   4495 
   4496       Diag(SO->second.front().Method->getLocation(),
   4497            diag::note_pure_virtual_function)
   4498         << SO->second.front().Method->getDeclName() << RD->getDeclName();
   4499     }
   4500   }
   4501 
   4502   if (!PureVirtualClassDiagSet)
   4503     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
   4504   PureVirtualClassDiagSet->insert(RD);
   4505 }
   4506 
   4507 namespace {
   4508 struct AbstractUsageInfo {
   4509   Sema &S;
   4510   CXXRecordDecl *Record;
   4511   CanQualType AbstractType;
   4512   bool Invalid;
   4513 
   4514   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
   4515     : S(S), Record(Record),
   4516       AbstractType(S.Context.getCanonicalType(
   4517                    S.Context.getTypeDeclType(Record))),
   4518       Invalid(false) {}
   4519 
   4520   void DiagnoseAbstractType() {
   4521     if (Invalid) return;
   4522     S.DiagnoseAbstractType(Record);
   4523     Invalid = true;
   4524   }
   4525 
   4526   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
   4527 };
   4528 
   4529 struct CheckAbstractUsage {
   4530   AbstractUsageInfo &Info;
   4531   const NamedDecl *Ctx;
   4532 
   4533   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
   4534     : Info(Info), Ctx(Ctx) {}
   4535 
   4536   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
   4537     switch (TL.getTypeLocClass()) {
   4538 #define ABSTRACT_TYPELOC(CLASS, PARENT)
   4539 #define TYPELOC(CLASS, PARENT) \
   4540     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
   4541 #include "clang/AST/TypeLocNodes.def"
   4542     }
   4543   }
   4544 
   4545   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
   4546     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
   4547     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
   4548       if (!TL.getParam(I))
   4549         continue;
   4550 
   4551       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
   4552       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
   4553     }
   4554   }
   4555 
   4556   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
   4557     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
   4558   }
   4559 
   4560   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
   4561     // Visit the type parameters from a permissive context.
   4562     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
   4563       TemplateArgumentLoc TAL = TL.getArgLoc(I);
   4564       if (TAL.getArgument().getKind() == TemplateArgument::Type)
   4565         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
   4566           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
   4567       // TODO: other template argument types?
   4568     }
   4569   }
   4570 
   4571   // Visit pointee types from a permissive context.
   4572 #define CheckPolymorphic(Type) \
   4573   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
   4574     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
   4575   }
   4576   CheckPolymorphic(PointerTypeLoc)
   4577   CheckPolymorphic(ReferenceTypeLoc)
   4578   CheckPolymorphic(MemberPointerTypeLoc)
   4579   CheckPolymorphic(BlockPointerTypeLoc)
   4580   CheckPolymorphic(AtomicTypeLoc)
   4581 
   4582   /// Handle all the types we haven't given a more specific
   4583   /// implementation for above.
   4584   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
   4585     // Every other kind of type that we haven't called out already
   4586     // that has an inner type is either (1) sugar or (2) contains that
   4587     // inner type in some way as a subobject.
   4588     if (TypeLoc Next = TL.getNextTypeLoc())
   4589       return Visit(Next, Sel);
   4590 
   4591     // If there's no inner type and we're in a permissive context,
   4592     // don't diagnose.
   4593     if (Sel == Sema::AbstractNone) return;
   4594 
   4595     // Check whether the type matches the abstract type.
   4596     QualType T = TL.getType();
   4597     if (T->isArrayType()) {
   4598       Sel = Sema::AbstractArrayType;
   4599       T = Info.S.Context.getBaseElementType(T);
   4600     }
   4601     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
   4602     if (CT != Info.AbstractType) return;
   4603 
   4604     // It matched; do some magic.
   4605     if (Sel == Sema::AbstractArrayType) {
   4606       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
   4607         << T << TL.getSourceRange();
   4608     } else {
   4609       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
   4610         << Sel << T << TL.getSourceRange();
   4611     }
   4612     Info.DiagnoseAbstractType();
   4613   }
   4614 };
   4615 
   4616 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
   4617                                   Sema::AbstractDiagSelID Sel) {
   4618   CheckAbstractUsage(*this, D).Visit(TL, Sel);
   4619 }
   4620 
   4621 }
   4622 
   4623 /// Check for invalid uses of an abstract type in a method declaration.
   4624 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
   4625                                     CXXMethodDecl *MD) {
   4626   // No need to do the check on definitions, which require that
   4627   // the return/param types be complete.
   4628   if (MD->doesThisDeclarationHaveABody())
   4629     return;
   4630 
   4631   // For safety's sake, just ignore it if we don't have type source
   4632   // information.  This should never happen for non-implicit methods,
   4633   // but...
   4634   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
   4635     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
   4636 }
   4637 
   4638 /// Check for invalid uses of an abstract type within a class definition.
   4639 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
   4640                                     CXXRecordDecl *RD) {
   4641   for (auto *D : RD->decls()) {
   4642     if (D->isImplicit()) continue;
   4643 
   4644     // Methods and method templates.
   4645     if (isa<CXXMethodDecl>(D)) {
   4646       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
   4647     } else if (isa<FunctionTemplateDecl>(D)) {
   4648       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
   4649       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
   4650 
   4651     // Fields and static variables.
   4652     } else if (isa<FieldDecl>(D)) {
   4653       FieldDecl *FD = cast<FieldDecl>(D);
   4654       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
   4655         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
   4656     } else if (isa<VarDecl>(D)) {
   4657       VarDecl *VD = cast<VarDecl>(D);
   4658       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
   4659         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
   4660 
   4661     // Nested classes and class templates.
   4662     } else if (isa<CXXRecordDecl>(D)) {
   4663       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
   4664     } else if (isa<ClassTemplateDecl>(D)) {
   4665       CheckAbstractClassUsage(Info,
   4666                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
   4667     }
   4668   }
   4669 }
   4670 
   4671 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
   4672   Attr *ClassAttr = getDLLAttr(Class);
   4673   if (!ClassAttr)
   4674     return;
   4675 
   4676   assert(ClassAttr->getKind() == attr::DLLExport);
   4677 
   4678   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
   4679 
   4680   if (TSK == TSK_ExplicitInstantiationDeclaration)
   4681     // Don't go any further if this is just an explicit instantiation
   4682     // declaration.
   4683     return;
   4684 
   4685   for (Decl *Member : Class->decls()) {
   4686     auto *MD = dyn_cast<CXXMethodDecl>(Member);
   4687     if (!MD)
   4688       continue;
   4689 
   4690     if (Member->getAttr<DLLExportAttr>()) {
   4691       if (MD->isUserProvided()) {
   4692         // Instantiate non-default class member functions ...
   4693 
   4694         // .. except for certain kinds of template specializations.
   4695         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
   4696           continue;
   4697 
   4698         S.MarkFunctionReferenced(Class->getLocation(), MD);
   4699 
   4700         // The function will be passed to the consumer when its definition is
   4701         // encountered.
   4702       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
   4703                  MD->isCopyAssignmentOperator() ||
   4704                  MD->isMoveAssignmentOperator()) {
   4705         // Synthesize and instantiate non-trivial implicit methods, explicitly
   4706         // defaulted methods, and the copy and move assignment operators. The
   4707         // latter are exported even if they are trivial, because the address of
   4708         // an operator can be taken and should compare equal accross libraries.
   4709         DiagnosticErrorTrap Trap(S.Diags);
   4710         S.MarkFunctionReferenced(Class->getLocation(), MD);
   4711         if (Trap.hasErrorOccurred()) {
   4712           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
   4713               << Class->getName() << !S.getLangOpts().CPlusPlus11;
   4714           break;
   4715         }
   4716 
   4717         // There is no later point when we will see the definition of this
   4718         // function, so pass it to the consumer now.
   4719         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
   4720       }
   4721     }
   4722   }
   4723 }
   4724 
   4725 /// \brief Check class-level dllimport/dllexport attribute.
   4726 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
   4727   Attr *ClassAttr = getDLLAttr(Class);
   4728 
   4729   // MSVC inherits DLL attributes to partial class template specializations.
   4730   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
   4731     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
   4732       if (Attr *TemplateAttr =
   4733               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
   4734         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
   4735         A->setInherited(true);
   4736         ClassAttr = A;
   4737       }
   4738     }
   4739   }
   4740 
   4741   if (!ClassAttr)
   4742     return;
   4743 
   4744   if (!Class->isExternallyVisible()) {
   4745     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
   4746         << Class << ClassAttr;
   4747     return;
   4748   }
   4749 
   4750   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   4751       !ClassAttr->isInherited()) {
   4752     // Diagnose dll attributes on members of class with dll attribute.
   4753     for (Decl *Member : Class->decls()) {
   4754       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
   4755         continue;
   4756       InheritableAttr *MemberAttr = getDLLAttr(Member);
   4757       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
   4758         continue;
   4759 
   4760       Diag(MemberAttr->getLocation(),
   4761              diag::err_attribute_dll_member_of_dll_class)
   4762           << MemberAttr << ClassAttr;
   4763       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
   4764       Member->setInvalidDecl();
   4765     }
   4766   }
   4767 
   4768   if (Class->getDescribedClassTemplate())
   4769     // Don't inherit dll attribute until the template is instantiated.
   4770     return;
   4771 
   4772   // The class is either imported or exported.
   4773   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
   4774   const bool ClassImported = !ClassExported;
   4775 
   4776   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
   4777 
   4778   // Ignore explicit dllexport on explicit class template instantiation declarations.
   4779   if (ClassExported && !ClassAttr->isInherited() &&
   4780       TSK == TSK_ExplicitInstantiationDeclaration) {
   4781     Class->dropAttr<DLLExportAttr>();
   4782     return;
   4783   }
   4784 
   4785   // Force declaration of implicit members so they can inherit the attribute.
   4786   ForceDeclarationOfImplicitMembers(Class);
   4787 
   4788   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
   4789   // seem to be true in practice?
   4790 
   4791   for (Decl *Member : Class->decls()) {
   4792     VarDecl *VD = dyn_cast<VarDecl>(Member);
   4793     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
   4794 
   4795     // Only methods and static fields inherit the attributes.
   4796     if (!VD && !MD)
   4797       continue;
   4798 
   4799     if (MD) {
   4800       // Don't process deleted methods.
   4801       if (MD->isDeleted())
   4802         continue;
   4803 
   4804       if (MD->isInlined()) {
   4805         // MinGW does not import or export inline methods.
   4806         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
   4807           continue;
   4808 
   4809         // MSVC versions before 2015 don't export the move assignment operators,
   4810         // so don't attempt to import them if we have a definition.
   4811         if (ClassImported && MD->isMoveAssignmentOperator() &&
   4812             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
   4813           continue;
   4814       }
   4815     }
   4816 
   4817     if (!cast<NamedDecl>(Member)->isExternallyVisible())
   4818       continue;
   4819 
   4820     if (!getDLLAttr(Member)) {
   4821       auto *NewAttr =
   4822           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
   4823       NewAttr->setInherited(true);
   4824       Member->addAttr(NewAttr);
   4825     }
   4826   }
   4827 
   4828   if (ClassExported)
   4829     DelayedDllExportClasses.push_back(Class);
   4830 }
   4831 
   4832 /// \brief Perform propagation of DLL attributes from a derived class to a
   4833 /// templated base class for MS compatibility.
   4834 void Sema::propagateDLLAttrToBaseClassTemplate(
   4835     CXXRecordDecl *Class, Attr *ClassAttr,
   4836     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
   4837   if (getDLLAttr(
   4838           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
   4839     // If the base class template has a DLL attribute, don't try to change it.
   4840     return;
   4841   }
   4842 
   4843   auto TSK = BaseTemplateSpec->getSpecializationKind();
   4844   if (!getDLLAttr(BaseTemplateSpec) &&
   4845       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
   4846        TSK == TSK_ImplicitInstantiation)) {
   4847     // The template hasn't been instantiated yet (or it has, but only as an
   4848     // explicit instantiation declaration or implicit instantiation, which means
   4849     // we haven't codegenned any members yet), so propagate the attribute.
   4850     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
   4851     NewAttr->setInherited(true);
   4852     BaseTemplateSpec->addAttr(NewAttr);
   4853 
   4854     // If the template is already instantiated, checkDLLAttributeRedeclaration()
   4855     // needs to be run again to work see the new attribute. Otherwise this will
   4856     // get run whenever the template is instantiated.
   4857     if (TSK != TSK_Undeclared)
   4858       checkClassLevelDLLAttribute(BaseTemplateSpec);
   4859 
   4860     return;
   4861   }
   4862 
   4863   if (getDLLAttr(BaseTemplateSpec)) {
   4864     // The template has already been specialized or instantiated with an
   4865     // attribute, explicitly or through propagation. We should not try to change
   4866     // it.
   4867     return;
   4868   }
   4869 
   4870   // The template was previously instantiated or explicitly specialized without
   4871   // a dll attribute, It's too late for us to add an attribute, so warn that
   4872   // this is unsupported.
   4873   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
   4874       << BaseTemplateSpec->isExplicitSpecialization();
   4875   Diag(ClassAttr->getLocation(), diag::note_attribute);
   4876   if (BaseTemplateSpec->isExplicitSpecialization()) {
   4877     Diag(BaseTemplateSpec->getLocation(),
   4878            diag::note_template_class_explicit_specialization_was_here)
   4879         << BaseTemplateSpec;
   4880   } else {
   4881     Diag(BaseTemplateSpec->getPointOfInstantiation(),
   4882            diag::note_template_class_instantiation_was_here)
   4883         << BaseTemplateSpec;
   4884   }
   4885 }
   4886 
   4887 /// \brief Perform semantic checks on a class definition that has been
   4888 /// completing, introducing implicitly-declared members, checking for
   4889 /// abstract types, etc.
   4890 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
   4891   if (!Record)
   4892     return;
   4893 
   4894   if (Record->isAbstract() && !Record->isInvalidDecl()) {
   4895     AbstractUsageInfo Info(*this, Record);
   4896     CheckAbstractClassUsage(Info, Record);
   4897   }
   4898 
   4899   // If this is not an aggregate type and has no user-declared constructor,
   4900   // complain about any non-static data members of reference or const scalar
   4901   // type, since they will never get initializers.
   4902   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
   4903       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
   4904       !Record->isLambda()) {
   4905     bool Complained = false;
   4906     for (const auto *F : Record->fields()) {
   4907       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
   4908         continue;
   4909 
   4910       if (F->getType()->isReferenceType() ||
   4911           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
   4912         if (!Complained) {
   4913           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
   4914             << Record->getTagKind() << Record;
   4915           Complained = true;
   4916         }
   4917 
   4918         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
   4919           << F->getType()->isReferenceType()
   4920           << F->getDeclName();
   4921       }
   4922     }
   4923   }
   4924 
   4925   if (Record->getIdentifier()) {
   4926     // C++ [class.mem]p13:
   4927     //   If T is the name of a class, then each of the following shall have a
   4928     //   name different from T:
   4929     //     - every member of every anonymous union that is a member of class T.
   4930     //
   4931     // C++ [class.mem]p14:
   4932     //   In addition, if class T has a user-declared constructor (12.1), every
   4933     //   non-static data member of class T shall have a name different from T.
   4934     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
   4935     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
   4936          ++I) {
   4937       NamedDecl *D = *I;
   4938       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
   4939           isa<IndirectFieldDecl>(D)) {
   4940         Diag(D->getLocation(), diag::err_member_name_of_class)
   4941           << D->getDeclName();
   4942         break;
   4943       }
   4944     }
   4945   }
   4946 
   4947   // Warn if the class has virtual methods but non-virtual public destructor.
   4948   if (Record->isPolymorphic() && !Record->isDependentType()) {
   4949     CXXDestructorDecl *dtor = Record->getDestructor();
   4950     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
   4951         !Record->hasAttr<FinalAttr>())
   4952       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
   4953            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
   4954   }
   4955 
   4956   if (Record->isAbstract()) {
   4957     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
   4958       Diag(Record->getLocation(), diag::warn_abstract_final_class)
   4959         << FA->isSpelledAsSealed();
   4960       DiagnoseAbstractType(Record);
   4961     }
   4962   }
   4963 
   4964   bool HasMethodWithOverrideControl = false,
   4965        HasOverridingMethodWithoutOverrideControl = false;
   4966   if (!Record->isDependentType()) {
   4967     for (auto *M : Record->methods()) {
   4968       // See if a method overloads virtual methods in a base
   4969       // class without overriding any.
   4970       if (!M->isStatic())
   4971         DiagnoseHiddenVirtualMethods(M);
   4972       if (M->hasAttr<OverrideAttr>())
   4973         HasMethodWithOverrideControl = true;
   4974       else if (M->size_overridden_methods() > 0)
   4975         HasOverridingMethodWithoutOverrideControl = true;
   4976       // Check whether the explicitly-defaulted special members are valid.
   4977       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
   4978         CheckExplicitlyDefaultedSpecialMember(M);
   4979 
   4980       // For an explicitly defaulted or deleted special member, we defer
   4981       // determining triviality until the class is complete. That time is now!
   4982       if (!M->isImplicit() && !M->isUserProvided()) {
   4983         CXXSpecialMember CSM = getSpecialMember(M);
   4984         if (CSM != CXXInvalid) {
   4985           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
   4986 
   4987           // Inform the class that we've finished declaring this member.
   4988           Record->finishedDefaultedOrDeletedMember(M);
   4989         }
   4990       }
   4991     }
   4992   }
   4993 
   4994   if (HasMethodWithOverrideControl &&
   4995       HasOverridingMethodWithoutOverrideControl) {
   4996     // At least one method has the 'override' control declared.
   4997     // Diagnose all other overridden methods which do not have 'override' specified on them.
   4998     for (auto *M : Record->methods())
   4999       DiagnoseAbsenceOfOverrideControl(M);
   5000   }
   5001 
   5002   // ms_struct is a request to use the same ABI rules as MSVC.  Check
   5003   // whether this class uses any C++ features that are implemented
   5004   // completely differently in MSVC, and if so, emit a diagnostic.
   5005   // That diagnostic defaults to an error, but we allow projects to
   5006   // map it down to a warning (or ignore it).  It's a fairly common
   5007   // practice among users of the ms_struct pragma to mass-annotate
   5008   // headers, sweeping up a bunch of types that the project doesn't
   5009   // really rely on MSVC-compatible layout for.  We must therefore
   5010   // support "ms_struct except for C++ stuff" as a secondary ABI.
   5011   if (Record->isMsStruct(Context) &&
   5012       (Record->isPolymorphic() || Record->getNumBases())) {
   5013     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
   5014   }
   5015 
   5016   // Declare inheriting constructors. We do this eagerly here because:
   5017   // - The standard requires an eager diagnostic for conflicting inheriting
   5018   //   constructors from different classes.
   5019   // - The lazy declaration of the other implicit constructors is so as to not
   5020   //   waste space and performance on classes that are not meant to be
   5021   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
   5022   //   have inheriting constructors.
   5023   DeclareInheritingConstructors(Record);
   5024 
   5025   checkClassLevelDLLAttribute(Record);
   5026 }
   5027 
   5028 /// Look up the special member function that would be called by a special
   5029 /// member function for a subobject of class type.
   5030 ///
   5031 /// \param Class The class type of the subobject.
   5032 /// \param CSM The kind of special member function.
   5033 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
   5034 /// \param ConstRHS True if this is a copy operation with a const object
   5035 ///        on its RHS, that is, if the argument to the outer special member
   5036 ///        function is 'const' and this is not a field marked 'mutable'.
   5037 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
   5038     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
   5039     unsigned FieldQuals, bool ConstRHS) {
   5040   unsigned LHSQuals = 0;
   5041   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
   5042     LHSQuals = FieldQuals;
   5043 
   5044   unsigned RHSQuals = FieldQuals;
   5045   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
   5046     RHSQuals = 0;
   5047   else if (ConstRHS)
   5048     RHSQuals |= Qualifiers::Const;
   5049 
   5050   return S.LookupSpecialMember(Class, CSM,
   5051                                RHSQuals & Qualifiers::Const,
   5052                                RHSQuals & Qualifiers::Volatile,
   5053                                false,
   5054                                LHSQuals & Qualifiers::Const,
   5055                                LHSQuals & Qualifiers::Volatile);
   5056 }
   5057 
   5058 /// Is the special member function which would be selected to perform the
   5059 /// specified operation on the specified class type a constexpr constructor?
   5060 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
   5061                                      Sema::CXXSpecialMember CSM,
   5062                                      unsigned Quals, bool ConstRHS) {
   5063   Sema::SpecialMemberOverloadResult *SMOR =
   5064       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
   5065   if (!SMOR || !SMOR->getMethod())
   5066     // A constructor we wouldn't select can't be "involved in initializing"
   5067     // anything.
   5068     return true;
   5069   return SMOR->getMethod()->isConstexpr();
   5070 }
   5071 
   5072 /// Determine whether the specified special member function would be constexpr
   5073 /// if it were implicitly defined.
   5074 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
   5075                                               Sema::CXXSpecialMember CSM,
   5076                                               bool ConstArg) {
   5077   if (!S.getLangOpts().CPlusPlus11)
   5078     return false;
   5079 
   5080   // C++11 [dcl.constexpr]p4:
   5081   // In the definition of a constexpr constructor [...]
   5082   bool Ctor = true;
   5083   switch (CSM) {
   5084   case Sema::CXXDefaultConstructor:
   5085     // Since default constructor lookup is essentially trivial (and cannot
   5086     // involve, for instance, template instantiation), we compute whether a
   5087     // defaulted default constructor is constexpr directly within CXXRecordDecl.
   5088     //
   5089     // This is important for performance; we need to know whether the default
   5090     // constructor is constexpr to determine whether the type is a literal type.
   5091     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
   5092 
   5093   case Sema::CXXCopyConstructor:
   5094   case Sema::CXXMoveConstructor:
   5095     // For copy or move constructors, we need to perform overload resolution.
   5096     break;
   5097 
   5098   case Sema::CXXCopyAssignment:
   5099   case Sema::CXXMoveAssignment:
   5100     if (!S.getLangOpts().CPlusPlus14)
   5101       return false;
   5102     // In C++1y, we need to perform overload resolution.
   5103     Ctor = false;
   5104     break;
   5105 
   5106   case Sema::CXXDestructor:
   5107   case Sema::CXXInvalid:
   5108     return false;
   5109   }
   5110 
   5111   //   -- if the class is a non-empty union, or for each non-empty anonymous
   5112   //      union member of a non-union class, exactly one non-static data member
   5113   //      shall be initialized; [DR1359]
   5114   //
   5115   // If we squint, this is guaranteed, since exactly one non-static data member
   5116   // will be initialized (if the constructor isn't deleted), we just don't know
   5117   // which one.
   5118   if (Ctor && ClassDecl->isUnion())
   5119     return true;
   5120 
   5121   //   -- the class shall not have any virtual base classes;
   5122   if (Ctor && ClassDecl->getNumVBases())
   5123     return false;
   5124 
   5125   // C++1y [class.copy]p26:
   5126   //   -- [the class] is a literal type, and
   5127   if (!Ctor && !ClassDecl->isLiteral())
   5128     return false;
   5129 
   5130   //   -- every constructor involved in initializing [...] base class
   5131   //      sub-objects shall be a constexpr constructor;
   5132   //   -- the assignment operator selected to copy/move each direct base
   5133   //      class is a constexpr function, and
   5134   for (const auto &B : ClassDecl->bases()) {
   5135     const RecordType *BaseType = B.getType()->getAs<RecordType>();
   5136     if (!BaseType) continue;
   5137 
   5138     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   5139     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
   5140       return false;
   5141   }
   5142 
   5143   //   -- every constructor involved in initializing non-static data members
   5144   //      [...] shall be a constexpr constructor;
   5145   //   -- every non-static data member and base class sub-object shall be
   5146   //      initialized
   5147   //   -- for each non-static data member of X that is of class type (or array
   5148   //      thereof), the assignment operator selected to copy/move that member is
   5149   //      a constexpr function
   5150   for (const auto *F : ClassDecl->fields()) {
   5151     if (F->isInvalidDecl())
   5152       continue;
   5153     QualType BaseType = S.Context.getBaseElementType(F->getType());
   5154     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
   5155       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
   5156       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
   5157                                     BaseType.getCVRQualifiers(),
   5158                                     ConstArg && !F->isMutable()))
   5159         return false;
   5160     }
   5161   }
   5162 
   5163   // All OK, it's constexpr!
   5164   return true;
   5165 }
   5166 
   5167 static Sema::ImplicitExceptionSpecification
   5168 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
   5169   switch (S.getSpecialMember(MD)) {
   5170   case Sema::CXXDefaultConstructor:
   5171     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
   5172   case Sema::CXXCopyConstructor:
   5173     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
   5174   case Sema::CXXCopyAssignment:
   5175     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
   5176   case Sema::CXXMoveConstructor:
   5177     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
   5178   case Sema::CXXMoveAssignment:
   5179     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
   5180   case Sema::CXXDestructor:
   5181     return S.ComputeDefaultedDtorExceptionSpec(MD);
   5182   case Sema::CXXInvalid:
   5183     break;
   5184   }
   5185   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
   5186          "only special members have implicit exception specs");
   5187   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
   5188 }
   5189 
   5190 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
   5191                                                             CXXMethodDecl *MD) {
   5192   FunctionProtoType::ExtProtoInfo EPI;
   5193 
   5194   // Build an exception specification pointing back at this member.
   5195   EPI.ExceptionSpec.Type = EST_Unevaluated;
   5196   EPI.ExceptionSpec.SourceDecl = MD;
   5197 
   5198   // Set the calling convention to the default for C++ instance methods.
   5199   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
   5200       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
   5201                                             /*IsCXXMethod=*/true));
   5202   return EPI;
   5203 }
   5204 
   5205 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
   5206   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
   5207   if (FPT->getExceptionSpecType() != EST_Unevaluated)
   5208     return;
   5209 
   5210   // Evaluate the exception specification.
   5211   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
   5212 
   5213   // Update the type of the special member to use it.
   5214   UpdateExceptionSpec(MD, ESI);
   5215 
   5216   // A user-provided destructor can be defined outside the class. When that
   5217   // happens, be sure to update the exception specification on both
   5218   // declarations.
   5219   const FunctionProtoType *CanonicalFPT =
   5220     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
   5221   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
   5222     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
   5223 }
   5224 
   5225 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
   5226   CXXRecordDecl *RD = MD->getParent();
   5227   CXXSpecialMember CSM = getSpecialMember(MD);
   5228 
   5229   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
   5230          "not an explicitly-defaulted special member");
   5231 
   5232   // Whether this was the first-declared instance of the constructor.
   5233   // This affects whether we implicitly add an exception spec and constexpr.
   5234   bool First = MD == MD->getCanonicalDecl();
   5235 
   5236   bool HadError = false;
   5237 
   5238   // C++11 [dcl.fct.def.default]p1:
   5239   //   A function that is explicitly defaulted shall
   5240   //     -- be a special member function (checked elsewhere),
   5241   //     -- have the same type (except for ref-qualifiers, and except that a
   5242   //        copy operation can take a non-const reference) as an implicit
   5243   //        declaration, and
   5244   //     -- not have default arguments.
   5245   unsigned ExpectedParams = 1;
   5246   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
   5247     ExpectedParams = 0;
   5248   if (MD->getNumParams() != ExpectedParams) {
   5249     // This also checks for default arguments: a copy or move constructor with a
   5250     // default argument is classified as a default constructor, and assignment
   5251     // operations and destructors can't have default arguments.
   5252     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
   5253       << CSM << MD->getSourceRange();
   5254     HadError = true;
   5255   } else if (MD->isVariadic()) {
   5256     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
   5257       << CSM << MD->getSourceRange();
   5258     HadError = true;
   5259   }
   5260 
   5261   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
   5262 
   5263   bool CanHaveConstParam = false;
   5264   if (CSM == CXXCopyConstructor)
   5265     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
   5266   else if (CSM == CXXCopyAssignment)
   5267     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
   5268 
   5269   QualType ReturnType = Context.VoidTy;
   5270   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
   5271     // Check for return type matching.
   5272     ReturnType = Type->getReturnType();
   5273     QualType ExpectedReturnType =
   5274         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
   5275     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
   5276       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
   5277         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
   5278       HadError = true;
   5279     }
   5280 
   5281     // A defaulted special member cannot have cv-qualifiers.
   5282     if (Type->getTypeQuals()) {
   5283       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
   5284         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
   5285       HadError = true;
   5286     }
   5287   }
   5288 
   5289   // Check for parameter type matching.
   5290   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
   5291   bool HasConstParam = false;
   5292   if (ExpectedParams && ArgType->isReferenceType()) {
   5293     // Argument must be reference to possibly-const T.
   5294     QualType ReferentType = ArgType->getPointeeType();
   5295     HasConstParam = ReferentType.isConstQualified();
   5296 
   5297     if (ReferentType.isVolatileQualified()) {
   5298       Diag(MD->getLocation(),
   5299            diag::err_defaulted_special_member_volatile_param) << CSM;
   5300       HadError = true;
   5301     }
   5302 
   5303     if (HasConstParam && !CanHaveConstParam) {
   5304       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
   5305         Diag(MD->getLocation(),
   5306              diag::err_defaulted_special_member_copy_const_param)
   5307           << (CSM == CXXCopyAssignment);
   5308         // FIXME: Explain why this special member can't be const.
   5309       } else {
   5310         Diag(MD->getLocation(),
   5311              diag::err_defaulted_special_member_move_const_param)
   5312           << (CSM == CXXMoveAssignment);
   5313       }
   5314       HadError = true;
   5315     }
   5316   } else if (ExpectedParams) {
   5317     // A copy assignment operator can take its argument by value, but a
   5318     // defaulted one cannot.
   5319     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
   5320     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
   5321     HadError = true;
   5322   }
   5323 
   5324   // C++11 [dcl.fct.def.default]p2:
   5325   //   An explicitly-defaulted function may be declared constexpr only if it
   5326   //   would have been implicitly declared as constexpr,
   5327   // Do not apply this rule to members of class templates, since core issue 1358
   5328   // makes such functions always instantiate to constexpr functions. For
   5329   // functions which cannot be constexpr (for non-constructors in C++11 and for
   5330   // destructors in C++1y), this is checked elsewhere.
   5331   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
   5332                                                      HasConstParam);
   5333   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
   5334                                  : isa<CXXConstructorDecl>(MD)) &&
   5335       MD->isConstexpr() && !Constexpr &&
   5336       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
   5337     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
   5338     // FIXME: Explain why the special member can't be constexpr.
   5339     HadError = true;
   5340   }
   5341 
   5342   //   and may have an explicit exception-specification only if it is compatible
   5343   //   with the exception-specification on the implicit declaration.
   5344   if (Type->hasExceptionSpec()) {
   5345     // Delay the check if this is the first declaration of the special member,
   5346     // since we may not have parsed some necessary in-class initializers yet.
   5347     if (First) {
   5348       // If the exception specification needs to be instantiated, do so now,
   5349       // before we clobber it with an EST_Unevaluated specification below.
   5350       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
   5351         InstantiateExceptionSpec(MD->getLocStart(), MD);
   5352         Type = MD->getType()->getAs<FunctionProtoType>();
   5353       }
   5354       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
   5355     } else
   5356       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
   5357   }
   5358 
   5359   //   If a function is explicitly defaulted on its first declaration,
   5360   if (First) {
   5361     //  -- it is implicitly considered to be constexpr if the implicit
   5362     //     definition would be,
   5363     MD->setConstexpr(Constexpr);
   5364 
   5365     //  -- it is implicitly considered to have the same exception-specification
   5366     //     as if it had been implicitly declared,
   5367     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
   5368     EPI.ExceptionSpec.Type = EST_Unevaluated;
   5369     EPI.ExceptionSpec.SourceDecl = MD;
   5370     MD->setType(Context.getFunctionType(ReturnType,
   5371                                         llvm::makeArrayRef(&ArgType,
   5372                                                            ExpectedParams),
   5373                                         EPI));
   5374   }
   5375 
   5376   if (ShouldDeleteSpecialMember(MD, CSM)) {
   5377     if (First) {
   5378       SetDeclDeleted(MD, MD->getLocation());
   5379     } else {
   5380       // C++11 [dcl.fct.def.default]p4:
   5381       //   [For a] user-provided explicitly-defaulted function [...] if such a
   5382       //   function is implicitly defined as deleted, the program is ill-formed.
   5383       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
   5384       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
   5385       HadError = true;
   5386     }
   5387   }
   5388 
   5389   if (HadError)
   5390     MD->setInvalidDecl();
   5391 }
   5392 
   5393 /// Check whether the exception specification provided for an
   5394 /// explicitly-defaulted special member matches the exception specification
   5395 /// that would have been generated for an implicit special member, per
   5396 /// C++11 [dcl.fct.def.default]p2.
   5397 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
   5398     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
   5399   // If the exception specification was explicitly specified but hadn't been
   5400   // parsed when the method was defaulted, grab it now.
   5401   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
   5402     SpecifiedType =
   5403         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
   5404 
   5405   // Compute the implicit exception specification.
   5406   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
   5407                                                        /*IsCXXMethod=*/true);
   5408   FunctionProtoType::ExtProtoInfo EPI(CC);
   5409   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
   5410                           .getExceptionSpec();
   5411   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
   5412     Context.getFunctionType(Context.VoidTy, None, EPI));
   5413 
   5414   // Ensure that it matches.
   5415   CheckEquivalentExceptionSpec(
   5416     PDiag(diag::err_incorrect_defaulted_exception_spec)
   5417       << getSpecialMember(MD), PDiag(),
   5418     ImplicitType, SourceLocation(),
   5419     SpecifiedType, MD->getLocation());
   5420 }
   5421 
   5422 void Sema::CheckDelayedMemberExceptionSpecs() {
   5423   decltype(DelayedExceptionSpecChecks) Checks;
   5424   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
   5425 
   5426   std::swap(Checks, DelayedExceptionSpecChecks);
   5427   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
   5428 
   5429   // Perform any deferred checking of exception specifications for virtual
   5430   // destructors.
   5431   for (auto &Check : Checks)
   5432     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
   5433 
   5434   // Check that any explicitly-defaulted methods have exception specifications
   5435   // compatible with their implicit exception specifications.
   5436   for (auto &Spec : Specs)
   5437     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
   5438 }
   5439 
   5440 namespace {
   5441 struct SpecialMemberDeletionInfo {
   5442   Sema &S;
   5443   CXXMethodDecl *MD;
   5444   Sema::CXXSpecialMember CSM;
   5445   bool Diagnose;
   5446 
   5447   // Properties of the special member, computed for convenience.
   5448   bool IsConstructor, IsAssignment, IsMove, ConstArg;
   5449   SourceLocation Loc;
   5450 
   5451   bool AllFieldsAreConst;
   5452 
   5453   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
   5454                             Sema::CXXSpecialMember CSM, bool Diagnose)
   5455     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
   5456       IsConstructor(false), IsAssignment(false), IsMove(false),
   5457       ConstArg(false), Loc(MD->getLocation()),
   5458       AllFieldsAreConst(true) {
   5459     switch (CSM) {
   5460       case Sema::CXXDefaultConstructor:
   5461       case Sema::CXXCopyConstructor:
   5462         IsConstructor = true;
   5463         break;
   5464       case Sema::CXXMoveConstructor:
   5465         IsConstructor = true;
   5466         IsMove = true;
   5467         break;
   5468       case Sema::CXXCopyAssignment:
   5469         IsAssignment = true;
   5470         break;
   5471       case Sema::CXXMoveAssignment:
   5472         IsAssignment = true;
   5473         IsMove = true;
   5474         break;
   5475       case Sema::CXXDestructor:
   5476         break;
   5477       case Sema::CXXInvalid:
   5478         llvm_unreachable("invalid special member kind");
   5479     }
   5480 
   5481     if (MD->getNumParams()) {
   5482       if (const ReferenceType *RT =
   5483               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
   5484         ConstArg = RT->getPointeeType().isConstQualified();
   5485     }
   5486   }
   5487 
   5488   bool inUnion() const { return MD->getParent()->isUnion(); }
   5489 
   5490   /// Look up the corresponding special member in the given class.
   5491   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
   5492                                               unsigned Quals, bool IsMutable) {
   5493     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
   5494                                        ConstArg && !IsMutable);
   5495   }
   5496 
   5497   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
   5498 
   5499   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
   5500   bool shouldDeleteForField(FieldDecl *FD);
   5501   bool shouldDeleteForAllConstMembers();
   5502 
   5503   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
   5504                                      unsigned Quals);
   5505   bool shouldDeleteForSubobjectCall(Subobject Subobj,
   5506                                     Sema::SpecialMemberOverloadResult *SMOR,
   5507                                     bool IsDtorCallInCtor);
   5508 
   5509   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
   5510 };
   5511 }
   5512 
   5513 /// Is the given special member inaccessible when used on the given
   5514 /// sub-object.
   5515 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
   5516                                              CXXMethodDecl *target) {
   5517   /// If we're operating on a base class, the object type is the
   5518   /// type of this special member.
   5519   QualType objectTy;
   5520   AccessSpecifier access = target->getAccess();
   5521   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
   5522     objectTy = S.Context.getTypeDeclType(MD->getParent());
   5523     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
   5524 
   5525   // If we're operating on a field, the object type is the type of the field.
   5526   } else {
   5527     objectTy = S.Context.getTypeDeclType(target->getParent());
   5528   }
   5529 
   5530   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
   5531 }
   5532 
   5533 /// Check whether we should delete a special member due to the implicit
   5534 /// definition containing a call to a special member of a subobject.
   5535 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
   5536     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
   5537     bool IsDtorCallInCtor) {
   5538   CXXMethodDecl *Decl = SMOR->getMethod();
   5539   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
   5540 
   5541   int DiagKind = -1;
   5542 
   5543   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
   5544     DiagKind = !Decl ? 0 : 1;
   5545   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
   5546     DiagKind = 2;
   5547   else if (!isAccessible(Subobj, Decl))
   5548     DiagKind = 3;
   5549   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
   5550            !Decl->isTrivial()) {
   5551     // A member of a union must have a trivial corresponding special member.
   5552     // As a weird special case, a destructor call from a union's constructor
   5553     // must be accessible and non-deleted, but need not be trivial. Such a
   5554     // destructor is never actually called, but is semantically checked as
   5555     // if it were.
   5556     DiagKind = 4;
   5557   }
   5558 
   5559   if (DiagKind == -1)
   5560     return false;
   5561 
   5562   if (Diagnose) {
   5563     if (Field) {
   5564       S.Diag(Field->getLocation(),
   5565              diag::note_deleted_special_member_class_subobject)
   5566         << CSM << MD->getParent() << /*IsField*/true
   5567         << Field << DiagKind << IsDtorCallInCtor;
   5568     } else {
   5569       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
   5570       S.Diag(Base->getLocStart(),
   5571              diag::note_deleted_special_member_class_subobject)
   5572         << CSM << MD->getParent() << /*IsField*/false
   5573         << Base->getType() << DiagKind << IsDtorCallInCtor;
   5574     }
   5575 
   5576     if (DiagKind == 1)
   5577       S.NoteDeletedFunction(Decl);
   5578     // FIXME: Explain inaccessibility if DiagKind == 3.
   5579   }
   5580 
   5581   return true;
   5582 }
   5583 
   5584 /// Check whether we should delete a special member function due to having a
   5585 /// direct or virtual base class or non-static data member of class type M.
   5586 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
   5587     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
   5588   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
   5589   bool IsMutable = Field && Field->isMutable();
   5590 
   5591   // C++11 [class.ctor]p5:
   5592   // -- any direct or virtual base class, or non-static data member with no
   5593   //    brace-or-equal-initializer, has class type M (or array thereof) and
   5594   //    either M has no default constructor or overload resolution as applied
   5595   //    to M's default constructor results in an ambiguity or in a function
   5596   //    that is deleted or inaccessible
   5597   // C++11 [class.copy]p11, C++11 [class.copy]p23:
   5598   // -- a direct or virtual base class B that cannot be copied/moved because
   5599   //    overload resolution, as applied to B's corresponding special member,
   5600   //    results in an ambiguity or a function that is deleted or inaccessible
   5601   //    from the defaulted special member
   5602   // C++11 [class.dtor]p5:
   5603   // -- any direct or virtual base class [...] has a type with a destructor
   5604   //    that is deleted or inaccessible
   5605   if (!(CSM == Sema::CXXDefaultConstructor &&
   5606         Field && Field->hasInClassInitializer()) &&
   5607       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
   5608                                    false))
   5609     return true;
   5610 
   5611   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
   5612   // -- any direct or virtual base class or non-static data member has a
   5613   //    type with a destructor that is deleted or inaccessible
   5614   if (IsConstructor) {
   5615     Sema::SpecialMemberOverloadResult *SMOR =
   5616         S.LookupSpecialMember(Class, Sema::CXXDestructor,
   5617                               false, false, false, false, false);
   5618     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
   5619       return true;
   5620   }
   5621 
   5622   return false;
   5623 }
   5624 
   5625 /// Check whether we should delete a special member function due to the class
   5626 /// having a particular direct or virtual base class.
   5627 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
   5628   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
   5629   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
   5630 }
   5631 
   5632 /// Check whether we should delete a special member function due to the class
   5633 /// having a particular non-static data member.
   5634 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
   5635   QualType FieldType = S.Context.getBaseElementType(FD->getType());
   5636   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
   5637 
   5638   if (CSM == Sema::CXXDefaultConstructor) {
   5639     // For a default constructor, all references must be initialized in-class
   5640     // and, if a union, it must have a non-const member.
   5641     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
   5642       if (Diagnose)
   5643         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
   5644           << MD->getParent() << FD << FieldType << /*Reference*/0;
   5645       return true;
   5646     }
   5647     // C++11 [class.ctor]p5: any non-variant non-static data member of
   5648     // const-qualified type (or array thereof) with no
   5649     // brace-or-equal-initializer does not have a user-provided default
   5650     // constructor.
   5651     if (!inUnion() && FieldType.isConstQualified() &&
   5652         !FD->hasInClassInitializer() &&
   5653         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
   5654       if (Diagnose)
   5655         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
   5656           << MD->getParent() << FD << FD->getType() << /*Const*/1;
   5657       return true;
   5658     }
   5659 
   5660     if (inUnion() && !FieldType.isConstQualified())
   5661       AllFieldsAreConst = false;
   5662   } else if (CSM == Sema::CXXCopyConstructor) {
   5663     // For a copy constructor, data members must not be of rvalue reference
   5664     // type.
   5665     if (FieldType->isRValueReferenceType()) {
   5666       if (Diagnose)
   5667         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
   5668           << MD->getParent() << FD << FieldType;
   5669       return true;
   5670     }
   5671   } else if (IsAssignment) {
   5672     // For an assignment operator, data members must not be of reference type.
   5673     if (FieldType->isReferenceType()) {
   5674       if (Diagnose)
   5675         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
   5676           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
   5677       return true;
   5678     }
   5679     if (!FieldRecord && FieldType.isConstQualified()) {
   5680       // C++11 [class.copy]p23:
   5681       // -- a non-static data member of const non-class type (or array thereof)
   5682       if (Diagnose)
   5683         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
   5684           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
   5685       return true;
   5686     }
   5687   }
   5688 
   5689   if (FieldRecord) {
   5690     // Some additional restrictions exist on the variant members.
   5691     if (!inUnion() && FieldRecord->isUnion() &&
   5692         FieldRecord->isAnonymousStructOrUnion()) {
   5693       bool AllVariantFieldsAreConst = true;
   5694 
   5695       // FIXME: Handle anonymous unions declared within anonymous unions.
   5696       for (auto *UI : FieldRecord->fields()) {
   5697         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
   5698 
   5699         if (!UnionFieldType.isConstQualified())
   5700           AllVariantFieldsAreConst = false;
   5701 
   5702         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
   5703         if (UnionFieldRecord &&
   5704             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
   5705                                           UnionFieldType.getCVRQualifiers()))
   5706           return true;
   5707       }
   5708 
   5709       // At least one member in each anonymous union must be non-const
   5710       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
   5711           !FieldRecord->field_empty()) {
   5712         if (Diagnose)
   5713           S.Diag(FieldRecord->getLocation(),
   5714                  diag::note_deleted_default_ctor_all_const)
   5715             << MD->getParent() << /*anonymous union*/1;
   5716         return true;
   5717       }
   5718 
   5719       // Don't check the implicit member of the anonymous union type.
   5720       // This is technically non-conformant, but sanity demands it.
   5721       return false;
   5722     }
   5723 
   5724     if (shouldDeleteForClassSubobject(FieldRecord, FD,
   5725                                       FieldType.getCVRQualifiers()))
   5726       return true;
   5727   }
   5728 
   5729   return false;
   5730 }
   5731 
   5732 /// C++11 [class.ctor] p5:
   5733 ///   A defaulted default constructor for a class X is defined as deleted if
   5734 /// X is a union and all of its variant members are of const-qualified type.
   5735 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
   5736   // This is a silly definition, because it gives an empty union a deleted
   5737   // default constructor. Don't do that.
   5738   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
   5739       !MD->getParent()->field_empty()) {
   5740     if (Diagnose)
   5741       S.Diag(MD->getParent()->getLocation(),
   5742              diag::note_deleted_default_ctor_all_const)
   5743         << MD->getParent() << /*not anonymous union*/0;
   5744     return true;
   5745   }
   5746   return false;
   5747 }
   5748 
   5749 /// Determine whether a defaulted special member function should be defined as
   5750 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
   5751 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
   5752 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
   5753                                      bool Diagnose) {
   5754   if (MD->isInvalidDecl())
   5755     return false;
   5756   CXXRecordDecl *RD = MD->getParent();
   5757   assert(!RD->isDependentType() && "do deletion after instantiation");
   5758   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
   5759     return false;
   5760 
   5761   // C++11 [expr.lambda.prim]p19:
   5762   //   The closure type associated with a lambda-expression has a
   5763   //   deleted (8.4.3) default constructor and a deleted copy
   5764   //   assignment operator.
   5765   if (RD->isLambda() &&
   5766       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
   5767     if (Diagnose)
   5768       Diag(RD->getLocation(), diag::note_lambda_decl);
   5769     return true;
   5770   }
   5771 
   5772   // For an anonymous struct or union, the copy and assignment special members
   5773   // will never be used, so skip the check. For an anonymous union declared at
   5774   // namespace scope, the constructor and destructor are used.
   5775   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
   5776       RD->isAnonymousStructOrUnion())
   5777     return false;
   5778 
   5779   // C++11 [class.copy]p7, p18:
   5780   //   If the class definition declares a move constructor or move assignment
   5781   //   operator, an implicitly declared copy constructor or copy assignment
   5782   //   operator is defined as deleted.
   5783   if (MD->isImplicit() &&
   5784       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
   5785     CXXMethodDecl *UserDeclaredMove = nullptr;
   5786 
   5787     // In Microsoft mode, a user-declared move only causes the deletion of the
   5788     // corresponding copy operation, not both copy operations.
   5789     if (RD->hasUserDeclaredMoveConstructor() &&
   5790         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
   5791       if (!Diagnose) return true;
   5792 
   5793       // Find any user-declared move constructor.
   5794       for (auto *I : RD->ctors()) {
   5795         if (I->isMoveConstructor()) {
   5796           UserDeclaredMove = I;
   5797           break;
   5798         }
   5799       }
   5800       assert(UserDeclaredMove);
   5801     } else if (RD->hasUserDeclaredMoveAssignment() &&
   5802                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
   5803       if (!Diagnose) return true;
   5804 
   5805       // Find any user-declared move assignment operator.
   5806       for (auto *I : RD->methods()) {
   5807         if (I->isMoveAssignmentOperator()) {
   5808           UserDeclaredMove = I;
   5809           break;
   5810         }
   5811       }
   5812       assert(UserDeclaredMove);
   5813     }
   5814 
   5815     if (UserDeclaredMove) {
   5816       Diag(UserDeclaredMove->getLocation(),
   5817            diag::note_deleted_copy_user_declared_move)
   5818         << (CSM == CXXCopyAssignment) << RD
   5819         << UserDeclaredMove->isMoveAssignmentOperator();
   5820       return true;
   5821     }
   5822   }
   5823 
   5824   // Do access control from the special member function
   5825   ContextRAII MethodContext(*this, MD);
   5826 
   5827   // C++11 [class.dtor]p5:
   5828   // -- for a virtual destructor, lookup of the non-array deallocation function
   5829   //    results in an ambiguity or in a function that is deleted or inaccessible
   5830   if (CSM == CXXDestructor && MD->isVirtual()) {
   5831     FunctionDecl *OperatorDelete = nullptr;
   5832     DeclarationName Name =
   5833       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
   5834     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
   5835                                  OperatorDelete, false)) {
   5836       if (Diagnose)
   5837         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
   5838       return true;
   5839     }
   5840   }
   5841 
   5842   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
   5843 
   5844   for (auto &BI : RD->bases())
   5845     if (!BI.isVirtual() &&
   5846         SMI.shouldDeleteForBase(&BI))
   5847       return true;
   5848 
   5849   // Per DR1611, do not consider virtual bases of constructors of abstract
   5850   // classes, since we are not going to construct them.
   5851   if (!RD->isAbstract() || !SMI.IsConstructor) {
   5852     for (auto &BI : RD->vbases())
   5853       if (SMI.shouldDeleteForBase(&BI))
   5854         return true;
   5855   }
   5856 
   5857   for (auto *FI : RD->fields())
   5858     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
   5859         SMI.shouldDeleteForField(FI))
   5860       return true;
   5861 
   5862   if (SMI.shouldDeleteForAllConstMembers())
   5863     return true;
   5864 
   5865   if (getLangOpts().CUDA) {
   5866     // We should delete the special member in CUDA mode if target inference
   5867     // failed.
   5868     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
   5869                                                    Diagnose);
   5870   }
   5871 
   5872   return false;
   5873 }
   5874 
   5875 /// Perform lookup for a special member of the specified kind, and determine
   5876 /// whether it is trivial. If the triviality can be determined without the
   5877 /// lookup, skip it. This is intended for use when determining whether a
   5878 /// special member of a containing object is trivial, and thus does not ever
   5879 /// perform overload resolution for default constructors.
   5880 ///
   5881 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
   5882 /// member that was most likely to be intended to be trivial, if any.
   5883 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
   5884                                      Sema::CXXSpecialMember CSM, unsigned Quals,
   5885                                      bool ConstRHS, CXXMethodDecl **Selected) {
   5886   if (Selected)
   5887     *Selected = nullptr;
   5888 
   5889   switch (CSM) {
   5890   case Sema::CXXInvalid:
   5891     llvm_unreachable("not a special member");
   5892 
   5893   case Sema::CXXDefaultConstructor:
   5894     // C++11 [class.ctor]p5:
   5895     //   A default constructor is trivial if:
   5896     //    - all the [direct subobjects] have trivial default constructors
   5897     //
   5898     // Note, no overload resolution is performed in this case.
   5899     if (RD->hasTrivialDefaultConstructor())
   5900       return true;
   5901 
   5902     if (Selected) {
   5903       // If there's a default constructor which could have been trivial, dig it
   5904       // out. Otherwise, if there's any user-provided default constructor, point
   5905       // to that as an example of why there's not a trivial one.
   5906       CXXConstructorDecl *DefCtor = nullptr;
   5907       if (RD->needsImplicitDefaultConstructor())
   5908         S.DeclareImplicitDefaultConstructor(RD);
   5909       for (auto *CI : RD->ctors()) {
   5910         if (!CI->isDefaultConstructor())
   5911           continue;
   5912         DefCtor = CI;
   5913         if (!DefCtor->isUserProvided())
   5914           break;
   5915       }
   5916 
   5917       *Selected = DefCtor;
   5918     }
   5919 
   5920     return false;
   5921 
   5922   case Sema::CXXDestructor:
   5923     // C++11 [class.dtor]p5:
   5924     //   A destructor is trivial if:
   5925     //    - all the direct [subobjects] have trivial destructors
   5926     if (RD->hasTrivialDestructor())
   5927       return true;
   5928 
   5929     if (Selected) {
   5930       if (RD->needsImplicitDestructor())
   5931         S.DeclareImplicitDestructor(RD);
   5932       *Selected = RD->getDestructor();
   5933     }
   5934 
   5935     return false;
   5936 
   5937   case Sema::CXXCopyConstructor:
   5938     // C++11 [class.copy]p12:
   5939     //   A copy constructor is trivial if:
   5940     //    - the constructor selected to copy each direct [subobject] is trivial
   5941     if (RD->hasTrivialCopyConstructor()) {
   5942       if (Quals == Qualifiers::Const)
   5943         // We must either select the trivial copy constructor or reach an
   5944         // ambiguity; no need to actually perform overload resolution.
   5945         return true;
   5946     } else if (!Selected) {
   5947       return false;
   5948     }
   5949     // In C++98, we are not supposed to perform overload resolution here, but we
   5950     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
   5951     // cases like B as having a non-trivial copy constructor:
   5952     //   struct A { template<typename T> A(T&); };
   5953     //   struct B { mutable A a; };
   5954     goto NeedOverloadResolution;
   5955 
   5956   case Sema::CXXCopyAssignment:
   5957     // C++11 [class.copy]p25:
   5958     //   A copy assignment operator is trivial if:
   5959     //    - the assignment operator selected to copy each direct [subobject] is
   5960     //      trivial
   5961     if (RD->hasTrivialCopyAssignment()) {
   5962       if (Quals == Qualifiers::Const)
   5963         return true;
   5964     } else if (!Selected) {
   5965       return false;
   5966     }
   5967     // In C++98, we are not supposed to perform overload resolution here, but we
   5968     // treat that as a language defect.
   5969     goto NeedOverloadResolution;
   5970 
   5971   case Sema::CXXMoveConstructor:
   5972   case Sema::CXXMoveAssignment:
   5973   NeedOverloadResolution:
   5974     Sema::SpecialMemberOverloadResult *SMOR =
   5975         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
   5976 
   5977     // The standard doesn't describe how to behave if the lookup is ambiguous.
   5978     // We treat it as not making the member non-trivial, just like the standard
   5979     // mandates for the default constructor. This should rarely matter, because
   5980     // the member will also be deleted.
   5981     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
   5982       return true;
   5983 
   5984     if (!SMOR->getMethod()) {
   5985       assert(SMOR->getKind() ==
   5986              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
   5987       return false;
   5988     }
   5989 
   5990     // We deliberately don't check if we found a deleted special member. We're
   5991     // not supposed to!
   5992     if (Selected)
   5993       *Selected = SMOR->getMethod();
   5994     return SMOR->getMethod()->isTrivial();
   5995   }
   5996 
   5997   llvm_unreachable("unknown special method kind");
   5998 }
   5999 
   6000 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
   6001   for (auto *CI : RD->ctors())
   6002     if (!CI->isImplicit())
   6003       return CI;
   6004 
   6005   // Look for constructor templates.
   6006   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
   6007   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
   6008     if (CXXConstructorDecl *CD =
   6009           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
   6010       return CD;
   6011   }
   6012 
   6013   return nullptr;
   6014 }
   6015 
   6016 /// The kind of subobject we are checking for triviality. The values of this
   6017 /// enumeration are used in diagnostics.
   6018 enum TrivialSubobjectKind {
   6019   /// The subobject is a base class.
   6020   TSK_BaseClass,
   6021   /// The subobject is a non-static data member.
   6022   TSK_Field,
   6023   /// The object is actually the complete object.
   6024   TSK_CompleteObject
   6025 };
   6026 
   6027 /// Check whether the special member selected for a given type would be trivial.
   6028 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
   6029                                       QualType SubType, bool ConstRHS,
   6030                                       Sema::CXXSpecialMember CSM,
   6031                                       TrivialSubobjectKind Kind,
   6032                                       bool Diagnose) {
   6033   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
   6034   if (!SubRD)
   6035     return true;
   6036 
   6037   CXXMethodDecl *Selected;
   6038   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
   6039                                ConstRHS, Diagnose ? &Selected : nullptr))
   6040     return true;
   6041 
   6042   if (Diagnose) {
   6043     if (ConstRHS)
   6044       SubType.addConst();
   6045 
   6046     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
   6047       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
   6048         << Kind << SubType.getUnqualifiedType();
   6049       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
   6050         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
   6051     } else if (!Selected)
   6052       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
   6053         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
   6054     else if (Selected->isUserProvided()) {
   6055       if (Kind == TSK_CompleteObject)
   6056         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
   6057           << Kind << SubType.getUnqualifiedType() << CSM;
   6058       else {
   6059         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
   6060           << Kind << SubType.getUnqualifiedType() << CSM;
   6061         S.Diag(Selected->getLocation(), diag::note_declared_at);
   6062       }
   6063     } else {
   6064       if (Kind != TSK_CompleteObject)
   6065         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
   6066           << Kind << SubType.getUnqualifiedType() << CSM;
   6067 
   6068       // Explain why the defaulted or deleted special member isn't trivial.
   6069       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
   6070     }
   6071   }
   6072 
   6073   return false;
   6074 }
   6075 
   6076 /// Check whether the members of a class type allow a special member to be
   6077 /// trivial.
   6078 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
   6079                                      Sema::CXXSpecialMember CSM,
   6080                                      bool ConstArg, bool Diagnose) {
   6081   for (const auto *FI : RD->fields()) {
   6082     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
   6083       continue;
   6084 
   6085     QualType FieldType = S.Context.getBaseElementType(FI->getType());
   6086 
   6087     // Pretend anonymous struct or union members are members of this class.
   6088     if (FI->isAnonymousStructOrUnion()) {
   6089       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
   6090                                     CSM, ConstArg, Diagnose))
   6091         return false;
   6092       continue;
   6093     }
   6094 
   6095     // C++11 [class.ctor]p5:
   6096     //   A default constructor is trivial if [...]
   6097     //    -- no non-static data member of its class has a
   6098     //       brace-or-equal-initializer
   6099     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
   6100       if (Diagnose)
   6101         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
   6102       return false;
   6103     }
   6104 
   6105     // Objective C ARC 4.3.5:
   6106     //   [...] nontrivally ownership-qualified types are [...] not trivially
   6107     //   default constructible, copy constructible, move constructible, copy
   6108     //   assignable, move assignable, or destructible [...]
   6109     if (S.getLangOpts().ObjCAutoRefCount &&
   6110         FieldType.hasNonTrivialObjCLifetime()) {
   6111       if (Diagnose)
   6112         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
   6113           << RD << FieldType.getObjCLifetime();
   6114       return false;
   6115     }
   6116 
   6117     bool ConstRHS = ConstArg && !FI->isMutable();
   6118     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
   6119                                    CSM, TSK_Field, Diagnose))
   6120       return false;
   6121   }
   6122 
   6123   return true;
   6124 }
   6125 
   6126 /// Diagnose why the specified class does not have a trivial special member of
   6127 /// the given kind.
   6128 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
   6129   QualType Ty = Context.getRecordType(RD);
   6130 
   6131   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
   6132   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
   6133                             TSK_CompleteObject, /*Diagnose*/true);
   6134 }
   6135 
   6136 /// Determine whether a defaulted or deleted special member function is trivial,
   6137 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
   6138 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
   6139 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
   6140                                   bool Diagnose) {
   6141   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
   6142 
   6143   CXXRecordDecl *RD = MD->getParent();
   6144 
   6145   bool ConstArg = false;
   6146 
   6147   // C++11 [class.copy]p12, p25: [DR1593]
   6148   //   A [special member] is trivial if [...] its parameter-type-list is
   6149   //   equivalent to the parameter-type-list of an implicit declaration [...]
   6150   switch (CSM) {
   6151   case CXXDefaultConstructor:
   6152   case CXXDestructor:
   6153     // Trivial default constructors and destructors cannot have parameters.
   6154     break;
   6155 
   6156   case CXXCopyConstructor:
   6157   case CXXCopyAssignment: {
   6158     // Trivial copy operations always have const, non-volatile parameter types.
   6159     ConstArg = true;
   6160     const ParmVarDecl *Param0 = MD->getParamDecl(0);
   6161     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
   6162     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
   6163       if (Diagnose)
   6164         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
   6165           << Param0->getSourceRange() << Param0->getType()
   6166           << Context.getLValueReferenceType(
   6167                Context.getRecordType(RD).withConst());
   6168       return false;
   6169     }
   6170     break;
   6171   }
   6172 
   6173   case CXXMoveConstructor:
   6174   case CXXMoveAssignment: {
   6175     // Trivial move operations always have non-cv-qualified parameters.
   6176     const ParmVarDecl *Param0 = MD->getParamDecl(0);
   6177     const RValueReferenceType *RT =
   6178       Param0->getType()->getAs<RValueReferenceType>();
   6179     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
   6180       if (Diagnose)
   6181         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
   6182           << Param0->getSourceRange() << Param0->getType()
   6183           << Context.getRValueReferenceType(Context.getRecordType(RD));
   6184       return false;
   6185     }
   6186     break;
   6187   }
   6188 
   6189   case CXXInvalid:
   6190     llvm_unreachable("not a special member");
   6191   }
   6192 
   6193   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
   6194     if (Diagnose)
   6195       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
   6196            diag::note_nontrivial_default_arg)
   6197         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
   6198     return false;
   6199   }
   6200   if (MD->isVariadic()) {
   6201     if (Diagnose)
   6202       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
   6203     return false;
   6204   }
   6205 
   6206   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
   6207   //   A copy/move [constructor or assignment operator] is trivial if
   6208   //    -- the [member] selected to copy/move each direct base class subobject
   6209   //       is trivial
   6210   //
   6211   // C++11 [class.copy]p12, C++11 [class.copy]p25:
   6212   //   A [default constructor or destructor] is trivial if
   6213   //    -- all the direct base classes have trivial [default constructors or
   6214   //       destructors]
   6215   for (const auto &BI : RD->bases())
   6216     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
   6217                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
   6218       return false;
   6219 
   6220   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
   6221   //   A copy/move [constructor or assignment operator] for a class X is
   6222   //   trivial if
   6223   //    -- for each non-static data member of X that is of class type (or array
   6224   //       thereof), the constructor selected to copy/move that member is
   6225   //       trivial
   6226   //
   6227   // C++11 [class.copy]p12, C++11 [class.copy]p25:
   6228   //   A [default constructor or destructor] is trivial if
   6229   //    -- for all of the non-static data members of its class that are of class
   6230   //       type (or array thereof), each such class has a trivial [default
   6231   //       constructor or destructor]
   6232   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
   6233     return false;
   6234 
   6235   // C++11 [class.dtor]p5:
   6236   //   A destructor is trivial if [...]
   6237   //    -- the destructor is not virtual
   6238   if (CSM == CXXDestructor && MD->isVirtual()) {
   6239     if (Diagnose)
   6240       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
   6241     return false;
   6242   }
   6243 
   6244   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
   6245   //   A [special member] for class X is trivial if [...]
   6246   //    -- class X has no virtual functions and no virtual base classes
   6247   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
   6248     if (!Diagnose)
   6249       return false;
   6250 
   6251     if (RD->getNumVBases()) {
   6252       // Check for virtual bases. We already know that the corresponding
   6253       // member in all bases is trivial, so vbases must all be direct.
   6254       CXXBaseSpecifier &BS = *RD->vbases_begin();
   6255       assert(BS.isVirtual());
   6256       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
   6257       return false;
   6258     }
   6259 
   6260     // Must have a virtual method.
   6261     for (const auto *MI : RD->methods()) {
   6262       if (MI->isVirtual()) {
   6263         SourceLocation MLoc = MI->getLocStart();
   6264         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
   6265         return false;
   6266       }
   6267     }
   6268 
   6269     llvm_unreachable("dynamic class with no vbases and no virtual functions");
   6270   }
   6271 
   6272   // Looks like it's trivial!
   6273   return true;
   6274 }
   6275 
   6276 namespace {
   6277 struct FindHiddenVirtualMethod {
   6278   Sema *S;
   6279   CXXMethodDecl *Method;
   6280   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
   6281   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
   6282 
   6283 private:
   6284   /// Check whether any most overriden method from MD in Methods
   6285   static bool CheckMostOverridenMethods(
   6286       const CXXMethodDecl *MD,
   6287       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
   6288     if (MD->size_overridden_methods() == 0)
   6289       return Methods.count(MD->getCanonicalDecl());
   6290     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
   6291                                         E = MD->end_overridden_methods();
   6292          I != E; ++I)
   6293       if (CheckMostOverridenMethods(*I, Methods))
   6294         return true;
   6295     return false;
   6296   }
   6297 
   6298 public:
   6299   /// Member lookup function that determines whether a given C++
   6300   /// method overloads virtual methods in a base class without overriding any,
   6301   /// to be used with CXXRecordDecl::lookupInBases().
   6302   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
   6303     RecordDecl *BaseRecord =
   6304         Specifier->getType()->getAs<RecordType>()->getDecl();
   6305 
   6306     DeclarationName Name = Method->getDeclName();
   6307     assert(Name.getNameKind() == DeclarationName::Identifier);
   6308 
   6309     bool foundSameNameMethod = false;
   6310     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
   6311     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
   6312          Path.Decls = Path.Decls.slice(1)) {
   6313       NamedDecl *D = Path.Decls.front();
   6314       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
   6315         MD = MD->getCanonicalDecl();
   6316         foundSameNameMethod = true;
   6317         // Interested only in hidden virtual methods.
   6318         if (!MD->isVirtual())
   6319           continue;
   6320         // If the method we are checking overrides a method from its base
   6321         // don't warn about the other overloaded methods. Clang deviates from
   6322         // GCC by only diagnosing overloads of inherited virtual functions that
   6323         // do not override any other virtual functions in the base. GCC's
   6324         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
   6325         // function from a base class. These cases may be better served by a
   6326         // warning (not specific to virtual functions) on call sites when the
   6327         // call would select a different function from the base class, were it
   6328         // visible.
   6329         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
   6330         if (!S->IsOverload(Method, MD, false))
   6331           return true;
   6332         // Collect the overload only if its hidden.
   6333         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
   6334           overloadedMethods.push_back(MD);
   6335       }
   6336     }
   6337 
   6338     if (foundSameNameMethod)
   6339       OverloadedMethods.append(overloadedMethods.begin(),
   6340                                overloadedMethods.end());
   6341     return foundSameNameMethod;
   6342   }
   6343 };
   6344 } // end anonymous namespace
   6345 
   6346 /// \brief Add the most overriden methods from MD to Methods
   6347 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
   6348                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
   6349   if (MD->size_overridden_methods() == 0)
   6350     Methods.insert(MD->getCanonicalDecl());
   6351   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
   6352                                       E = MD->end_overridden_methods();
   6353        I != E; ++I)
   6354     AddMostOverridenMethods(*I, Methods);
   6355 }
   6356 
   6357 /// \brief Check if a method overloads virtual methods in a base class without
   6358 /// overriding any.
   6359 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
   6360                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
   6361   if (!MD->getDeclName().isIdentifier())
   6362     return;
   6363 
   6364   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
   6365                      /*bool RecordPaths=*/false,
   6366                      /*bool DetectVirtual=*/false);
   6367   FindHiddenVirtualMethod FHVM;
   6368   FHVM.Method = MD;
   6369   FHVM.S = this;
   6370 
   6371   // Keep the base methods that were overriden or introduced in the subclass
   6372   // by 'using' in a set. A base method not in this set is hidden.
   6373   CXXRecordDecl *DC = MD->getParent();
   6374   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
   6375   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
   6376     NamedDecl *ND = *I;
   6377     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
   6378       ND = shad->getTargetDecl();
   6379     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
   6380       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
   6381   }
   6382 
   6383   if (DC->lookupInBases(FHVM, Paths))
   6384     OverloadedMethods = FHVM.OverloadedMethods;
   6385 }
   6386 
   6387 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
   6388                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
   6389   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
   6390     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
   6391     PartialDiagnostic PD = PDiag(
   6392          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
   6393     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
   6394     Diag(overloadedMD->getLocation(), PD);
   6395   }
   6396 }
   6397 
   6398 /// \brief Diagnose methods which overload virtual methods in a base class
   6399 /// without overriding any.
   6400 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
   6401   if (MD->isInvalidDecl())
   6402     return;
   6403 
   6404   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
   6405     return;
   6406 
   6407   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
   6408   FindHiddenVirtualMethods(MD, OverloadedMethods);
   6409   if (!OverloadedMethods.empty()) {
   6410     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
   6411       << MD << (OverloadedMethods.size() > 1);
   6412 
   6413     NoteHiddenVirtualMethods(MD, OverloadedMethods);
   6414   }
   6415 }
   6416 
   6417 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
   6418                                              Decl *TagDecl,
   6419                                              SourceLocation LBrac,
   6420                                              SourceLocation RBrac,
   6421                                              AttributeList *AttrList) {
   6422   if (!TagDecl)
   6423     return;
   6424 
   6425   AdjustDeclIfTemplate(TagDecl);
   6426 
   6427   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
   6428     if (l->getKind() != AttributeList::AT_Visibility)
   6429       continue;
   6430     l->setInvalid();
   6431     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
   6432       l->getName();
   6433   }
   6434 
   6435   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
   6436               // strict aliasing violation!
   6437               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
   6438               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
   6439 
   6440   CheckCompletedCXXClass(
   6441                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
   6442 }
   6443 
   6444 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
   6445 /// special functions, such as the default constructor, copy
   6446 /// constructor, or destructor, to the given C++ class (C++
   6447 /// [special]p1).  This routine can only be executed just before the
   6448 /// definition of the class is complete.
   6449 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
   6450   if (!ClassDecl->hasUserDeclaredConstructor())
   6451     ++ASTContext::NumImplicitDefaultConstructors;
   6452 
   6453   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
   6454     ++ASTContext::NumImplicitCopyConstructors;
   6455 
   6456     // If the properties or semantics of the copy constructor couldn't be
   6457     // determined while the class was being declared, force a declaration
   6458     // of it now.
   6459     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
   6460       DeclareImplicitCopyConstructor(ClassDecl);
   6461   }
   6462 
   6463   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
   6464     ++ASTContext::NumImplicitMoveConstructors;
   6465 
   6466     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
   6467       DeclareImplicitMoveConstructor(ClassDecl);
   6468   }
   6469 
   6470   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
   6471     ++ASTContext::NumImplicitCopyAssignmentOperators;
   6472 
   6473     // If we have a dynamic class, then the copy assignment operator may be
   6474     // virtual, so we have to declare it immediately. This ensures that, e.g.,
   6475     // it shows up in the right place in the vtable and that we diagnose
   6476     // problems with the implicit exception specification.
   6477     if (ClassDecl->isDynamicClass() ||
   6478         ClassDecl->needsOverloadResolutionForCopyAssignment())
   6479       DeclareImplicitCopyAssignment(ClassDecl);
   6480   }
   6481 
   6482   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
   6483     ++ASTContext::NumImplicitMoveAssignmentOperators;
   6484 
   6485     // Likewise for the move assignment operator.
   6486     if (ClassDecl->isDynamicClass() ||
   6487         ClassDecl->needsOverloadResolutionForMoveAssignment())
   6488       DeclareImplicitMoveAssignment(ClassDecl);
   6489   }
   6490 
   6491   if (!ClassDecl->hasUserDeclaredDestructor()) {
   6492     ++ASTContext::NumImplicitDestructors;
   6493 
   6494     // If we have a dynamic class, then the destructor may be virtual, so we
   6495     // have to declare the destructor immediately. This ensures that, e.g., it
   6496     // shows up in the right place in the vtable and that we diagnose problems
   6497     // with the implicit exception specification.
   6498     if (ClassDecl->isDynamicClass() ||
   6499         ClassDecl->needsOverloadResolutionForDestructor())
   6500       DeclareImplicitDestructor(ClassDecl);
   6501   }
   6502 }
   6503 
   6504 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
   6505   if (!D)
   6506     return 0;
   6507 
   6508   // The order of template parameters is not important here. All names
   6509   // get added to the same scope.
   6510   SmallVector<TemplateParameterList *, 4> ParameterLists;
   6511 
   6512   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
   6513     D = TD->getTemplatedDecl();
   6514 
   6515   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
   6516     ParameterLists.push_back(PSD->getTemplateParameters());
   6517 
   6518   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
   6519     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
   6520       ParameterLists.push_back(DD->getTemplateParameterList(i));
   6521 
   6522     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   6523       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
   6524         ParameterLists.push_back(FTD->getTemplateParameters());
   6525     }
   6526   }
   6527 
   6528   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
   6529     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
   6530       ParameterLists.push_back(TD->getTemplateParameterList(i));
   6531 
   6532     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
   6533       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
   6534         ParameterLists.push_back(CTD->getTemplateParameters());
   6535     }
   6536   }
   6537 
   6538   unsigned Count = 0;
   6539   for (TemplateParameterList *Params : ParameterLists) {
   6540     if (Params->size() > 0)
   6541       // Ignore explicit specializations; they don't contribute to the template
   6542       // depth.
   6543       ++Count;
   6544     for (NamedDecl *Param : *Params) {
   6545       if (Param->getDeclName()) {
   6546         S->AddDecl(Param);
   6547         IdResolver.AddDecl(Param);
   6548       }
   6549     }
   6550   }
   6551 
   6552   return Count;
   6553 }
   6554 
   6555 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
   6556   if (!RecordD) return;
   6557   AdjustDeclIfTemplate(RecordD);
   6558   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
   6559   PushDeclContext(S, Record);
   6560 }
   6561 
   6562 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
   6563   if (!RecordD) return;
   6564   PopDeclContext();
   6565 }
   6566 
   6567 /// This is used to implement the constant expression evaluation part of the
   6568 /// attribute enable_if extension. There is nothing in standard C++ which would
   6569 /// require reentering parameters.
   6570 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
   6571   if (!Param)
   6572     return;
   6573 
   6574   S->AddDecl(Param);
   6575   if (Param->getDeclName())
   6576     IdResolver.AddDecl(Param);
   6577 }
   6578 
   6579 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
   6580 /// parsing a top-level (non-nested) C++ class, and we are now
   6581 /// parsing those parts of the given Method declaration that could
   6582 /// not be parsed earlier (C++ [class.mem]p2), such as default
   6583 /// arguments. This action should enter the scope of the given
   6584 /// Method declaration as if we had just parsed the qualified method
   6585 /// name. However, it should not bring the parameters into scope;
   6586 /// that will be performed by ActOnDelayedCXXMethodParameter.
   6587 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
   6588 }
   6589 
   6590 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
   6591 /// C++ method declaration. We're (re-)introducing the given
   6592 /// function parameter into scope for use in parsing later parts of
   6593 /// the method declaration. For example, we could see an
   6594 /// ActOnParamDefaultArgument event for this parameter.
   6595 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
   6596   if (!ParamD)
   6597     return;
   6598 
   6599   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
   6600 
   6601   // If this parameter has an unparsed default argument, clear it out
   6602   // to make way for the parsed default argument.
   6603   if (Param->hasUnparsedDefaultArg())
   6604     Param->setDefaultArg(nullptr);
   6605 
   6606   S->AddDecl(Param);
   6607   if (Param->getDeclName())
   6608     IdResolver.AddDecl(Param);
   6609 }
   6610 
   6611 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
   6612 /// processing the delayed method declaration for Method. The method
   6613 /// declaration is now considered finished. There may be a separate
   6614 /// ActOnStartOfFunctionDef action later (not necessarily
   6615 /// immediately!) for this method, if it was also defined inside the
   6616 /// class body.
   6617 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
   6618   if (!MethodD)
   6619     return;
   6620 
   6621   AdjustDeclIfTemplate(MethodD);
   6622 
   6623   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
   6624 
   6625   // Now that we have our default arguments, check the constructor
   6626   // again. It could produce additional diagnostics or affect whether
   6627   // the class has implicitly-declared destructors, among other
   6628   // things.
   6629   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
   6630     CheckConstructor(Constructor);
   6631 
   6632   // Check the default arguments, which we may have added.
   6633   if (!Method->isInvalidDecl())
   6634     CheckCXXDefaultArguments(Method);
   6635 }
   6636 
   6637 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
   6638 /// the well-formedness of the constructor declarator @p D with type @p
   6639 /// R. If there are any errors in the declarator, this routine will
   6640 /// emit diagnostics and set the invalid bit to true.  In any case, the type
   6641 /// will be updated to reflect a well-formed type for the constructor and
   6642 /// returned.
   6643 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
   6644                                           StorageClass &SC) {
   6645   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
   6646 
   6647   // C++ [class.ctor]p3:
   6648   //   A constructor shall not be virtual (10.3) or static (9.4). A
   6649   //   constructor can be invoked for a const, volatile or const
   6650   //   volatile object. A constructor shall not be declared const,
   6651   //   volatile, or const volatile (9.3.2).
   6652   if (isVirtual) {
   6653     if (!D.isInvalidType())
   6654       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
   6655         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
   6656         << SourceRange(D.getIdentifierLoc());
   6657     D.setInvalidType();
   6658   }
   6659   if (SC == SC_Static) {
   6660     if (!D.isInvalidType())
   6661       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
   6662         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
   6663         << SourceRange(D.getIdentifierLoc());
   6664     D.setInvalidType();
   6665     SC = SC_None;
   6666   }
   6667 
   6668   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
   6669     diagnoseIgnoredQualifiers(
   6670         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
   6671         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
   6672         D.getDeclSpec().getRestrictSpecLoc(),
   6673         D.getDeclSpec().getAtomicSpecLoc());
   6674     D.setInvalidType();
   6675   }
   6676 
   6677   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
   6678   if (FTI.TypeQuals != 0) {
   6679     if (FTI.TypeQuals & Qualifiers::Const)
   6680       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
   6681         << "const" << SourceRange(D.getIdentifierLoc());
   6682     if (FTI.TypeQuals & Qualifiers::Volatile)
   6683       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
   6684         << "volatile" << SourceRange(D.getIdentifierLoc());
   6685     if (FTI.TypeQuals & Qualifiers::Restrict)
   6686       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
   6687         << "restrict" << SourceRange(D.getIdentifierLoc());
   6688     D.setInvalidType();
   6689   }
   6690 
   6691   // C++0x [class.ctor]p4:
   6692   //   A constructor shall not be declared with a ref-qualifier.
   6693   if (FTI.hasRefQualifier()) {
   6694     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
   6695       << FTI.RefQualifierIsLValueRef
   6696       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
   6697     D.setInvalidType();
   6698   }
   6699 
   6700   // Rebuild the function type "R" without any type qualifiers (in
   6701   // case any of the errors above fired) and with "void" as the
   6702   // return type, since constructors don't have return types.
   6703   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
   6704   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
   6705     return R;
   6706 
   6707   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
   6708   EPI.TypeQuals = 0;
   6709   EPI.RefQualifier = RQ_None;
   6710 
   6711   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
   6712 }
   6713 
   6714 /// CheckConstructor - Checks a fully-formed constructor for
   6715 /// well-formedness, issuing any diagnostics required. Returns true if
   6716 /// the constructor declarator is invalid.
   6717 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
   6718   CXXRecordDecl *ClassDecl
   6719     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
   6720   if (!ClassDecl)
   6721     return Constructor->setInvalidDecl();
   6722 
   6723   // C++ [class.copy]p3:
   6724   //   A declaration of a constructor for a class X is ill-formed if
   6725   //   its first parameter is of type (optionally cv-qualified) X and
   6726   //   either there are no other parameters or else all other
   6727   //   parameters have default arguments.
   6728   if (!Constructor->isInvalidDecl() &&
   6729       ((Constructor->getNumParams() == 1) ||
   6730        (Constructor->getNumParams() > 1 &&
   6731         Constructor->getParamDecl(1)->hasDefaultArg())) &&
   6732       Constructor->getTemplateSpecializationKind()
   6733                                               != TSK_ImplicitInstantiation) {
   6734     QualType ParamType = Constructor->getParamDecl(0)->getType();
   6735     QualType ClassTy = Context.getTagDeclType(ClassDecl);
   6736     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
   6737       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
   6738       const char *ConstRef
   6739         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
   6740                                                         : " const &";
   6741       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
   6742         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
   6743 
   6744       // FIXME: Rather that making the constructor invalid, we should endeavor
   6745       // to fix the type.
   6746       Constructor->setInvalidDecl();
   6747     }
   6748   }
   6749 }
   6750 
   6751 /// CheckDestructor - Checks a fully-formed destructor definition for
   6752 /// well-formedness, issuing any diagnostics required.  Returns true
   6753 /// on error.
   6754 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
   6755   CXXRecordDecl *RD = Destructor->getParent();
   6756 
   6757   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
   6758     SourceLocation Loc;
   6759 
   6760     if (!Destructor->isImplicit())
   6761       Loc = Destructor->getLocation();
   6762     else
   6763       Loc = RD->getLocation();
   6764 
   6765     // If we have a virtual destructor, look up the deallocation function
   6766     FunctionDecl *OperatorDelete = nullptr;
   6767     DeclarationName Name =
   6768     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
   6769     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
   6770       return true;
   6771     // If there's no class-specific operator delete, look up the global
   6772     // non-array delete.
   6773     if (!OperatorDelete)
   6774       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
   6775 
   6776     MarkFunctionReferenced(Loc, OperatorDelete);
   6777 
   6778     Destructor->setOperatorDelete(OperatorDelete);
   6779   }
   6780 
   6781   return false;
   6782 }
   6783 
   6784 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
   6785 /// the well-formednes of the destructor declarator @p D with type @p
   6786 /// R. If there are any errors in the declarator, this routine will
   6787 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
   6788 /// will be updated to reflect a well-formed type for the destructor and
   6789 /// returned.
   6790 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
   6791                                          StorageClass& SC) {
   6792   // C++ [class.dtor]p1:
   6793   //   [...] A typedef-name that names a class is a class-name
   6794   //   (7.1.3); however, a typedef-name that names a class shall not
   6795   //   be used as the identifier in the declarator for a destructor
   6796   //   declaration.
   6797   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
   6798   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
   6799     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
   6800       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
   6801   else if (const TemplateSpecializationType *TST =
   6802              DeclaratorType->getAs<TemplateSpecializationType>())
   6803     if (TST->isTypeAlias())
   6804       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
   6805         << DeclaratorType << 1;
   6806 
   6807   // C++ [class.dtor]p2:
   6808   //   A destructor is used to destroy objects of its class type. A
   6809   //   destructor takes no parameters, and no return type can be
   6810   //   specified for it (not even void). The address of a destructor
   6811   //   shall not be taken. A destructor shall not be static. A
   6812   //   destructor can be invoked for a const, volatile or const
   6813   //   volatile object. A destructor shall not be declared const,
   6814   //   volatile or const volatile (9.3.2).
   6815   if (SC == SC_Static) {
   6816     if (!D.isInvalidType())
   6817       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
   6818         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
   6819         << SourceRange(D.getIdentifierLoc())
   6820         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
   6821 
   6822     SC = SC_None;
   6823   }
   6824   if (!D.isInvalidType()) {
   6825     // Destructors don't have return types, but the parser will
   6826     // happily parse something like:
   6827     //
   6828     //   class X {
   6829     //     float ~X();
   6830     //   };
   6831     //
   6832     // The return type will be eliminated later.
   6833     if (D.getDeclSpec().hasTypeSpecifier())
   6834       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
   6835         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
   6836         << SourceRange(D.getIdentifierLoc());
   6837     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
   6838       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
   6839                                 SourceLocation(),
   6840                                 D.getDeclSpec().getConstSpecLoc(),
   6841                                 D.getDeclSpec().getVolatileSpecLoc(),
   6842                                 D.getDeclSpec().getRestrictSpecLoc(),
   6843                                 D.getDeclSpec().getAtomicSpecLoc());
   6844       D.setInvalidType();
   6845     }
   6846   }
   6847 
   6848   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
   6849   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
   6850     if (FTI.TypeQuals & Qualifiers::Const)
   6851       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
   6852         << "const" << SourceRange(D.getIdentifierLoc());
   6853     if (FTI.TypeQuals & Qualifiers::Volatile)
   6854       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
   6855         << "volatile" << SourceRange(D.getIdentifierLoc());
   6856     if (FTI.TypeQuals & Qualifiers::Restrict)
   6857       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
   6858         << "restrict" << SourceRange(D.getIdentifierLoc());
   6859     D.setInvalidType();
   6860   }
   6861 
   6862   // C++0x [class.dtor]p2:
   6863   //   A destructor shall not be declared with a ref-qualifier.
   6864   if (FTI.hasRefQualifier()) {
   6865     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
   6866       << FTI.RefQualifierIsLValueRef
   6867       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
   6868     D.setInvalidType();
   6869   }
   6870 
   6871   // Make sure we don't have any parameters.
   6872   if (FTIHasNonVoidParameters(FTI)) {
   6873     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
   6874 
   6875     // Delete the parameters.
   6876     FTI.freeParams();
   6877     D.setInvalidType();
   6878   }
   6879 
   6880   // Make sure the destructor isn't variadic.
   6881   if (FTI.isVariadic) {
   6882     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
   6883     D.setInvalidType();
   6884   }
   6885 
   6886   // Rebuild the function type "R" without any type qualifiers or
   6887   // parameters (in case any of the errors above fired) and with
   6888   // "void" as the return type, since destructors don't have return
   6889   // types.
   6890   if (!D.isInvalidType())
   6891     return R;
   6892 
   6893   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
   6894   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
   6895   EPI.Variadic = false;
   6896   EPI.TypeQuals = 0;
   6897   EPI.RefQualifier = RQ_None;
   6898   return Context.getFunctionType(Context.VoidTy, None, EPI);
   6899 }
   6900 
   6901 static void extendLeft(SourceRange &R, SourceRange Before) {
   6902   if (Before.isInvalid())
   6903     return;
   6904   R.setBegin(Before.getBegin());
   6905   if (R.getEnd().isInvalid())
   6906     R.setEnd(Before.getEnd());
   6907 }
   6908 
   6909 static void extendRight(SourceRange &R, SourceRange After) {
   6910   if (After.isInvalid())
   6911     return;
   6912   if (R.getBegin().isInvalid())
   6913     R.setBegin(After.getBegin());
   6914   R.setEnd(After.getEnd());
   6915 }
   6916 
   6917 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
   6918 /// well-formednes of the conversion function declarator @p D with
   6919 /// type @p R. If there are any errors in the declarator, this routine
   6920 /// will emit diagnostics and return true. Otherwise, it will return
   6921 /// false. Either way, the type @p R will be updated to reflect a
   6922 /// well-formed type for the conversion operator.
   6923 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
   6924                                      StorageClass& SC) {
   6925   // C++ [class.conv.fct]p1:
   6926   //   Neither parameter types nor return type can be specified. The
   6927   //   type of a conversion function (8.3.5) is "function taking no
   6928   //   parameter returning conversion-type-id."
   6929   if (SC == SC_Static) {
   6930     if (!D.isInvalidType())
   6931       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
   6932         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
   6933         << D.getName().getSourceRange();
   6934     D.setInvalidType();
   6935     SC = SC_None;
   6936   }
   6937 
   6938   TypeSourceInfo *ConvTSI = nullptr;
   6939   QualType ConvType =
   6940       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
   6941 
   6942   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
   6943     // Conversion functions don't have return types, but the parser will
   6944     // happily parse something like:
   6945     //
   6946     //   class X {
   6947     //     float operator bool();
   6948     //   };
   6949     //
   6950     // The return type will be changed later anyway.
   6951     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
   6952       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
   6953       << SourceRange(D.getIdentifierLoc());
   6954     D.setInvalidType();
   6955   }
   6956 
   6957   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
   6958 
   6959   // Make sure we don't have any parameters.
   6960   if (Proto->getNumParams() > 0) {
   6961     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
   6962 
   6963     // Delete the parameters.
   6964     D.getFunctionTypeInfo().freeParams();
   6965     D.setInvalidType();
   6966   } else if (Proto->isVariadic()) {
   6967     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
   6968     D.setInvalidType();
   6969   }
   6970 
   6971   // Diagnose "&operator bool()" and other such nonsense.  This
   6972   // is actually a gcc extension which we don't support.
   6973   if (Proto->getReturnType() != ConvType) {
   6974     bool NeedsTypedef = false;
   6975     SourceRange Before, After;
   6976 
   6977     // Walk the chunks and extract information on them for our diagnostic.
   6978     bool PastFunctionChunk = false;
   6979     for (auto &Chunk : D.type_objects()) {
   6980       switch (Chunk.Kind) {
   6981       case DeclaratorChunk::Function:
   6982         if (!PastFunctionChunk) {
   6983           if (Chunk.Fun.HasTrailingReturnType) {
   6984             TypeSourceInfo *TRT = nullptr;
   6985             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
   6986             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
   6987           }
   6988           PastFunctionChunk = true;
   6989           break;
   6990         }
   6991         // Fall through.
   6992       case DeclaratorChunk::Array:
   6993         NeedsTypedef = true;
   6994         extendRight(After, Chunk.getSourceRange());
   6995         break;
   6996 
   6997       case DeclaratorChunk::Pointer:
   6998       case DeclaratorChunk::BlockPointer:
   6999       case DeclaratorChunk::Reference:
   7000       case DeclaratorChunk::MemberPointer:
   7001         extendLeft(Before, Chunk.getSourceRange());
   7002         break;
   7003 
   7004       case DeclaratorChunk::Paren:
   7005         extendLeft(Before, Chunk.Loc);
   7006         extendRight(After, Chunk.EndLoc);
   7007         break;
   7008       }
   7009     }
   7010 
   7011     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
   7012                          After.isValid()  ? After.getBegin() :
   7013                                             D.getIdentifierLoc();
   7014     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
   7015     DB << Before << After;
   7016 
   7017     if (!NeedsTypedef) {
   7018       DB << /*don't need a typedef*/0;
   7019 
   7020       // If we can provide a correct fix-it hint, do so.
   7021       if (After.isInvalid() && ConvTSI) {
   7022         SourceLocation InsertLoc =
   7023             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
   7024         DB << FixItHint::CreateInsertion(InsertLoc, " ")
   7025            << FixItHint::CreateInsertionFromRange(
   7026                   InsertLoc, CharSourceRange::getTokenRange(Before))
   7027            << FixItHint::CreateRemoval(Before);
   7028       }
   7029     } else if (!Proto->getReturnType()->isDependentType()) {
   7030       DB << /*typedef*/1 << Proto->getReturnType();
   7031     } else if (getLangOpts().CPlusPlus11) {
   7032       DB << /*alias template*/2 << Proto->getReturnType();
   7033     } else {
   7034       DB << /*might not be fixable*/3;
   7035     }
   7036 
   7037     // Recover by incorporating the other type chunks into the result type.
   7038     // Note, this does *not* change the name of the function. This is compatible
   7039     // with the GCC extension:
   7040     //   struct S { &operator int(); } s;
   7041     //   int &r = s.operator int(); // ok in GCC
   7042     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
   7043     ConvType = Proto->getReturnType();
   7044   }
   7045 
   7046   // C++ [class.conv.fct]p4:
   7047   //   The conversion-type-id shall not represent a function type nor
   7048   //   an array type.
   7049   if (ConvType->isArrayType()) {
   7050     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
   7051     ConvType = Context.getPointerType(ConvType);
   7052     D.setInvalidType();
   7053   } else if (ConvType->isFunctionType()) {
   7054     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
   7055     ConvType = Context.getPointerType(ConvType);
   7056     D.setInvalidType();
   7057   }
   7058 
   7059   // Rebuild the function type "R" without any parameters (in case any
   7060   // of the errors above fired) and with the conversion type as the
   7061   // return type.
   7062   if (D.isInvalidType())
   7063     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
   7064 
   7065   // C++0x explicit conversion operators.
   7066   if (D.getDeclSpec().isExplicitSpecified())
   7067     Diag(D.getDeclSpec().getExplicitSpecLoc(),
   7068          getLangOpts().CPlusPlus11 ?
   7069            diag::warn_cxx98_compat_explicit_conversion_functions :
   7070            diag::ext_explicit_conversion_functions)
   7071       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
   7072 }
   7073 
   7074 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
   7075 /// the declaration of the given C++ conversion function. This routine
   7076 /// is responsible for recording the conversion function in the C++
   7077 /// class, if possible.
   7078 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
   7079   assert(Conversion && "Expected to receive a conversion function declaration");
   7080 
   7081   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
   7082 
   7083   // Make sure we aren't redeclaring the conversion function.
   7084   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
   7085 
   7086   // C++ [class.conv.fct]p1:
   7087   //   [...] A conversion function is never used to convert a
   7088   //   (possibly cv-qualified) object to the (possibly cv-qualified)
   7089   //   same object type (or a reference to it), to a (possibly
   7090   //   cv-qualified) base class of that type (or a reference to it),
   7091   //   or to (possibly cv-qualified) void.
   7092   // FIXME: Suppress this warning if the conversion function ends up being a
   7093   // virtual function that overrides a virtual function in a base class.
   7094   QualType ClassType
   7095     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
   7096   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
   7097     ConvType = ConvTypeRef->getPointeeType();
   7098   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
   7099       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
   7100     /* Suppress diagnostics for instantiations. */;
   7101   else if (ConvType->isRecordType()) {
   7102     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
   7103     if (ConvType == ClassType)
   7104       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
   7105         << ClassType;
   7106     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
   7107       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
   7108         <<  ClassType << ConvType;
   7109   } else if (ConvType->isVoidType()) {
   7110     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
   7111       << ClassType << ConvType;
   7112   }
   7113 
   7114   if (FunctionTemplateDecl *ConversionTemplate
   7115                                 = Conversion->getDescribedFunctionTemplate())
   7116     return ConversionTemplate;
   7117 
   7118   return Conversion;
   7119 }
   7120 
   7121 //===----------------------------------------------------------------------===//
   7122 // Namespace Handling
   7123 //===----------------------------------------------------------------------===//
   7124 
   7125 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
   7126 /// reopened.
   7127 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
   7128                                             SourceLocation Loc,
   7129                                             IdentifierInfo *II, bool *IsInline,
   7130                                             NamespaceDecl *PrevNS) {
   7131   assert(*IsInline != PrevNS->isInline());
   7132 
   7133   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
   7134   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
   7135   // inline namespaces, with the intention of bringing names into namespace std.
   7136   //
   7137   // We support this just well enough to get that case working; this is not
   7138   // sufficient to support reopening namespaces as inline in general.
   7139   if (*IsInline && II && II->getName().startswith("__atomic") &&
   7140       S.getSourceManager().isInSystemHeader(Loc)) {
   7141     // Mark all prior declarations of the namespace as inline.
   7142     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
   7143          NS = NS->getPreviousDecl())
   7144       NS->setInline(*IsInline);
   7145     // Patch up the lookup table for the containing namespace. This isn't really
   7146     // correct, but it's good enough for this particular case.
   7147     for (auto *I : PrevNS->decls())
   7148       if (auto *ND = dyn_cast<NamedDecl>(I))
   7149         PrevNS->getParent()->makeDeclVisibleInContext(ND);
   7150     return;
   7151   }
   7152 
   7153   if (PrevNS->isInline())
   7154     // The user probably just forgot the 'inline', so suggest that it
   7155     // be added back.
   7156     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
   7157       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
   7158   else
   7159     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
   7160 
   7161   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
   7162   *IsInline = PrevNS->isInline();
   7163 }
   7164 
   7165 /// ActOnStartNamespaceDef - This is called at the start of a namespace
   7166 /// definition.
   7167 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
   7168                                    SourceLocation InlineLoc,
   7169                                    SourceLocation NamespaceLoc,
   7170                                    SourceLocation IdentLoc,
   7171                                    IdentifierInfo *II,
   7172                                    SourceLocation LBrace,
   7173                                    AttributeList *AttrList,
   7174                                    UsingDirectiveDecl *&UD) {
   7175   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
   7176   // For anonymous namespace, take the location of the left brace.
   7177   SourceLocation Loc = II ? IdentLoc : LBrace;
   7178   bool IsInline = InlineLoc.isValid();
   7179   bool IsInvalid = false;
   7180   bool IsStd = false;
   7181   bool AddToKnown = false;
   7182   Scope *DeclRegionScope = NamespcScope->getParent();
   7183 
   7184   NamespaceDecl *PrevNS = nullptr;
   7185   if (II) {
   7186     // C++ [namespace.def]p2:
   7187     //   The identifier in an original-namespace-definition shall not
   7188     //   have been previously defined in the declarative region in
   7189     //   which the original-namespace-definition appears. The
   7190     //   identifier in an original-namespace-definition is the name of
   7191     //   the namespace. Subsequently in that declarative region, it is
   7192     //   treated as an original-namespace-name.
   7193     //
   7194     // Since namespace names are unique in their scope, and we don't
   7195     // look through using directives, just look for any ordinary names
   7196     // as if by qualified name lookup.
   7197     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
   7198     LookupQualifiedName(R, CurContext->getRedeclContext());
   7199     NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
   7200     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
   7201 
   7202     if (PrevNS) {
   7203       // This is an extended namespace definition.
   7204       if (IsInline != PrevNS->isInline())
   7205         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
   7206                                         &IsInline, PrevNS);
   7207     } else if (PrevDecl) {
   7208       // This is an invalid name redefinition.
   7209       Diag(Loc, diag::err_redefinition_different_kind)
   7210         << II;
   7211       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   7212       IsInvalid = true;
   7213       // Continue on to push Namespc as current DeclContext and return it.
   7214     } else if (II->isStr("std") &&
   7215                CurContext->getRedeclContext()->isTranslationUnit()) {
   7216       // This is the first "real" definition of the namespace "std", so update
   7217       // our cache of the "std" namespace to point at this definition.
   7218       PrevNS = getStdNamespace();
   7219       IsStd = true;
   7220       AddToKnown = !IsInline;
   7221     } else {
   7222       // We've seen this namespace for the first time.
   7223       AddToKnown = !IsInline;
   7224     }
   7225   } else {
   7226     // Anonymous namespaces.
   7227 
   7228     // Determine whether the parent already has an anonymous namespace.
   7229     DeclContext *Parent = CurContext->getRedeclContext();
   7230     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
   7231       PrevNS = TU->getAnonymousNamespace();
   7232     } else {
   7233       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
   7234       PrevNS = ND->getAnonymousNamespace();
   7235     }
   7236 
   7237     if (PrevNS && IsInline != PrevNS->isInline())
   7238       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
   7239                                       &IsInline, PrevNS);
   7240   }
   7241 
   7242   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
   7243                                                  StartLoc, Loc, II, PrevNS);
   7244   if (IsInvalid)
   7245     Namespc->setInvalidDecl();
   7246 
   7247   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
   7248 
   7249   // FIXME: Should we be merging attributes?
   7250   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
   7251     PushNamespaceVisibilityAttr(Attr, Loc);
   7252 
   7253   if (IsStd)
   7254     StdNamespace = Namespc;
   7255   if (AddToKnown)
   7256     KnownNamespaces[Namespc] = false;
   7257 
   7258   if (II) {
   7259     PushOnScopeChains(Namespc, DeclRegionScope);
   7260   } else {
   7261     // Link the anonymous namespace into its parent.
   7262     DeclContext *Parent = CurContext->getRedeclContext();
   7263     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
   7264       TU->setAnonymousNamespace(Namespc);
   7265     } else {
   7266       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
   7267     }
   7268 
   7269     CurContext->addDecl(Namespc);
   7270 
   7271     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
   7272     //   behaves as if it were replaced by
   7273     //     namespace unique { /* empty body */ }
   7274     //     using namespace unique;
   7275     //     namespace unique { namespace-body }
   7276     //   where all occurrences of 'unique' in a translation unit are
   7277     //   replaced by the same identifier and this identifier differs
   7278     //   from all other identifiers in the entire program.
   7279 
   7280     // We just create the namespace with an empty name and then add an
   7281     // implicit using declaration, just like the standard suggests.
   7282     //
   7283     // CodeGen enforces the "universally unique" aspect by giving all
   7284     // declarations semantically contained within an anonymous
   7285     // namespace internal linkage.
   7286 
   7287     if (!PrevNS) {
   7288       UD = UsingDirectiveDecl::Create(Context, Parent,
   7289                                       /* 'using' */ LBrace,
   7290                                       /* 'namespace' */ SourceLocation(),
   7291                                       /* qualifier */ NestedNameSpecifierLoc(),
   7292                                       /* identifier */ SourceLocation(),
   7293                                       Namespc,
   7294                                       /* Ancestor */ Parent);
   7295       UD->setImplicit();
   7296       Parent->addDecl(UD);
   7297     }
   7298   }
   7299 
   7300   ActOnDocumentableDecl(Namespc);
   7301 
   7302   // Although we could have an invalid decl (i.e. the namespace name is a
   7303   // redefinition), push it as current DeclContext and try to continue parsing.
   7304   // FIXME: We should be able to push Namespc here, so that the each DeclContext
   7305   // for the namespace has the declarations that showed up in that particular
   7306   // namespace definition.
   7307   PushDeclContext(NamespcScope, Namespc);
   7308   return Namespc;
   7309 }
   7310 
   7311 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
   7312 /// is a namespace alias, returns the namespace it points to.
   7313 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
   7314   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
   7315     return AD->getNamespace();
   7316   return dyn_cast_or_null<NamespaceDecl>(D);
   7317 }
   7318 
   7319 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
   7320 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
   7321 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
   7322   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
   7323   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
   7324   Namespc->setRBraceLoc(RBrace);
   7325   PopDeclContext();
   7326   if (Namespc->hasAttr<VisibilityAttr>())
   7327     PopPragmaVisibility(true, RBrace);
   7328 }
   7329 
   7330 CXXRecordDecl *Sema::getStdBadAlloc() const {
   7331   return cast_or_null<CXXRecordDecl>(
   7332                                   StdBadAlloc.get(Context.getExternalSource()));
   7333 }
   7334 
   7335 NamespaceDecl *Sema::getStdNamespace() const {
   7336   return cast_or_null<NamespaceDecl>(
   7337                                  StdNamespace.get(Context.getExternalSource()));
   7338 }
   7339 
   7340 /// \brief Retrieve the special "std" namespace, which may require us to
   7341 /// implicitly define the namespace.
   7342 NamespaceDecl *Sema::getOrCreateStdNamespace() {
   7343   if (!StdNamespace) {
   7344     // The "std" namespace has not yet been defined, so build one implicitly.
   7345     StdNamespace = NamespaceDecl::Create(Context,
   7346                                          Context.getTranslationUnitDecl(),
   7347                                          /*Inline=*/false,
   7348                                          SourceLocation(), SourceLocation(),
   7349                                          &PP.getIdentifierTable().get("std"),
   7350                                          /*PrevDecl=*/nullptr);
   7351     getStdNamespace()->setImplicit(true);
   7352   }
   7353 
   7354   return getStdNamespace();
   7355 }
   7356 
   7357 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
   7358   assert(getLangOpts().CPlusPlus &&
   7359          "Looking for std::initializer_list outside of C++.");
   7360 
   7361   // We're looking for implicit instantiations of
   7362   // template <typename E> class std::initializer_list.
   7363 
   7364   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
   7365     return false;
   7366 
   7367   ClassTemplateDecl *Template = nullptr;
   7368   const TemplateArgument *Arguments = nullptr;
   7369 
   7370   if (const RecordType *RT = Ty->getAs<RecordType>()) {
   7371 
   7372     ClassTemplateSpecializationDecl *Specialization =
   7373         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
   7374     if (!Specialization)
   7375       return false;
   7376 
   7377     Template = Specialization->getSpecializedTemplate();
   7378     Arguments = Specialization->getTemplateArgs().data();
   7379   } else if (const TemplateSpecializationType *TST =
   7380                  Ty->getAs<TemplateSpecializationType>()) {
   7381     Template = dyn_cast_or_null<ClassTemplateDecl>(
   7382         TST->getTemplateName().getAsTemplateDecl());
   7383     Arguments = TST->getArgs();
   7384   }
   7385   if (!Template)
   7386     return false;
   7387 
   7388   if (!StdInitializerList) {
   7389     // Haven't recognized std::initializer_list yet, maybe this is it.
   7390     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
   7391     if (TemplateClass->getIdentifier() !=
   7392             &PP.getIdentifierTable().get("initializer_list") ||
   7393         !getStdNamespace()->InEnclosingNamespaceSetOf(
   7394             TemplateClass->getDeclContext()))
   7395       return false;
   7396     // This is a template called std::initializer_list, but is it the right
   7397     // template?
   7398     TemplateParameterList *Params = Template->getTemplateParameters();
   7399     if (Params->getMinRequiredArguments() != 1)
   7400       return false;
   7401     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
   7402       return false;
   7403 
   7404     // It's the right template.
   7405     StdInitializerList = Template;
   7406   }
   7407 
   7408   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
   7409     return false;
   7410 
   7411   // This is an instance of std::initializer_list. Find the argument type.
   7412   if (Element)
   7413     *Element = Arguments[0].getAsType();
   7414   return true;
   7415 }
   7416 
   7417 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
   7418   NamespaceDecl *Std = S.getStdNamespace();
   7419   if (!Std) {
   7420     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
   7421     return nullptr;
   7422   }
   7423 
   7424   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
   7425                       Loc, Sema::LookupOrdinaryName);
   7426   if (!S.LookupQualifiedName(Result, Std)) {
   7427     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
   7428     return nullptr;
   7429   }
   7430   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
   7431   if (!Template) {
   7432     Result.suppressDiagnostics();
   7433     // We found something weird. Complain about the first thing we found.
   7434     NamedDecl *Found = *Result.begin();
   7435     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
   7436     return nullptr;
   7437   }
   7438 
   7439   // We found some template called std::initializer_list. Now verify that it's
   7440   // correct.
   7441   TemplateParameterList *Params = Template->getTemplateParameters();
   7442   if (Params->getMinRequiredArguments() != 1 ||
   7443       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
   7444     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
   7445     return nullptr;
   7446   }
   7447 
   7448   return Template;
   7449 }
   7450 
   7451 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
   7452   if (!StdInitializerList) {
   7453     StdInitializerList = LookupStdInitializerList(*this, Loc);
   7454     if (!StdInitializerList)
   7455       return QualType();
   7456   }
   7457 
   7458   TemplateArgumentListInfo Args(Loc, Loc);
   7459   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
   7460                                        Context.getTrivialTypeSourceInfo(Element,
   7461                                                                         Loc)));
   7462   return Context.getCanonicalType(
   7463       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
   7464 }
   7465 
   7466 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
   7467   // C++ [dcl.init.list]p2:
   7468   //   A constructor is an initializer-list constructor if its first parameter
   7469   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
   7470   //   std::initializer_list<E> for some type E, and either there are no other
   7471   //   parameters or else all other parameters have default arguments.
   7472   if (Ctor->getNumParams() < 1 ||
   7473       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
   7474     return false;
   7475 
   7476   QualType ArgType = Ctor->getParamDecl(0)->getType();
   7477   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
   7478     ArgType = RT->getPointeeType().getUnqualifiedType();
   7479 
   7480   return isStdInitializerList(ArgType, nullptr);
   7481 }
   7482 
   7483 /// \brief Determine whether a using statement is in a context where it will be
   7484 /// apply in all contexts.
   7485 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
   7486   switch (CurContext->getDeclKind()) {
   7487     case Decl::TranslationUnit:
   7488       return true;
   7489     case Decl::LinkageSpec:
   7490       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
   7491     default:
   7492       return false;
   7493   }
   7494 }
   7495 
   7496 namespace {
   7497 
   7498 // Callback to only accept typo corrections that are namespaces.
   7499 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
   7500 public:
   7501   bool ValidateCandidate(const TypoCorrection &candidate) override {
   7502     if (NamedDecl *ND = candidate.getCorrectionDecl())
   7503       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
   7504     return false;
   7505   }
   7506 };
   7507 
   7508 }
   7509 
   7510 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
   7511                                        CXXScopeSpec &SS,
   7512                                        SourceLocation IdentLoc,
   7513                                        IdentifierInfo *Ident) {
   7514   R.clear();
   7515   if (TypoCorrection Corrected =
   7516           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
   7517                         llvm::make_unique<NamespaceValidatorCCC>(),
   7518                         Sema::CTK_ErrorRecovery)) {
   7519     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
   7520       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
   7521       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
   7522                               Ident->getName().equals(CorrectedStr);
   7523       S.diagnoseTypo(Corrected,
   7524                      S.PDiag(diag::err_using_directive_member_suggest)
   7525                        << Ident << DC << DroppedSpecifier << SS.getRange(),
   7526                      S.PDiag(diag::note_namespace_defined_here));
   7527     } else {
   7528       S.diagnoseTypo(Corrected,
   7529                      S.PDiag(diag::err_using_directive_suggest) << Ident,
   7530                      S.PDiag(diag::note_namespace_defined_here));
   7531     }
   7532     R.addDecl(Corrected.getCorrectionDecl());
   7533     return true;
   7534   }
   7535   return false;
   7536 }
   7537 
   7538 Decl *Sema::ActOnUsingDirective(Scope *S,
   7539                                           SourceLocation UsingLoc,
   7540                                           SourceLocation NamespcLoc,
   7541                                           CXXScopeSpec &SS,
   7542                                           SourceLocation IdentLoc,
   7543                                           IdentifierInfo *NamespcName,
   7544                                           AttributeList *AttrList) {
   7545   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
   7546   assert(NamespcName && "Invalid NamespcName.");
   7547   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
   7548 
   7549   // This can only happen along a recovery path.
   7550   while (S->isTemplateParamScope())
   7551     S = S->getParent();
   7552   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
   7553 
   7554   UsingDirectiveDecl *UDir = nullptr;
   7555   NestedNameSpecifier *Qualifier = nullptr;
   7556   if (SS.isSet())
   7557     Qualifier = SS.getScopeRep();
   7558 
   7559   // Lookup namespace name.
   7560   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
   7561   LookupParsedName(R, S, &SS);
   7562   if (R.isAmbiguous())
   7563     return nullptr;
   7564 
   7565   if (R.empty()) {
   7566     R.clear();
   7567     // Allow "using namespace std;" or "using namespace ::std;" even if
   7568     // "std" hasn't been defined yet, for GCC compatibility.
   7569     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
   7570         NamespcName->isStr("std")) {
   7571       Diag(IdentLoc, diag::ext_using_undefined_std);
   7572       R.addDecl(getOrCreateStdNamespace());
   7573       R.resolveKind();
   7574     }
   7575     // Otherwise, attempt typo correction.
   7576     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
   7577   }
   7578 
   7579   if (!R.empty()) {
   7580     NamedDecl *Named = R.getFoundDecl();
   7581     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
   7582         && "expected namespace decl");
   7583 
   7584     // The use of a nested name specifier may trigger deprecation warnings.
   7585     DiagnoseUseOfDecl(Named, IdentLoc);
   7586 
   7587     // C++ [namespace.udir]p1:
   7588     //   A using-directive specifies that the names in the nominated
   7589     //   namespace can be used in the scope in which the
   7590     //   using-directive appears after the using-directive. During
   7591     //   unqualified name lookup (3.4.1), the names appear as if they
   7592     //   were declared in the nearest enclosing namespace which
   7593     //   contains both the using-directive and the nominated
   7594     //   namespace. [Note: in this context, "contains" means "contains
   7595     //   directly or indirectly". ]
   7596 
   7597     // Find enclosing context containing both using-directive and
   7598     // nominated namespace.
   7599     NamespaceDecl *NS = getNamespaceDecl(Named);
   7600     DeclContext *CommonAncestor = cast<DeclContext>(NS);
   7601     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
   7602       CommonAncestor = CommonAncestor->getParent();
   7603 
   7604     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
   7605                                       SS.getWithLocInContext(Context),
   7606                                       IdentLoc, Named, CommonAncestor);
   7607 
   7608     if (IsUsingDirectiveInToplevelContext(CurContext) &&
   7609         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
   7610       Diag(IdentLoc, diag::warn_using_directive_in_header);
   7611     }
   7612 
   7613     PushUsingDirective(S, UDir);
   7614   } else {
   7615     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
   7616   }
   7617 
   7618   if (UDir)
   7619     ProcessDeclAttributeList(S, UDir, AttrList);
   7620 
   7621   return UDir;
   7622 }
   7623 
   7624 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
   7625   // If the scope has an associated entity and the using directive is at
   7626   // namespace or translation unit scope, add the UsingDirectiveDecl into
   7627   // its lookup structure so qualified name lookup can find it.
   7628   DeclContext *Ctx = S->getEntity();
   7629   if (Ctx && !Ctx->isFunctionOrMethod())
   7630     Ctx->addDecl(UDir);
   7631   else
   7632     // Otherwise, it is at block scope. The using-directives will affect lookup
   7633     // only to the end of the scope.
   7634     S->PushUsingDirective(UDir);
   7635 }
   7636 
   7637 
   7638 Decl *Sema::ActOnUsingDeclaration(Scope *S,
   7639                                   AccessSpecifier AS,
   7640                                   bool HasUsingKeyword,
   7641                                   SourceLocation UsingLoc,
   7642                                   CXXScopeSpec &SS,
   7643                                   UnqualifiedId &Name,
   7644                                   AttributeList *AttrList,
   7645                                   bool HasTypenameKeyword,
   7646                                   SourceLocation TypenameLoc) {
   7647   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
   7648 
   7649   switch (Name.getKind()) {
   7650   case UnqualifiedId::IK_ImplicitSelfParam:
   7651   case UnqualifiedId::IK_Identifier:
   7652   case UnqualifiedId::IK_OperatorFunctionId:
   7653   case UnqualifiedId::IK_LiteralOperatorId:
   7654   case UnqualifiedId::IK_ConversionFunctionId:
   7655     break;
   7656 
   7657   case UnqualifiedId::IK_ConstructorName:
   7658   case UnqualifiedId::IK_ConstructorTemplateId:
   7659     // C++11 inheriting constructors.
   7660     Diag(Name.getLocStart(),
   7661          getLangOpts().CPlusPlus11 ?
   7662            diag::warn_cxx98_compat_using_decl_constructor :
   7663            diag::err_using_decl_constructor)
   7664       << SS.getRange();
   7665 
   7666     if (getLangOpts().CPlusPlus11) break;
   7667 
   7668     return nullptr;
   7669 
   7670   case UnqualifiedId::IK_DestructorName:
   7671     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
   7672       << SS.getRange();
   7673     return nullptr;
   7674 
   7675   case UnqualifiedId::IK_TemplateId:
   7676     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
   7677       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
   7678     return nullptr;
   7679   }
   7680 
   7681   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
   7682   DeclarationName TargetName = TargetNameInfo.getName();
   7683   if (!TargetName)
   7684     return nullptr;
   7685 
   7686   // Warn about access declarations.
   7687   if (!HasUsingKeyword) {
   7688     Diag(Name.getLocStart(),
   7689          getLangOpts().CPlusPlus11 ? diag::err_access_decl
   7690                                    : diag::warn_access_decl_deprecated)
   7691       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
   7692   }
   7693 
   7694   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
   7695       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
   7696     return nullptr;
   7697 
   7698   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
   7699                                         TargetNameInfo, AttrList,
   7700                                         /* IsInstantiation */ false,
   7701                                         HasTypenameKeyword, TypenameLoc);
   7702   if (UD)
   7703     PushOnScopeChains(UD, S, /*AddToContext*/ false);
   7704 
   7705   return UD;
   7706 }
   7707 
   7708 /// \brief Determine whether a using declaration considers the given
   7709 /// declarations as "equivalent", e.g., if they are redeclarations of
   7710 /// the same entity or are both typedefs of the same type.
   7711 static bool
   7712 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
   7713   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
   7714     return true;
   7715 
   7716   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
   7717     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
   7718       return Context.hasSameType(TD1->getUnderlyingType(),
   7719                                  TD2->getUnderlyingType());
   7720 
   7721   return false;
   7722 }
   7723 
   7724 
   7725 /// Determines whether to create a using shadow decl for a particular
   7726 /// decl, given the set of decls existing prior to this using lookup.
   7727 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
   7728                                 const LookupResult &Previous,
   7729                                 UsingShadowDecl *&PrevShadow) {
   7730   // Diagnose finding a decl which is not from a base class of the
   7731   // current class.  We do this now because there are cases where this
   7732   // function will silently decide not to build a shadow decl, which
   7733   // will pre-empt further diagnostics.
   7734   //
   7735   // We don't need to do this in C++0x because we do the check once on
   7736   // the qualifier.
   7737   //
   7738   // FIXME: diagnose the following if we care enough:
   7739   //   struct A { int foo; };
   7740   //   struct B : A { using A::foo; };
   7741   //   template <class T> struct C : A {};
   7742   //   template <class T> struct D : C<T> { using B::foo; } // <---
   7743   // This is invalid (during instantiation) in C++03 because B::foo
   7744   // resolves to the using decl in B, which is not a base class of D<T>.
   7745   // We can't diagnose it immediately because C<T> is an unknown
   7746   // specialization.  The UsingShadowDecl in D<T> then points directly
   7747   // to A::foo, which will look well-formed when we instantiate.
   7748   // The right solution is to not collapse the shadow-decl chain.
   7749   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
   7750     DeclContext *OrigDC = Orig->getDeclContext();
   7751 
   7752     // Handle enums and anonymous structs.
   7753     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
   7754     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
   7755     while (OrigRec->isAnonymousStructOrUnion())
   7756       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
   7757 
   7758     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
   7759       if (OrigDC == CurContext) {
   7760         Diag(Using->getLocation(),
   7761              diag::err_using_decl_nested_name_specifier_is_current_class)
   7762           << Using->getQualifierLoc().getSourceRange();
   7763         Diag(Orig->getLocation(), diag::note_using_decl_target);
   7764         return true;
   7765       }
   7766 
   7767       Diag(Using->getQualifierLoc().getBeginLoc(),
   7768            diag::err_using_decl_nested_name_specifier_is_not_base_class)
   7769         << Using->getQualifier()
   7770         << cast<CXXRecordDecl>(CurContext)
   7771         << Using->getQualifierLoc().getSourceRange();
   7772       Diag(Orig->getLocation(), diag::note_using_decl_target);
   7773       return true;
   7774     }
   7775   }
   7776 
   7777   if (Previous.empty()) return false;
   7778 
   7779   NamedDecl *Target = Orig;
   7780   if (isa<UsingShadowDecl>(Target))
   7781     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
   7782 
   7783   // If the target happens to be one of the previous declarations, we
   7784   // don't have a conflict.
   7785   //
   7786   // FIXME: but we might be increasing its access, in which case we
   7787   // should redeclare it.
   7788   NamedDecl *NonTag = nullptr, *Tag = nullptr;
   7789   bool FoundEquivalentDecl = false;
   7790   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
   7791          I != E; ++I) {
   7792     NamedDecl *D = (*I)->getUnderlyingDecl();
   7793     if (IsEquivalentForUsingDecl(Context, D, Target)) {
   7794       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
   7795         PrevShadow = Shadow;
   7796       FoundEquivalentDecl = true;
   7797     }
   7798 
   7799     if (isVisible(D))
   7800       (isa<TagDecl>(D) ? Tag : NonTag) = D;
   7801   }
   7802 
   7803   if (FoundEquivalentDecl)
   7804     return false;
   7805 
   7806   if (FunctionDecl *FD = Target->getAsFunction()) {
   7807     NamedDecl *OldDecl = nullptr;
   7808     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
   7809                           /*IsForUsingDecl*/ true)) {
   7810     case Ovl_Overload:
   7811       return false;
   7812 
   7813     case Ovl_NonFunction:
   7814       Diag(Using->getLocation(), diag::err_using_decl_conflict);
   7815       break;
   7816 
   7817     // We found a decl with the exact signature.
   7818     case Ovl_Match:
   7819       // If we're in a record, we want to hide the target, so we
   7820       // return true (without a diagnostic) to tell the caller not to
   7821       // build a shadow decl.
   7822       if (CurContext->isRecord())
   7823         return true;
   7824 
   7825       // If we're not in a record, this is an error.
   7826       Diag(Using->getLocation(), diag::err_using_decl_conflict);
   7827       break;
   7828     }
   7829 
   7830     Diag(Target->getLocation(), diag::note_using_decl_target);
   7831     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
   7832     return true;
   7833   }
   7834 
   7835   // Target is not a function.
   7836 
   7837   if (isa<TagDecl>(Target)) {
   7838     // No conflict between a tag and a non-tag.
   7839     if (!Tag) return false;
   7840 
   7841     Diag(Using->getLocation(), diag::err_using_decl_conflict);
   7842     Diag(Target->getLocation(), diag::note_using_decl_target);
   7843     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
   7844     return true;
   7845   }
   7846 
   7847   // No conflict between a tag and a non-tag.
   7848   if (!NonTag) return false;
   7849 
   7850   Diag(Using->getLocation(), diag::err_using_decl_conflict);
   7851   Diag(Target->getLocation(), diag::note_using_decl_target);
   7852   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
   7853   return true;
   7854 }
   7855 
   7856 /// Builds a shadow declaration corresponding to a 'using' declaration.
   7857 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
   7858                                             UsingDecl *UD,
   7859                                             NamedDecl *Orig,
   7860                                             UsingShadowDecl *PrevDecl) {
   7861 
   7862   // If we resolved to another shadow declaration, just coalesce them.
   7863   NamedDecl *Target = Orig;
   7864   if (isa<UsingShadowDecl>(Target)) {
   7865     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
   7866     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
   7867   }
   7868 
   7869   UsingShadowDecl *Shadow
   7870     = UsingShadowDecl::Create(Context, CurContext,
   7871                               UD->getLocation(), UD, Target);
   7872   UD->addShadowDecl(Shadow);
   7873 
   7874   Shadow->setAccess(UD->getAccess());
   7875   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
   7876     Shadow->setInvalidDecl();
   7877 
   7878   Shadow->setPreviousDecl(PrevDecl);
   7879 
   7880   if (S)
   7881     PushOnScopeChains(Shadow, S);
   7882   else
   7883     CurContext->addDecl(Shadow);
   7884 
   7885 
   7886   return Shadow;
   7887 }
   7888 
   7889 /// Hides a using shadow declaration.  This is required by the current
   7890 /// using-decl implementation when a resolvable using declaration in a
   7891 /// class is followed by a declaration which would hide or override
   7892 /// one or more of the using decl's targets; for example:
   7893 ///
   7894 ///   struct Base { void foo(int); };
   7895 ///   struct Derived : Base {
   7896 ///     using Base::foo;
   7897 ///     void foo(int);
   7898 ///   };
   7899 ///
   7900 /// The governing language is C++03 [namespace.udecl]p12:
   7901 ///
   7902 ///   When a using-declaration brings names from a base class into a
   7903 ///   derived class scope, member functions in the derived class
   7904 ///   override and/or hide member functions with the same name and
   7905 ///   parameter types in a base class (rather than conflicting).
   7906 ///
   7907 /// There are two ways to implement this:
   7908 ///   (1) optimistically create shadow decls when they're not hidden
   7909 ///       by existing declarations, or
   7910 ///   (2) don't create any shadow decls (or at least don't make them
   7911 ///       visible) until we've fully parsed/instantiated the class.
   7912 /// The problem with (1) is that we might have to retroactively remove
   7913 /// a shadow decl, which requires several O(n) operations because the
   7914 /// decl structures are (very reasonably) not designed for removal.
   7915 /// (2) avoids this but is very fiddly and phase-dependent.
   7916 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
   7917   if (Shadow->getDeclName().getNameKind() ==
   7918         DeclarationName::CXXConversionFunctionName)
   7919     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
   7920 
   7921   // Remove it from the DeclContext...
   7922   Shadow->getDeclContext()->removeDecl(Shadow);
   7923 
   7924   // ...and the scope, if applicable...
   7925   if (S) {
   7926     S->RemoveDecl(Shadow);
   7927     IdResolver.RemoveDecl(Shadow);
   7928   }
   7929 
   7930   // ...and the using decl.
   7931   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
   7932 
   7933   // TODO: complain somehow if Shadow was used.  It shouldn't
   7934   // be possible for this to happen, because...?
   7935 }
   7936 
   7937 /// Find the base specifier for a base class with the given type.
   7938 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
   7939                                                 QualType DesiredBase,
   7940                                                 bool &AnyDependentBases) {
   7941   // Check whether the named type is a direct base class.
   7942   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
   7943   for (auto &Base : Derived->bases()) {
   7944     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
   7945     if (CanonicalDesiredBase == BaseType)
   7946       return &Base;
   7947     if (BaseType->isDependentType())
   7948       AnyDependentBases = true;
   7949   }
   7950   return nullptr;
   7951 }
   7952 
   7953 namespace {
   7954 class UsingValidatorCCC : public CorrectionCandidateCallback {
   7955 public:
   7956   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
   7957                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
   7958       : HasTypenameKeyword(HasTypenameKeyword),
   7959         IsInstantiation(IsInstantiation), OldNNS(NNS),
   7960         RequireMemberOf(RequireMemberOf) {}
   7961 
   7962   bool ValidateCandidate(const TypoCorrection &Candidate) override {
   7963     NamedDecl *ND = Candidate.getCorrectionDecl();
   7964 
   7965     // Keywords are not valid here.
   7966     if (!ND || isa<NamespaceDecl>(ND))
   7967       return false;
   7968 
   7969     // Completely unqualified names are invalid for a 'using' declaration.
   7970     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
   7971       return false;
   7972 
   7973     if (RequireMemberOf) {
   7974       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
   7975       if (FoundRecord && FoundRecord->isInjectedClassName()) {
   7976         // No-one ever wants a using-declaration to name an injected-class-name
   7977         // of a base class, unless they're declaring an inheriting constructor.
   7978         ASTContext &Ctx = ND->getASTContext();
   7979         if (!Ctx.getLangOpts().CPlusPlus11)
   7980           return false;
   7981         QualType FoundType = Ctx.getRecordType(FoundRecord);
   7982 
   7983         // Check that the injected-class-name is named as a member of its own
   7984         // type; we don't want to suggest 'using Derived::Base;', since that
   7985         // means something else.
   7986         NestedNameSpecifier *Specifier =
   7987             Candidate.WillReplaceSpecifier()
   7988                 ? Candidate.getCorrectionSpecifier()
   7989                 : OldNNS;
   7990         if (!Specifier->getAsType() ||
   7991             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
   7992           return false;
   7993 
   7994         // Check that this inheriting constructor declaration actually names a
   7995         // direct base class of the current class.
   7996         bool AnyDependentBases = false;
   7997         if (!findDirectBaseWithType(RequireMemberOf,
   7998                                     Ctx.getRecordType(FoundRecord),
   7999                                     AnyDependentBases) &&
   8000             !AnyDependentBases)
   8001           return false;
   8002       } else {
   8003         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
   8004         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
   8005           return false;
   8006 
   8007         // FIXME: Check that the base class member is accessible?
   8008       }
   8009     } else {
   8010       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
   8011       if (FoundRecord && FoundRecord->isInjectedClassName())
   8012         return false;
   8013     }
   8014 
   8015     if (isa<TypeDecl>(ND))
   8016       return HasTypenameKeyword || !IsInstantiation;
   8017 
   8018     return !HasTypenameKeyword;
   8019   }
   8020 
   8021 private:
   8022   bool HasTypenameKeyword;
   8023   bool IsInstantiation;
   8024   NestedNameSpecifier *OldNNS;
   8025   CXXRecordDecl *RequireMemberOf;
   8026 };
   8027 } // end anonymous namespace
   8028 
   8029 /// Builds a using declaration.
   8030 ///
   8031 /// \param IsInstantiation - Whether this call arises from an
   8032 ///   instantiation of an unresolved using declaration.  We treat
   8033 ///   the lookup differently for these declarations.
   8034 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
   8035                                        SourceLocation UsingLoc,
   8036                                        CXXScopeSpec &SS,
   8037                                        DeclarationNameInfo NameInfo,
   8038                                        AttributeList *AttrList,
   8039                                        bool IsInstantiation,
   8040                                        bool HasTypenameKeyword,
   8041                                        SourceLocation TypenameLoc) {
   8042   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
   8043   SourceLocation IdentLoc = NameInfo.getLoc();
   8044   assert(IdentLoc.isValid() && "Invalid TargetName location.");
   8045 
   8046   // FIXME: We ignore attributes for now.
   8047 
   8048   if (SS.isEmpty()) {
   8049     Diag(IdentLoc, diag::err_using_requires_qualname);
   8050     return nullptr;
   8051   }
   8052 
   8053   // Do the redeclaration lookup in the current scope.
   8054   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
   8055                         ForRedeclaration);
   8056   Previous.setHideTags(false);
   8057   if (S) {
   8058     LookupName(Previous, S);
   8059 
   8060     // It is really dumb that we have to do this.
   8061     LookupResult::Filter F = Previous.makeFilter();
   8062     while (F.hasNext()) {
   8063       NamedDecl *D = F.next();
   8064       if (!isDeclInScope(D, CurContext, S))
   8065         F.erase();
   8066       // If we found a local extern declaration that's not ordinarily visible,
   8067       // and this declaration is being added to a non-block scope, ignore it.
   8068       // We're only checking for scope conflicts here, not also for violations
   8069       // of the linkage rules.
   8070       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
   8071                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
   8072         F.erase();
   8073     }
   8074     F.done();
   8075   } else {
   8076     assert(IsInstantiation && "no scope in non-instantiation");
   8077     assert(CurContext->isRecord() && "scope not record in instantiation");
   8078     LookupQualifiedName(Previous, CurContext);
   8079   }
   8080 
   8081   // Check for invalid redeclarations.
   8082   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
   8083                                   SS, IdentLoc, Previous))
   8084     return nullptr;
   8085 
   8086   // Check for bad qualifiers.
   8087   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
   8088     return nullptr;
   8089 
   8090   DeclContext *LookupContext = computeDeclContext(SS);
   8091   NamedDecl *D;
   8092   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
   8093   if (!LookupContext) {
   8094     if (HasTypenameKeyword) {
   8095       // FIXME: not all declaration name kinds are legal here
   8096       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
   8097                                               UsingLoc, TypenameLoc,
   8098                                               QualifierLoc,
   8099                                               IdentLoc, NameInfo.getName());
   8100     } else {
   8101       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
   8102                                            QualifierLoc, NameInfo);
   8103     }
   8104     D->setAccess(AS);
   8105     CurContext->addDecl(D);
   8106     return D;
   8107   }
   8108 
   8109   auto Build = [&](bool Invalid) {
   8110     UsingDecl *UD =
   8111         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
   8112                           HasTypenameKeyword);
   8113     UD->setAccess(AS);
   8114     CurContext->addDecl(UD);
   8115     UD->setInvalidDecl(Invalid);
   8116     return UD;
   8117   };
   8118   auto BuildInvalid = [&]{ return Build(true); };
   8119   auto BuildValid = [&]{ return Build(false); };
   8120 
   8121   if (RequireCompleteDeclContext(SS, LookupContext))
   8122     return BuildInvalid();
   8123 
   8124   // Look up the target name.
   8125   LookupResult R(*this, NameInfo, LookupOrdinaryName);
   8126 
   8127   // Unlike most lookups, we don't always want to hide tag
   8128   // declarations: tag names are visible through the using declaration
   8129   // even if hidden by ordinary names, *except* in a dependent context
   8130   // where it's important for the sanity of two-phase lookup.
   8131   if (!IsInstantiation)
   8132     R.setHideTags(false);
   8133 
   8134   // For the purposes of this lookup, we have a base object type
   8135   // equal to that of the current context.
   8136   if (CurContext->isRecord()) {
   8137     R.setBaseObjectType(
   8138                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
   8139   }
   8140 
   8141   LookupQualifiedName(R, LookupContext);
   8142 
   8143   // Try to correct typos if possible. If constructor name lookup finds no
   8144   // results, that means the named class has no explicit constructors, and we
   8145   // suppressed declaring implicit ones (probably because it's dependent or
   8146   // invalid).
   8147   if (R.empty() &&
   8148       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
   8149     if (TypoCorrection Corrected = CorrectTypo(
   8150             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
   8151             llvm::make_unique<UsingValidatorCCC>(
   8152                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
   8153                 dyn_cast<CXXRecordDecl>(CurContext)),
   8154             CTK_ErrorRecovery)) {
   8155       // We reject any correction for which ND would be NULL.
   8156       NamedDecl *ND = Corrected.getCorrectionDecl();
   8157 
   8158       // We reject candidates where DroppedSpecifier == true, hence the
   8159       // literal '0' below.
   8160       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
   8161                                 << NameInfo.getName() << LookupContext << 0
   8162                                 << SS.getRange());
   8163 
   8164       // If we corrected to an inheriting constructor, handle it as one.
   8165       auto *RD = dyn_cast<CXXRecordDecl>(ND);
   8166       if (RD && RD->isInjectedClassName()) {
   8167         // Fix up the information we'll use to build the using declaration.
   8168         if (Corrected.WillReplaceSpecifier()) {
   8169           NestedNameSpecifierLocBuilder Builder;
   8170           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
   8171                               QualifierLoc.getSourceRange());
   8172           QualifierLoc = Builder.getWithLocInContext(Context);
   8173         }
   8174 
   8175         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
   8176             Context.getCanonicalType(Context.getRecordType(RD))));
   8177         NameInfo.setNamedTypeInfo(nullptr);
   8178         for (auto *Ctor : LookupConstructors(RD))
   8179           R.addDecl(Ctor);
   8180       } else {
   8181         // FIXME: Pick up all the declarations if we found an overloaded function.
   8182         R.addDecl(ND);
   8183       }
   8184     } else {
   8185       Diag(IdentLoc, diag::err_no_member)
   8186         << NameInfo.getName() << LookupContext << SS.getRange();
   8187       return BuildInvalid();
   8188     }
   8189   }
   8190 
   8191   if (R.isAmbiguous())
   8192     return BuildInvalid();
   8193 
   8194   if (HasTypenameKeyword) {
   8195     // If we asked for a typename and got a non-type decl, error out.
   8196     if (!R.getAsSingle<TypeDecl>()) {
   8197       Diag(IdentLoc, diag::err_using_typename_non_type);
   8198       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
   8199         Diag((*I)->getUnderlyingDecl()->getLocation(),
   8200              diag::note_using_decl_target);
   8201       return BuildInvalid();
   8202     }
   8203   } else {
   8204     // If we asked for a non-typename and we got a type, error out,
   8205     // but only if this is an instantiation of an unresolved using
   8206     // decl.  Otherwise just silently find the type name.
   8207     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
   8208       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
   8209       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
   8210       return BuildInvalid();
   8211     }
   8212   }
   8213 
   8214   // C++0x N2914 [namespace.udecl]p6:
   8215   // A using-declaration shall not name a namespace.
   8216   if (R.getAsSingle<NamespaceDecl>()) {
   8217     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
   8218       << SS.getRange();
   8219     return BuildInvalid();
   8220   }
   8221 
   8222   UsingDecl *UD = BuildValid();
   8223 
   8224   // The normal rules do not apply to inheriting constructor declarations.
   8225   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
   8226     // Suppress access diagnostics; the access check is instead performed at the
   8227     // point of use for an inheriting constructor.
   8228     R.suppressDiagnostics();
   8229     CheckInheritingConstructorUsingDecl(UD);
   8230     return UD;
   8231   }
   8232 
   8233   // Otherwise, look up the target name.
   8234 
   8235   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
   8236     UsingShadowDecl *PrevDecl = nullptr;
   8237     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
   8238       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
   8239   }
   8240 
   8241   return UD;
   8242 }
   8243 
   8244 /// Additional checks for a using declaration referring to a constructor name.
   8245 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
   8246   assert(!UD->hasTypename() && "expecting a constructor name");
   8247 
   8248   const Type *SourceType = UD->getQualifier()->getAsType();
   8249   assert(SourceType &&
   8250          "Using decl naming constructor doesn't have type in scope spec.");
   8251   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
   8252 
   8253   // Check whether the named type is a direct base class.
   8254   bool AnyDependentBases = false;
   8255   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
   8256                                       AnyDependentBases);
   8257   if (!Base && !AnyDependentBases) {
   8258     Diag(UD->getUsingLoc(),
   8259          diag::err_using_decl_constructor_not_in_direct_base)
   8260       << UD->getNameInfo().getSourceRange()
   8261       << QualType(SourceType, 0) << TargetClass;
   8262     UD->setInvalidDecl();
   8263     return true;
   8264   }
   8265 
   8266   if (Base)
   8267     Base->setInheritConstructors();
   8268 
   8269   return false;
   8270 }
   8271 
   8272 /// Checks that the given using declaration is not an invalid
   8273 /// redeclaration.  Note that this is checking only for the using decl
   8274 /// itself, not for any ill-formedness among the UsingShadowDecls.
   8275 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
   8276                                        bool HasTypenameKeyword,
   8277                                        const CXXScopeSpec &SS,
   8278                                        SourceLocation NameLoc,
   8279                                        const LookupResult &Prev) {
   8280   // C++03 [namespace.udecl]p8:
   8281   // C++0x [namespace.udecl]p10:
   8282   //   A using-declaration is a declaration and can therefore be used
   8283   //   repeatedly where (and only where) multiple declarations are
   8284   //   allowed.
   8285   //
   8286   // That's in non-member contexts.
   8287   if (!CurContext->getRedeclContext()->isRecord())
   8288     return false;
   8289 
   8290   NestedNameSpecifier *Qual = SS.getScopeRep();
   8291 
   8292   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
   8293     NamedDecl *D = *I;
   8294 
   8295     bool DTypename;
   8296     NestedNameSpecifier *DQual;
   8297     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
   8298       DTypename = UD->hasTypename();
   8299       DQual = UD->getQualifier();
   8300     } else if (UnresolvedUsingValueDecl *UD
   8301                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
   8302       DTypename = false;
   8303       DQual = UD->getQualifier();
   8304     } else if (UnresolvedUsingTypenameDecl *UD
   8305                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
   8306       DTypename = true;
   8307       DQual = UD->getQualifier();
   8308     } else continue;
   8309 
   8310     // using decls differ if one says 'typename' and the other doesn't.
   8311     // FIXME: non-dependent using decls?
   8312     if (HasTypenameKeyword != DTypename) continue;
   8313 
   8314     // using decls differ if they name different scopes (but note that
   8315     // template instantiation can cause this check to trigger when it
   8316     // didn't before instantiation).
   8317     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
   8318         Context.getCanonicalNestedNameSpecifier(DQual))
   8319       continue;
   8320 
   8321     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
   8322     Diag(D->getLocation(), diag::note_using_decl) << 1;
   8323     return true;
   8324   }
   8325 
   8326   return false;
   8327 }
   8328 
   8329 
   8330 /// Checks that the given nested-name qualifier used in a using decl
   8331 /// in the current context is appropriately related to the current
   8332 /// scope.  If an error is found, diagnoses it and returns true.
   8333 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
   8334                                    const CXXScopeSpec &SS,
   8335                                    const DeclarationNameInfo &NameInfo,
   8336                                    SourceLocation NameLoc) {
   8337   DeclContext *NamedContext = computeDeclContext(SS);
   8338 
   8339   if (!CurContext->isRecord()) {
   8340     // C++03 [namespace.udecl]p3:
   8341     // C++0x [namespace.udecl]p8:
   8342     //   A using-declaration for a class member shall be a member-declaration.
   8343 
   8344     // If we weren't able to compute a valid scope, it must be a
   8345     // dependent class scope.
   8346     if (!NamedContext || NamedContext->isRecord()) {
   8347       auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
   8348       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
   8349         RD = nullptr;
   8350 
   8351       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
   8352         << SS.getRange();
   8353 
   8354       // If we have a complete, non-dependent source type, try to suggest a
   8355       // way to get the same effect.
   8356       if (!RD)
   8357         return true;
   8358 
   8359       // Find what this using-declaration was referring to.
   8360       LookupResult R(*this, NameInfo, LookupOrdinaryName);
   8361       R.setHideTags(false);
   8362       R.suppressDiagnostics();
   8363       LookupQualifiedName(R, RD);
   8364 
   8365       if (R.getAsSingle<TypeDecl>()) {
   8366         if (getLangOpts().CPlusPlus11) {
   8367           // Convert 'using X::Y;' to 'using Y = X::Y;'.
   8368           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
   8369             << 0 // alias declaration
   8370             << FixItHint::CreateInsertion(SS.getBeginLoc(),
   8371                                           NameInfo.getName().getAsString() +
   8372                                               " = ");
   8373         } else {
   8374           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
   8375           SourceLocation InsertLoc =
   8376               getLocForEndOfToken(NameInfo.getLocEnd());
   8377           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
   8378             << 1 // typedef declaration
   8379             << FixItHint::CreateReplacement(UsingLoc, "typedef")
   8380             << FixItHint::CreateInsertion(
   8381                    InsertLoc, " " + NameInfo.getName().getAsString());
   8382         }
   8383       } else if (R.getAsSingle<VarDecl>()) {
   8384         // Don't provide a fixit outside C++11 mode; we don't want to suggest
   8385         // repeating the type of the static data member here.
   8386         FixItHint FixIt;
   8387         if (getLangOpts().CPlusPlus11) {
   8388           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
   8389           FixIt = FixItHint::CreateReplacement(
   8390               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
   8391         }
   8392 
   8393         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
   8394           << 2 // reference declaration
   8395           << FixIt;
   8396       }
   8397       return true;
   8398     }
   8399 
   8400     // Otherwise, everything is known to be fine.
   8401     return false;
   8402   }
   8403 
   8404   // The current scope is a record.
   8405 
   8406   // If the named context is dependent, we can't decide much.
   8407   if (!NamedContext) {
   8408     // FIXME: in C++0x, we can diagnose if we can prove that the
   8409     // nested-name-specifier does not refer to a base class, which is
   8410     // still possible in some cases.
   8411 
   8412     // Otherwise we have to conservatively report that things might be
   8413     // okay.
   8414     return false;
   8415   }
   8416 
   8417   if (!NamedContext->isRecord()) {
   8418     // Ideally this would point at the last name in the specifier,
   8419     // but we don't have that level of source info.
   8420     Diag(SS.getRange().getBegin(),
   8421          diag::err_using_decl_nested_name_specifier_is_not_class)
   8422       << SS.getScopeRep() << SS.getRange();
   8423     return true;
   8424   }
   8425 
   8426   if (!NamedContext->isDependentContext() &&
   8427       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
   8428     return true;
   8429 
   8430   if (getLangOpts().CPlusPlus11) {
   8431     // C++0x [namespace.udecl]p3:
   8432     //   In a using-declaration used as a member-declaration, the
   8433     //   nested-name-specifier shall name a base class of the class
   8434     //   being defined.
   8435 
   8436     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
   8437                                  cast<CXXRecordDecl>(NamedContext))) {
   8438       if (CurContext == NamedContext) {
   8439         Diag(NameLoc,
   8440              diag::err_using_decl_nested_name_specifier_is_current_class)
   8441           << SS.getRange();
   8442         return true;
   8443       }
   8444 
   8445       Diag(SS.getRange().getBegin(),
   8446            diag::err_using_decl_nested_name_specifier_is_not_base_class)
   8447         << SS.getScopeRep()
   8448         << cast<CXXRecordDecl>(CurContext)
   8449         << SS.getRange();
   8450       return true;
   8451     }
   8452 
   8453     return false;
   8454   }
   8455 
   8456   // C++03 [namespace.udecl]p4:
   8457   //   A using-declaration used as a member-declaration shall refer
   8458   //   to a member of a base class of the class being defined [etc.].
   8459 
   8460   // Salient point: SS doesn't have to name a base class as long as
   8461   // lookup only finds members from base classes.  Therefore we can
   8462   // diagnose here only if we can prove that that can't happen,
   8463   // i.e. if the class hierarchies provably don't intersect.
   8464 
   8465   // TODO: it would be nice if "definitely valid" results were cached
   8466   // in the UsingDecl and UsingShadowDecl so that these checks didn't
   8467   // need to be repeated.
   8468 
   8469   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
   8470   auto Collect = [&Bases](const CXXRecordDecl *Base) {
   8471     Bases.insert(Base);
   8472     return true;
   8473   };
   8474 
   8475   // Collect all bases. Return false if we find a dependent base.
   8476   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
   8477     return false;
   8478 
   8479   // Returns true if the base is dependent or is one of the accumulated base
   8480   // classes.
   8481   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
   8482     return !Bases.count(Base);
   8483   };
   8484 
   8485   // Return false if the class has a dependent base or if it or one
   8486   // of its bases is present in the base set of the current context.
   8487   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
   8488       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
   8489     return false;
   8490 
   8491   Diag(SS.getRange().getBegin(),
   8492        diag::err_using_decl_nested_name_specifier_is_not_base_class)
   8493     << SS.getScopeRep()
   8494     << cast<CXXRecordDecl>(CurContext)
   8495     << SS.getRange();
   8496 
   8497   return true;
   8498 }
   8499 
   8500 Decl *Sema::ActOnAliasDeclaration(Scope *S,
   8501                                   AccessSpecifier AS,
   8502                                   MultiTemplateParamsArg TemplateParamLists,
   8503                                   SourceLocation UsingLoc,
   8504                                   UnqualifiedId &Name,
   8505                                   AttributeList *AttrList,
   8506                                   TypeResult Type,
   8507                                   Decl *DeclFromDeclSpec) {
   8508   // Skip up to the relevant declaration scope.
   8509   while (S->isTemplateParamScope())
   8510     S = S->getParent();
   8511   assert((S->getFlags() & Scope::DeclScope) &&
   8512          "got alias-declaration outside of declaration scope");
   8513 
   8514   if (Type.isInvalid())
   8515     return nullptr;
   8516 
   8517   bool Invalid = false;
   8518   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
   8519   TypeSourceInfo *TInfo = nullptr;
   8520   GetTypeFromParser(Type.get(), &TInfo);
   8521 
   8522   if (DiagnoseClassNameShadow(CurContext, NameInfo))
   8523     return nullptr;
   8524 
   8525   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
   8526                                       UPPC_DeclarationType)) {
   8527     Invalid = true;
   8528     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
   8529                                              TInfo->getTypeLoc().getBeginLoc());
   8530   }
   8531 
   8532   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
   8533   LookupName(Previous, S);
   8534 
   8535   // Warn about shadowing the name of a template parameter.
   8536   if (Previous.isSingleResult() &&
   8537       Previous.getFoundDecl()->isTemplateParameter()) {
   8538     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
   8539     Previous.clear();
   8540   }
   8541 
   8542   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
   8543          "name in alias declaration must be an identifier");
   8544   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
   8545                                                Name.StartLocation,
   8546                                                Name.Identifier, TInfo);
   8547 
   8548   NewTD->setAccess(AS);
   8549 
   8550   if (Invalid)
   8551     NewTD->setInvalidDecl();
   8552 
   8553   ProcessDeclAttributeList(S, NewTD, AttrList);
   8554 
   8555   CheckTypedefForVariablyModifiedType(S, NewTD);
   8556   Invalid |= NewTD->isInvalidDecl();
   8557 
   8558   bool Redeclaration = false;
   8559 
   8560   NamedDecl *NewND;
   8561   if (TemplateParamLists.size()) {
   8562     TypeAliasTemplateDecl *OldDecl = nullptr;
   8563     TemplateParameterList *OldTemplateParams = nullptr;
   8564 
   8565     if (TemplateParamLists.size() != 1) {
   8566       Diag(UsingLoc, diag::err_alias_template_extra_headers)
   8567         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
   8568          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
   8569     }
   8570     TemplateParameterList *TemplateParams = TemplateParamLists[0];
   8571 
   8572     // Only consider previous declarations in the same scope.
   8573     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
   8574                          /*ExplicitInstantiationOrSpecialization*/false);
   8575     if (!Previous.empty()) {
   8576       Redeclaration = true;
   8577 
   8578       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
   8579       if (!OldDecl && !Invalid) {
   8580         Diag(UsingLoc, diag::err_redefinition_different_kind)
   8581           << Name.Identifier;
   8582 
   8583         NamedDecl *OldD = Previous.getRepresentativeDecl();
   8584         if (OldD->getLocation().isValid())
   8585           Diag(OldD->getLocation(), diag::note_previous_definition);
   8586 
   8587         Invalid = true;
   8588       }
   8589 
   8590       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
   8591         if (TemplateParameterListsAreEqual(TemplateParams,
   8592                                            OldDecl->getTemplateParameters(),
   8593                                            /*Complain=*/true,
   8594                                            TPL_TemplateMatch))
   8595           OldTemplateParams = OldDecl->getTemplateParameters();
   8596         else
   8597           Invalid = true;
   8598 
   8599         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
   8600         if (!Invalid &&
   8601             !Context.hasSameType(OldTD->getUnderlyingType(),
   8602                                  NewTD->getUnderlyingType())) {
   8603           // FIXME: The C++0x standard does not clearly say this is ill-formed,
   8604           // but we can't reasonably accept it.
   8605           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
   8606             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
   8607           if (OldTD->getLocation().isValid())
   8608             Diag(OldTD->getLocation(), diag::note_previous_definition);
   8609           Invalid = true;
   8610         }
   8611       }
   8612     }
   8613 
   8614     // Merge any previous default template arguments into our parameters,
   8615     // and check the parameter list.
   8616     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
   8617                                    TPC_TypeAliasTemplate))
   8618       return nullptr;
   8619 
   8620     TypeAliasTemplateDecl *NewDecl =
   8621       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
   8622                                     Name.Identifier, TemplateParams,
   8623                                     NewTD);
   8624     NewTD->setDescribedAliasTemplate(NewDecl);
   8625 
   8626     NewDecl->setAccess(AS);
   8627 
   8628     if (Invalid)
   8629       NewDecl->setInvalidDecl();
   8630     else if (OldDecl)
   8631       NewDecl->setPreviousDecl(OldDecl);
   8632 
   8633     NewND = NewDecl;
   8634   } else {
   8635     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
   8636       setTagNameForLinkagePurposes(TD, NewTD);
   8637       handleTagNumbering(TD, S);
   8638     }
   8639     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
   8640     NewND = NewTD;
   8641   }
   8642 
   8643   if (!Redeclaration)
   8644     PushOnScopeChains(NewND, S);
   8645 
   8646   ActOnDocumentableDecl(NewND);
   8647   return NewND;
   8648 }
   8649 
   8650 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
   8651                                    SourceLocation AliasLoc,
   8652                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
   8653                                    SourceLocation IdentLoc,
   8654                                    IdentifierInfo *Ident) {
   8655 
   8656   // Lookup the namespace name.
   8657   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
   8658   LookupParsedName(R, S, &SS);
   8659 
   8660   if (R.isAmbiguous())
   8661     return nullptr;
   8662 
   8663   if (R.empty()) {
   8664     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
   8665       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
   8666       return nullptr;
   8667     }
   8668   }
   8669   assert(!R.isAmbiguous() && !R.empty());
   8670   NamedDecl *ND = R.getFoundDecl();
   8671 
   8672   // Check if we have a previous declaration with the same name.
   8673   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
   8674                      ForRedeclaration);
   8675   LookupName(PrevR, S);
   8676 
   8677   // Check we're not shadowing a template parameter.
   8678   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
   8679     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
   8680     PrevR.clear();
   8681   }
   8682 
   8683   // Filter out any other lookup result from an enclosing scope.
   8684   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
   8685                        /*AllowInlineNamespace*/false);
   8686 
   8687   // Find the previous declaration and check that we can redeclare it.
   8688   NamespaceAliasDecl *Prev = nullptr;
   8689   if (NamedDecl *PrevDecl = PrevR.getAsSingle<NamedDecl>()) {
   8690     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
   8691       // We already have an alias with the same name that points to the same
   8692       // namespace; check that it matches.
   8693       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
   8694         Prev = AD;
   8695       } else if (isVisible(PrevDecl)) {
   8696         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
   8697           << Alias;
   8698         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
   8699           << AD->getNamespace();
   8700         return nullptr;
   8701       }
   8702     } else if (isVisible(PrevDecl)) {
   8703       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
   8704                             ? diag::err_redefinition
   8705                             : diag::err_redefinition_different_kind;
   8706       Diag(AliasLoc, DiagID) << Alias;
   8707       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   8708       return nullptr;
   8709     }
   8710   }
   8711 
   8712   // The use of a nested name specifier may trigger deprecation warnings.
   8713   DiagnoseUseOfDecl(ND, IdentLoc);
   8714 
   8715   NamespaceAliasDecl *AliasDecl =
   8716     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
   8717                                Alias, SS.getWithLocInContext(Context),
   8718                                IdentLoc, ND);
   8719   if (Prev)
   8720     AliasDecl->setPreviousDecl(Prev);
   8721 
   8722   PushOnScopeChains(AliasDecl, S);
   8723   return AliasDecl;
   8724 }
   8725 
   8726 Sema::ImplicitExceptionSpecification
   8727 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
   8728                                                CXXMethodDecl *MD) {
   8729   CXXRecordDecl *ClassDecl = MD->getParent();
   8730 
   8731   // C++ [except.spec]p14:
   8732   //   An implicitly declared special member function (Clause 12) shall have an
   8733   //   exception-specification. [...]
   8734   ImplicitExceptionSpecification ExceptSpec(*this);
   8735   if (ClassDecl->isInvalidDecl())
   8736     return ExceptSpec;
   8737 
   8738   // Direct base-class constructors.
   8739   for (const auto &B : ClassDecl->bases()) {
   8740     if (B.isVirtual()) // Handled below.
   8741       continue;
   8742 
   8743     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
   8744       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   8745       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
   8746       // If this is a deleted function, add it anyway. This might be conformant
   8747       // with the standard. This might not. I'm not sure. It might not matter.
   8748       if (Constructor)
   8749         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
   8750     }
   8751   }
   8752 
   8753   // Virtual base-class constructors.
   8754   for (const auto &B : ClassDecl->vbases()) {
   8755     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
   8756       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   8757       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
   8758       // If this is a deleted function, add it anyway. This might be conformant
   8759       // with the standard. This might not. I'm not sure. It might not matter.
   8760       if (Constructor)
   8761         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
   8762     }
   8763   }
   8764 
   8765   // Field constructors.
   8766   for (const auto *F : ClassDecl->fields()) {
   8767     if (F->hasInClassInitializer()) {
   8768       if (Expr *E = F->getInClassInitializer())
   8769         ExceptSpec.CalledExpr(E);
   8770     } else if (const RecordType *RecordTy
   8771               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
   8772       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
   8773       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
   8774       // If this is a deleted function, add it anyway. This might be conformant
   8775       // with the standard. This might not. I'm not sure. It might not matter.
   8776       // In particular, the problem is that this function never gets called. It
   8777       // might just be ill-formed because this function attempts to refer to
   8778       // a deleted function here.
   8779       if (Constructor)
   8780         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
   8781     }
   8782   }
   8783 
   8784   return ExceptSpec;
   8785 }
   8786 
   8787 Sema::ImplicitExceptionSpecification
   8788 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
   8789   CXXRecordDecl *ClassDecl = CD->getParent();
   8790 
   8791   // C++ [except.spec]p14:
   8792   //   An inheriting constructor [...] shall have an exception-specification. [...]
   8793   ImplicitExceptionSpecification ExceptSpec(*this);
   8794   if (ClassDecl->isInvalidDecl())
   8795     return ExceptSpec;
   8796 
   8797   // Inherited constructor.
   8798   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
   8799   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
   8800   // FIXME: Copying or moving the parameters could add extra exceptions to the
   8801   // set, as could the default arguments for the inherited constructor. This
   8802   // will be addressed when we implement the resolution of core issue 1351.
   8803   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
   8804 
   8805   // Direct base-class constructors.
   8806   for (const auto &B : ClassDecl->bases()) {
   8807     if (B.isVirtual()) // Handled below.
   8808       continue;
   8809 
   8810     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
   8811       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   8812       if (BaseClassDecl == InheritedDecl)
   8813         continue;
   8814       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
   8815       if (Constructor)
   8816         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
   8817     }
   8818   }
   8819 
   8820   // Virtual base-class constructors.
   8821   for (const auto &B : ClassDecl->vbases()) {
   8822     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
   8823       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   8824       if (BaseClassDecl == InheritedDecl)
   8825         continue;
   8826       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
   8827       if (Constructor)
   8828         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
   8829     }
   8830   }
   8831 
   8832   // Field constructors.
   8833   for (const auto *F : ClassDecl->fields()) {
   8834     if (F->hasInClassInitializer()) {
   8835       if (Expr *E = F->getInClassInitializer())
   8836         ExceptSpec.CalledExpr(E);
   8837     } else if (const RecordType *RecordTy
   8838               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
   8839       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
   8840       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
   8841       if (Constructor)
   8842         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
   8843     }
   8844   }
   8845 
   8846   return ExceptSpec;
   8847 }
   8848 
   8849 namespace {
   8850 /// RAII object to register a special member as being currently declared.
   8851 struct DeclaringSpecialMember {
   8852   Sema &S;
   8853   Sema::SpecialMemberDecl D;
   8854   bool WasAlreadyBeingDeclared;
   8855 
   8856   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
   8857     : S(S), D(RD, CSM) {
   8858     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
   8859     if (WasAlreadyBeingDeclared)
   8860       // This almost never happens, but if it does, ensure that our cache
   8861       // doesn't contain a stale result.
   8862       S.SpecialMemberCache.clear();
   8863 
   8864     // FIXME: Register a note to be produced if we encounter an error while
   8865     // declaring the special member.
   8866   }
   8867   ~DeclaringSpecialMember() {
   8868     if (!WasAlreadyBeingDeclared)
   8869       S.SpecialMembersBeingDeclared.erase(D);
   8870   }
   8871 
   8872   /// \brief Are we already trying to declare this special member?
   8873   bool isAlreadyBeingDeclared() const {
   8874     return WasAlreadyBeingDeclared;
   8875   }
   8876 };
   8877 }
   8878 
   8879 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
   8880                                                      CXXRecordDecl *ClassDecl) {
   8881   // C++ [class.ctor]p5:
   8882   //   A default constructor for a class X is a constructor of class X
   8883   //   that can be called without an argument. If there is no
   8884   //   user-declared constructor for class X, a default constructor is
   8885   //   implicitly declared. An implicitly-declared default constructor
   8886   //   is an inline public member of its class.
   8887   assert(ClassDecl->needsImplicitDefaultConstructor() &&
   8888          "Should not build implicit default constructor!");
   8889 
   8890   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
   8891   if (DSM.isAlreadyBeingDeclared())
   8892     return nullptr;
   8893 
   8894   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   8895                                                      CXXDefaultConstructor,
   8896                                                      false);
   8897 
   8898   // Create the actual constructor declaration.
   8899   CanQualType ClassType
   8900     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
   8901   SourceLocation ClassLoc = ClassDecl->getLocation();
   8902   DeclarationName Name
   8903     = Context.DeclarationNames.getCXXConstructorName(ClassType);
   8904   DeclarationNameInfo NameInfo(Name, ClassLoc);
   8905   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
   8906       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
   8907       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
   8908       /*isImplicitlyDeclared=*/true, Constexpr);
   8909   DefaultCon->setAccess(AS_public);
   8910   DefaultCon->setDefaulted();
   8911 
   8912   if (getLangOpts().CUDA) {
   8913     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
   8914                                             DefaultCon,
   8915                                             /* ConstRHS */ false,
   8916                                             /* Diagnose */ false);
   8917   }
   8918 
   8919   // Build an exception specification pointing back at this constructor.
   8920   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
   8921   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
   8922 
   8923   // We don't need to use SpecialMemberIsTrivial here; triviality for default
   8924   // constructors is easy to compute.
   8925   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
   8926 
   8927   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
   8928     SetDeclDeleted(DefaultCon, ClassLoc);
   8929 
   8930   // Note that we have declared this constructor.
   8931   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
   8932 
   8933   if (Scope *S = getScopeForContext(ClassDecl))
   8934     PushOnScopeChains(DefaultCon, S, false);
   8935   ClassDecl->addDecl(DefaultCon);
   8936 
   8937   return DefaultCon;
   8938 }
   8939 
   8940 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
   8941                                             CXXConstructorDecl *Constructor) {
   8942   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
   8943           !Constructor->doesThisDeclarationHaveABody() &&
   8944           !Constructor->isDeleted()) &&
   8945     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
   8946 
   8947   CXXRecordDecl *ClassDecl = Constructor->getParent();
   8948   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
   8949 
   8950   SynthesizedFunctionScope Scope(*this, Constructor);
   8951   DiagnosticErrorTrap Trap(Diags);
   8952   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
   8953       Trap.hasErrorOccurred()) {
   8954     Diag(CurrentLocation, diag::note_member_synthesized_at)
   8955       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
   8956     Constructor->setInvalidDecl();
   8957     return;
   8958   }
   8959 
   8960   // The exception specification is needed because we are defining the
   8961   // function.
   8962   ResolveExceptionSpec(CurrentLocation,
   8963                        Constructor->getType()->castAs<FunctionProtoType>());
   8964 
   8965   SourceLocation Loc = Constructor->getLocEnd().isValid()
   8966                            ? Constructor->getLocEnd()
   8967                            : Constructor->getLocation();
   8968   Constructor->setBody(new (Context) CompoundStmt(Loc));
   8969 
   8970   Constructor->markUsed(Context);
   8971   MarkVTableUsed(CurrentLocation, ClassDecl);
   8972 
   8973   if (ASTMutationListener *L = getASTMutationListener()) {
   8974     L->CompletedImplicitDefinition(Constructor);
   8975   }
   8976 
   8977   DiagnoseUninitializedFields(*this, Constructor);
   8978 }
   8979 
   8980 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
   8981   // Perform any delayed checks on exception specifications.
   8982   CheckDelayedMemberExceptionSpecs();
   8983 }
   8984 
   8985 namespace {
   8986 /// Information on inheriting constructors to declare.
   8987 class InheritingConstructorInfo {
   8988 public:
   8989   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
   8990       : SemaRef(SemaRef), Derived(Derived) {
   8991     // Mark the constructors that we already have in the derived class.
   8992     //
   8993     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
   8994     //   unless there is a user-declared constructor with the same signature in
   8995     //   the class where the using-declaration appears.
   8996     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
   8997   }
   8998 
   8999   void inheritAll(CXXRecordDecl *RD) {
   9000     visitAll(RD, &InheritingConstructorInfo::inherit);
   9001   }
   9002 
   9003 private:
   9004   /// Information about an inheriting constructor.
   9005   struct InheritingConstructor {
   9006     InheritingConstructor()
   9007       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
   9008 
   9009     /// If \c true, a constructor with this signature is already declared
   9010     /// in the derived class.
   9011     bool DeclaredInDerived;
   9012 
   9013     /// The constructor which is inherited.
   9014     const CXXConstructorDecl *BaseCtor;
   9015 
   9016     /// The derived constructor we declared.
   9017     CXXConstructorDecl *DerivedCtor;
   9018   };
   9019 
   9020   /// Inheriting constructors with a given canonical type. There can be at
   9021   /// most one such non-template constructor, and any number of templated
   9022   /// constructors.
   9023   struct InheritingConstructorsForType {
   9024     InheritingConstructor NonTemplate;
   9025     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
   9026         Templates;
   9027 
   9028     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
   9029       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
   9030         TemplateParameterList *ParamList = FTD->getTemplateParameters();
   9031         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
   9032           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
   9033                                                false, S.TPL_TemplateMatch))
   9034             return Templates[I].second;
   9035         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
   9036         return Templates.back().second;
   9037       }
   9038 
   9039       return NonTemplate;
   9040     }
   9041   };
   9042 
   9043   /// Get or create the inheriting constructor record for a constructor.
   9044   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
   9045                                   QualType CtorType) {
   9046     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
   9047         .getEntry(SemaRef, Ctor);
   9048   }
   9049 
   9050   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
   9051 
   9052   /// Process all constructors for a class.
   9053   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
   9054     for (const auto *Ctor : RD->ctors())
   9055       (this->*Callback)(Ctor);
   9056     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
   9057              I(RD->decls_begin()), E(RD->decls_end());
   9058          I != E; ++I) {
   9059       const FunctionDecl *FD = (*I)->getTemplatedDecl();
   9060       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
   9061         (this->*Callback)(CD);
   9062     }
   9063   }
   9064 
   9065   /// Note that a constructor (or constructor template) was declared in Derived.
   9066   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
   9067     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
   9068   }
   9069 
   9070   /// Inherit a single constructor.
   9071   void inherit(const CXXConstructorDecl *Ctor) {
   9072     const FunctionProtoType *CtorType =
   9073         Ctor->getType()->castAs<FunctionProtoType>();
   9074     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
   9075     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
   9076 
   9077     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
   9078 
   9079     // Core issue (no number yet): the ellipsis is always discarded.
   9080     if (EPI.Variadic) {
   9081       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
   9082       SemaRef.Diag(Ctor->getLocation(),
   9083                    diag::note_using_decl_constructor_ellipsis);
   9084       EPI.Variadic = false;
   9085     }
   9086 
   9087     // Declare a constructor for each number of parameters.
   9088     //
   9089     // C++11 [class.inhctor]p1:
   9090     //   The candidate set of inherited constructors from the class X named in
   9091     //   the using-declaration consists of [... modulo defects ...] for each
   9092     //   constructor or constructor template of X, the set of constructors or
   9093     //   constructor templates that results from omitting any ellipsis parameter
   9094     //   specification and successively omitting parameters with a default
   9095     //   argument from the end of the parameter-type-list
   9096     unsigned MinParams = minParamsToInherit(Ctor);
   9097     unsigned Params = Ctor->getNumParams();
   9098     if (Params >= MinParams) {
   9099       do
   9100         declareCtor(UsingLoc, Ctor,
   9101                     SemaRef.Context.getFunctionType(
   9102                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
   9103       while (Params > MinParams &&
   9104              Ctor->getParamDecl(--Params)->hasDefaultArg());
   9105     }
   9106   }
   9107 
   9108   /// Find the using-declaration which specified that we should inherit the
   9109   /// constructors of \p Base.
   9110   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
   9111     // No fancy lookup required; just look for the base constructor name
   9112     // directly within the derived class.
   9113     ASTContext &Context = SemaRef.Context;
   9114     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
   9115         Context.getCanonicalType(Context.getRecordType(Base)));
   9116     DeclContext::lookup_result Decls = Derived->lookup(Name);
   9117     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
   9118   }
   9119 
   9120   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
   9121     // C++11 [class.inhctor]p3:
   9122     //   [F]or each constructor template in the candidate set of inherited
   9123     //   constructors, a constructor template is implicitly declared
   9124     if (Ctor->getDescribedFunctionTemplate())
   9125       return 0;
   9126 
   9127     //   For each non-template constructor in the candidate set of inherited
   9128     //   constructors other than a constructor having no parameters or a
   9129     //   copy/move constructor having a single parameter, a constructor is
   9130     //   implicitly declared [...]
   9131     if (Ctor->getNumParams() == 0)
   9132       return 1;
   9133     if (Ctor->isCopyOrMoveConstructor())
   9134       return 2;
   9135 
   9136     // Per discussion on core reflector, never inherit a constructor which
   9137     // would become a default, copy, or move constructor of Derived either.
   9138     const ParmVarDecl *PD = Ctor->getParamDecl(0);
   9139     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
   9140     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
   9141   }
   9142 
   9143   /// Declare a single inheriting constructor, inheriting the specified
   9144   /// constructor, with the given type.
   9145   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
   9146                    QualType DerivedType) {
   9147     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
   9148 
   9149     // C++11 [class.inhctor]p3:
   9150     //   ... a constructor is implicitly declared with the same constructor
   9151     //   characteristics unless there is a user-declared constructor with
   9152     //   the same signature in the class where the using-declaration appears
   9153     if (Entry.DeclaredInDerived)
   9154       return;
   9155 
   9156     // C++11 [class.inhctor]p7:
   9157     //   If two using-declarations declare inheriting constructors with the
   9158     //   same signature, the program is ill-formed
   9159     if (Entry.DerivedCtor) {
   9160       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
   9161         // Only diagnose this once per constructor.
   9162         if (Entry.DerivedCtor->isInvalidDecl())
   9163           return;
   9164         Entry.DerivedCtor->setInvalidDecl();
   9165 
   9166         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
   9167         SemaRef.Diag(BaseCtor->getLocation(),
   9168                      diag::note_using_decl_constructor_conflict_current_ctor);
   9169         SemaRef.Diag(Entry.BaseCtor->getLocation(),
   9170                      diag::note_using_decl_constructor_conflict_previous_ctor);
   9171         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
   9172                      diag::note_using_decl_constructor_conflict_previous_using);
   9173       } else {
   9174         // Core issue (no number): if the same inheriting constructor is
   9175         // produced by multiple base class constructors from the same base
   9176         // class, the inheriting constructor is defined as deleted.
   9177         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
   9178       }
   9179 
   9180       return;
   9181     }
   9182 
   9183     ASTContext &Context = SemaRef.Context;
   9184     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
   9185         Context.getCanonicalType(Context.getRecordType(Derived)));
   9186     DeclarationNameInfo NameInfo(Name, UsingLoc);
   9187 
   9188     TemplateParameterList *TemplateParams = nullptr;
   9189     if (const FunctionTemplateDecl *FTD =
   9190             BaseCtor->getDescribedFunctionTemplate()) {
   9191       TemplateParams = FTD->getTemplateParameters();
   9192       // We're reusing template parameters from a different DeclContext. This
   9193       // is questionable at best, but works out because the template depth in
   9194       // both places is guaranteed to be 0.
   9195       // FIXME: Rebuild the template parameters in the new context, and
   9196       // transform the function type to refer to them.
   9197     }
   9198 
   9199     // Build type source info pointing at the using-declaration. This is
   9200     // required by template instantiation.
   9201     TypeSourceInfo *TInfo =
   9202         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
   9203     FunctionProtoTypeLoc ProtoLoc =
   9204         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
   9205 
   9206     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
   9207         Context, Derived, UsingLoc, NameInfo, DerivedType,
   9208         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
   9209         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
   9210 
   9211     // Build an unevaluated exception specification for this constructor.
   9212     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
   9213     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
   9214     EPI.ExceptionSpec.Type = EST_Unevaluated;
   9215     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
   9216     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
   9217                                                  FPT->getParamTypes(), EPI));
   9218 
   9219     // Build the parameter declarations.
   9220     SmallVector<ParmVarDecl *, 16> ParamDecls;
   9221     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
   9222       TypeSourceInfo *TInfo =
   9223           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
   9224       ParmVarDecl *PD = ParmVarDecl::Create(
   9225           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
   9226           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
   9227       PD->setScopeInfo(0, I);
   9228       PD->setImplicit();
   9229       ParamDecls.push_back(PD);
   9230       ProtoLoc.setParam(I, PD);
   9231     }
   9232 
   9233     // Set up the new constructor.
   9234     DerivedCtor->setAccess(BaseCtor->getAccess());
   9235     DerivedCtor->setParams(ParamDecls);
   9236     DerivedCtor->setInheritedConstructor(BaseCtor);
   9237     if (BaseCtor->isDeleted())
   9238       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
   9239 
   9240     // If this is a constructor template, build the template declaration.
   9241     if (TemplateParams) {
   9242       FunctionTemplateDecl *DerivedTemplate =
   9243           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
   9244                                        TemplateParams, DerivedCtor);
   9245       DerivedTemplate->setAccess(BaseCtor->getAccess());
   9246       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
   9247       Derived->addDecl(DerivedTemplate);
   9248     } else {
   9249       Derived->addDecl(DerivedCtor);
   9250     }
   9251 
   9252     Entry.BaseCtor = BaseCtor;
   9253     Entry.DerivedCtor = DerivedCtor;
   9254   }
   9255 
   9256   Sema &SemaRef;
   9257   CXXRecordDecl *Derived;
   9258   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
   9259   MapType Map;
   9260 };
   9261 }
   9262 
   9263 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
   9264   // Defer declaring the inheriting constructors until the class is
   9265   // instantiated.
   9266   if (ClassDecl->isDependentContext())
   9267     return;
   9268 
   9269   // Find base classes from which we might inherit constructors.
   9270   SmallVector<CXXRecordDecl*, 4> InheritedBases;
   9271   for (const auto &BaseIt : ClassDecl->bases())
   9272     if (BaseIt.getInheritConstructors())
   9273       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
   9274 
   9275   // Go no further if we're not inheriting any constructors.
   9276   if (InheritedBases.empty())
   9277     return;
   9278 
   9279   // Declare the inherited constructors.
   9280   InheritingConstructorInfo ICI(*this, ClassDecl);
   9281   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
   9282     ICI.inheritAll(InheritedBases[I]);
   9283 }
   9284 
   9285 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
   9286                                        CXXConstructorDecl *Constructor) {
   9287   CXXRecordDecl *ClassDecl = Constructor->getParent();
   9288   assert(Constructor->getInheritedConstructor() &&
   9289          !Constructor->doesThisDeclarationHaveABody() &&
   9290          !Constructor->isDeleted());
   9291 
   9292   SynthesizedFunctionScope Scope(*this, Constructor);
   9293   DiagnosticErrorTrap Trap(Diags);
   9294   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
   9295       Trap.hasErrorOccurred()) {
   9296     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
   9297       << Context.getTagDeclType(ClassDecl);
   9298     Constructor->setInvalidDecl();
   9299     return;
   9300   }
   9301 
   9302   SourceLocation Loc = Constructor->getLocation();
   9303   Constructor->setBody(new (Context) CompoundStmt(Loc));
   9304 
   9305   Constructor->markUsed(Context);
   9306   MarkVTableUsed(CurrentLocation, ClassDecl);
   9307 
   9308   if (ASTMutationListener *L = getASTMutationListener()) {
   9309     L->CompletedImplicitDefinition(Constructor);
   9310   }
   9311 }
   9312 
   9313 
   9314 Sema::ImplicitExceptionSpecification
   9315 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
   9316   CXXRecordDecl *ClassDecl = MD->getParent();
   9317 
   9318   // C++ [except.spec]p14:
   9319   //   An implicitly declared special member function (Clause 12) shall have
   9320   //   an exception-specification.
   9321   ImplicitExceptionSpecification ExceptSpec(*this);
   9322   if (ClassDecl->isInvalidDecl())
   9323     return ExceptSpec;
   9324 
   9325   // Direct base-class destructors.
   9326   for (const auto &B : ClassDecl->bases()) {
   9327     if (B.isVirtual()) // Handled below.
   9328       continue;
   9329 
   9330     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
   9331       ExceptSpec.CalledDecl(B.getLocStart(),
   9332                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
   9333   }
   9334 
   9335   // Virtual base-class destructors.
   9336   for (const auto &B : ClassDecl->vbases()) {
   9337     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
   9338       ExceptSpec.CalledDecl(B.getLocStart(),
   9339                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
   9340   }
   9341 
   9342   // Field destructors.
   9343   for (const auto *F : ClassDecl->fields()) {
   9344     if (const RecordType *RecordTy
   9345         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
   9346       ExceptSpec.CalledDecl(F->getLocation(),
   9347                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
   9348   }
   9349 
   9350   return ExceptSpec;
   9351 }
   9352 
   9353 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
   9354   // C++ [class.dtor]p2:
   9355   //   If a class has no user-declared destructor, a destructor is
   9356   //   declared implicitly. An implicitly-declared destructor is an
   9357   //   inline public member of its class.
   9358   assert(ClassDecl->needsImplicitDestructor());
   9359 
   9360   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
   9361   if (DSM.isAlreadyBeingDeclared())
   9362     return nullptr;
   9363 
   9364   // Create the actual destructor declaration.
   9365   CanQualType ClassType
   9366     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
   9367   SourceLocation ClassLoc = ClassDecl->getLocation();
   9368   DeclarationName Name
   9369     = Context.DeclarationNames.getCXXDestructorName(ClassType);
   9370   DeclarationNameInfo NameInfo(Name, ClassLoc);
   9371   CXXDestructorDecl *Destructor
   9372       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
   9373                                   QualType(), nullptr, /*isInline=*/true,
   9374                                   /*isImplicitlyDeclared=*/true);
   9375   Destructor->setAccess(AS_public);
   9376   Destructor->setDefaulted();
   9377 
   9378   if (getLangOpts().CUDA) {
   9379     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
   9380                                             Destructor,
   9381                                             /* ConstRHS */ false,
   9382                                             /* Diagnose */ false);
   9383   }
   9384 
   9385   // Build an exception specification pointing back at this destructor.
   9386   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
   9387   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
   9388 
   9389   AddOverriddenMethods(ClassDecl, Destructor);
   9390 
   9391   // We don't need to use SpecialMemberIsTrivial here; triviality for
   9392   // destructors is easy to compute.
   9393   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
   9394 
   9395   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
   9396     SetDeclDeleted(Destructor, ClassLoc);
   9397 
   9398   // Note that we have declared this destructor.
   9399   ++ASTContext::NumImplicitDestructorsDeclared;
   9400 
   9401   // Introduce this destructor into its scope.
   9402   if (Scope *S = getScopeForContext(ClassDecl))
   9403     PushOnScopeChains(Destructor, S, false);
   9404   ClassDecl->addDecl(Destructor);
   9405 
   9406   return Destructor;
   9407 }
   9408 
   9409 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
   9410                                     CXXDestructorDecl *Destructor) {
   9411   assert((Destructor->isDefaulted() &&
   9412           !Destructor->doesThisDeclarationHaveABody() &&
   9413           !Destructor->isDeleted()) &&
   9414          "DefineImplicitDestructor - call it for implicit default dtor");
   9415   CXXRecordDecl *ClassDecl = Destructor->getParent();
   9416   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
   9417 
   9418   if (Destructor->isInvalidDecl())
   9419     return;
   9420 
   9421   SynthesizedFunctionScope Scope(*this, Destructor);
   9422 
   9423   DiagnosticErrorTrap Trap(Diags);
   9424   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
   9425                                          Destructor->getParent());
   9426 
   9427   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
   9428     Diag(CurrentLocation, diag::note_member_synthesized_at)
   9429       << CXXDestructor << Context.getTagDeclType(ClassDecl);
   9430 
   9431     Destructor->setInvalidDecl();
   9432     return;
   9433   }
   9434 
   9435   // The exception specification is needed because we are defining the
   9436   // function.
   9437   ResolveExceptionSpec(CurrentLocation,
   9438                        Destructor->getType()->castAs<FunctionProtoType>());
   9439 
   9440   SourceLocation Loc = Destructor->getLocEnd().isValid()
   9441                            ? Destructor->getLocEnd()
   9442                            : Destructor->getLocation();
   9443   Destructor->setBody(new (Context) CompoundStmt(Loc));
   9444   Destructor->markUsed(Context);
   9445   MarkVTableUsed(CurrentLocation, ClassDecl);
   9446 
   9447   if (ASTMutationListener *L = getASTMutationListener()) {
   9448     L->CompletedImplicitDefinition(Destructor);
   9449   }
   9450 }
   9451 
   9452 /// \brief Perform any semantic analysis which needs to be delayed until all
   9453 /// pending class member declarations have been parsed.
   9454 void Sema::ActOnFinishCXXMemberDecls() {
   9455   // If the context is an invalid C++ class, just suppress these checks.
   9456   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
   9457     if (Record->isInvalidDecl()) {
   9458       DelayedDefaultedMemberExceptionSpecs.clear();
   9459       DelayedExceptionSpecChecks.clear();
   9460       return;
   9461     }
   9462   }
   9463 }
   9464 
   9465 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
   9466   // Don't do anything for template patterns.
   9467   if (Class->getDescribedClassTemplate())
   9468     return;
   9469 
   9470   for (Decl *Member : Class->decls()) {
   9471     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
   9472     if (!CD) {
   9473       // Recurse on nested classes.
   9474       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
   9475         getDefaultArgExprsForConstructors(S, NestedRD);
   9476       continue;
   9477     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
   9478       continue;
   9479     }
   9480 
   9481     for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
   9482       // Skip any default arguments that we've already instantiated.
   9483       if (S.Context.getDefaultArgExprForConstructor(CD, I))
   9484         continue;
   9485 
   9486       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
   9487                                                   CD->getParamDecl(I)).get();
   9488       S.DiscardCleanupsInEvaluationContext();
   9489       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
   9490     }
   9491   }
   9492 }
   9493 
   9494 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
   9495   auto *RD = dyn_cast<CXXRecordDecl>(D);
   9496 
   9497   // Default constructors that are annotated with __declspec(dllexport) which
   9498   // have default arguments or don't use the standard calling convention are
   9499   // wrapped with a thunk called the default constructor closure.
   9500   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
   9501     getDefaultArgExprsForConstructors(*this, RD);
   9502 
   9503   if (!DelayedDllExportClasses.empty()) {
   9504     // Calling ReferenceDllExportedMethods might cause the current function to
   9505     // be called again, so use a local copy of DelayedDllExportClasses.
   9506     SmallVector<CXXRecordDecl *, 4> WorkList;
   9507     std::swap(DelayedDllExportClasses, WorkList);
   9508     for (CXXRecordDecl *Class : WorkList)
   9509       ReferenceDllExportedMethods(*this, Class);
   9510   }
   9511 }
   9512 
   9513 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
   9514                                          CXXDestructorDecl *Destructor) {
   9515   assert(getLangOpts().CPlusPlus11 &&
   9516          "adjusting dtor exception specs was introduced in c++11");
   9517 
   9518   // C++11 [class.dtor]p3:
   9519   //   A declaration of a destructor that does not have an exception-
   9520   //   specification is implicitly considered to have the same exception-
   9521   //   specification as an implicit declaration.
   9522   const FunctionProtoType *DtorType = Destructor->getType()->
   9523                                         getAs<FunctionProtoType>();
   9524   if (DtorType->hasExceptionSpec())
   9525     return;
   9526 
   9527   // Replace the destructor's type, building off the existing one. Fortunately,
   9528   // the only thing of interest in the destructor type is its extended info.
   9529   // The return and arguments are fixed.
   9530   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
   9531   EPI.ExceptionSpec.Type = EST_Unevaluated;
   9532   EPI.ExceptionSpec.SourceDecl = Destructor;
   9533   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
   9534 
   9535   // FIXME: If the destructor has a body that could throw, and the newly created
   9536   // spec doesn't allow exceptions, we should emit a warning, because this
   9537   // change in behavior can break conforming C++03 programs at runtime.
   9538   // However, we don't have a body or an exception specification yet, so it
   9539   // needs to be done somewhere else.
   9540 }
   9541 
   9542 namespace {
   9543 /// \brief An abstract base class for all helper classes used in building the
   9544 //  copy/move operators. These classes serve as factory functions and help us
   9545 //  avoid using the same Expr* in the AST twice.
   9546 class ExprBuilder {
   9547   ExprBuilder(const ExprBuilder&) = delete;
   9548   ExprBuilder &operator=(const ExprBuilder&) = delete;
   9549 
   9550 protected:
   9551   static Expr *assertNotNull(Expr *E) {
   9552     assert(E && "Expression construction must not fail.");
   9553     return E;
   9554   }
   9555 
   9556 public:
   9557   ExprBuilder() {}
   9558   virtual ~ExprBuilder() {}
   9559 
   9560   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
   9561 };
   9562 
   9563 class RefBuilder: public ExprBuilder {
   9564   VarDecl *Var;
   9565   QualType VarType;
   9566 
   9567 public:
   9568   Expr *build(Sema &S, SourceLocation Loc) const override {
   9569     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
   9570   }
   9571 
   9572   RefBuilder(VarDecl *Var, QualType VarType)
   9573       : Var(Var), VarType(VarType) {}
   9574 };
   9575 
   9576 class ThisBuilder: public ExprBuilder {
   9577 public:
   9578   Expr *build(Sema &S, SourceLocation Loc) const override {
   9579     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
   9580   }
   9581 };
   9582 
   9583 class CastBuilder: public ExprBuilder {
   9584   const ExprBuilder &Builder;
   9585   QualType Type;
   9586   ExprValueKind Kind;
   9587   const CXXCastPath &Path;
   9588 
   9589 public:
   9590   Expr *build(Sema &S, SourceLocation Loc) const override {
   9591     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
   9592                                              CK_UncheckedDerivedToBase, Kind,
   9593                                              &Path).get());
   9594   }
   9595 
   9596   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
   9597               const CXXCastPath &Path)
   9598       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
   9599 };
   9600 
   9601 class DerefBuilder: public ExprBuilder {
   9602   const ExprBuilder &Builder;
   9603 
   9604 public:
   9605   Expr *build(Sema &S, SourceLocation Loc) const override {
   9606     return assertNotNull(
   9607         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
   9608   }
   9609 
   9610   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
   9611 };
   9612 
   9613 class MemberBuilder: public ExprBuilder {
   9614   const ExprBuilder &Builder;
   9615   QualType Type;
   9616   CXXScopeSpec SS;
   9617   bool IsArrow;
   9618   LookupResult &MemberLookup;
   9619 
   9620 public:
   9621   Expr *build(Sema &S, SourceLocation Loc) const override {
   9622     return assertNotNull(S.BuildMemberReferenceExpr(
   9623         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
   9624         nullptr, MemberLookup, nullptr, nullptr).get());
   9625   }
   9626 
   9627   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
   9628                 LookupResult &MemberLookup)
   9629       : Builder(Builder), Type(Type), IsArrow(IsArrow),
   9630         MemberLookup(MemberLookup) {}
   9631 };
   9632 
   9633 class MoveCastBuilder: public ExprBuilder {
   9634   const ExprBuilder &Builder;
   9635 
   9636 public:
   9637   Expr *build(Sema &S, SourceLocation Loc) const override {
   9638     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
   9639   }
   9640 
   9641   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
   9642 };
   9643 
   9644 class LvalueConvBuilder: public ExprBuilder {
   9645   const ExprBuilder &Builder;
   9646 
   9647 public:
   9648   Expr *build(Sema &S, SourceLocation Loc) const override {
   9649     return assertNotNull(
   9650         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
   9651   }
   9652 
   9653   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
   9654 };
   9655 
   9656 class SubscriptBuilder: public ExprBuilder {
   9657   const ExprBuilder &Base;
   9658   const ExprBuilder &Index;
   9659 
   9660 public:
   9661   Expr *build(Sema &S, SourceLocation Loc) const override {
   9662     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
   9663         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
   9664   }
   9665 
   9666   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
   9667       : Base(Base), Index(Index) {}
   9668 };
   9669 
   9670 } // end anonymous namespace
   9671 
   9672 /// When generating a defaulted copy or move assignment operator, if a field
   9673 /// should be copied with __builtin_memcpy rather than via explicit assignments,
   9674 /// do so. This optimization only applies for arrays of scalars, and for arrays
   9675 /// of class type where the selected copy/move-assignment operator is trivial.
   9676 static StmtResult
   9677 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
   9678                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
   9679   // Compute the size of the memory buffer to be copied.
   9680   QualType SizeType = S.Context.getSizeType();
   9681   llvm::APInt Size(S.Context.getTypeSize(SizeType),
   9682                    S.Context.getTypeSizeInChars(T).getQuantity());
   9683 
   9684   // Take the address of the field references for "from" and "to". We
   9685   // directly construct UnaryOperators here because semantic analysis
   9686   // does not permit us to take the address of an xvalue.
   9687   Expr *From = FromB.build(S, Loc);
   9688   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
   9689                          S.Context.getPointerType(From->getType()),
   9690                          VK_RValue, OK_Ordinary, Loc);
   9691   Expr *To = ToB.build(S, Loc);
   9692   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
   9693                        S.Context.getPointerType(To->getType()),
   9694                        VK_RValue, OK_Ordinary, Loc);
   9695 
   9696   const Type *E = T->getBaseElementTypeUnsafe();
   9697   bool NeedsCollectableMemCpy =
   9698     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
   9699 
   9700   // Create a reference to the __builtin_objc_memmove_collectable function
   9701   StringRef MemCpyName = NeedsCollectableMemCpy ?
   9702     "__builtin_objc_memmove_collectable" :
   9703     "__builtin_memcpy";
   9704   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
   9705                  Sema::LookupOrdinaryName);
   9706   S.LookupName(R, S.TUScope, true);
   9707 
   9708   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
   9709   if (!MemCpy)
   9710     // Something went horribly wrong earlier, and we will have complained
   9711     // about it.
   9712     return StmtError();
   9713 
   9714   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
   9715                                             VK_RValue, Loc, nullptr);
   9716   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
   9717 
   9718   Expr *CallArgs[] = {
   9719     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
   9720   };
   9721   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
   9722                                     Loc, CallArgs, Loc);
   9723 
   9724   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
   9725   return Call.getAs<Stmt>();
   9726 }
   9727 
   9728 /// \brief Builds a statement that copies/moves the given entity from \p From to
   9729 /// \c To.
   9730 ///
   9731 /// This routine is used to copy/move the members of a class with an
   9732 /// implicitly-declared copy/move assignment operator. When the entities being
   9733 /// copied are arrays, this routine builds for loops to copy them.
   9734 ///
   9735 /// \param S The Sema object used for type-checking.
   9736 ///
   9737 /// \param Loc The location where the implicit copy/move is being generated.
   9738 ///
   9739 /// \param T The type of the expressions being copied/moved. Both expressions
   9740 /// must have this type.
   9741 ///
   9742 /// \param To The expression we are copying/moving to.
   9743 ///
   9744 /// \param From The expression we are copying/moving from.
   9745 ///
   9746 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
   9747 /// Otherwise, it's a non-static member subobject.
   9748 ///
   9749 /// \param Copying Whether we're copying or moving.
   9750 ///
   9751 /// \param Depth Internal parameter recording the depth of the recursion.
   9752 ///
   9753 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
   9754 /// if a memcpy should be used instead.
   9755 static StmtResult
   9756 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
   9757                                  const ExprBuilder &To, const ExprBuilder &From,
   9758                                  bool CopyingBaseSubobject, bool Copying,
   9759                                  unsigned Depth = 0) {
   9760   // C++11 [class.copy]p28:
   9761   //   Each subobject is assigned in the manner appropriate to its type:
   9762   //
   9763   //     - if the subobject is of class type, as if by a call to operator= with
   9764   //       the subobject as the object expression and the corresponding
   9765   //       subobject of x as a single function argument (as if by explicit
   9766   //       qualification; that is, ignoring any possible virtual overriding
   9767   //       functions in more derived classes);
   9768   //
   9769   // C++03 [class.copy]p13:
   9770   //     - if the subobject is of class type, the copy assignment operator for
   9771   //       the class is used (as if by explicit qualification; that is,
   9772   //       ignoring any possible virtual overriding functions in more derived
   9773   //       classes);
   9774   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
   9775     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
   9776 
   9777     // Look for operator=.
   9778     DeclarationName Name
   9779       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
   9780     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
   9781     S.LookupQualifiedName(OpLookup, ClassDecl, false);
   9782 
   9783     // Prior to C++11, filter out any result that isn't a copy/move-assignment
   9784     // operator.
   9785     if (!S.getLangOpts().CPlusPlus11) {
   9786       LookupResult::Filter F = OpLookup.makeFilter();
   9787       while (F.hasNext()) {
   9788         NamedDecl *D = F.next();
   9789         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
   9790           if (Method->isCopyAssignmentOperator() ||
   9791               (!Copying && Method->isMoveAssignmentOperator()))
   9792             continue;
   9793 
   9794         F.erase();
   9795       }
   9796       F.done();
   9797     }
   9798 
   9799     // Suppress the protected check (C++ [class.protected]) for each of the
   9800     // assignment operators we found. This strange dance is required when
   9801     // we're assigning via a base classes's copy-assignment operator. To
   9802     // ensure that we're getting the right base class subobject (without
   9803     // ambiguities), we need to cast "this" to that subobject type; to
   9804     // ensure that we don't go through the virtual call mechanism, we need
   9805     // to qualify the operator= name with the base class (see below). However,
   9806     // this means that if the base class has a protected copy assignment
   9807     // operator, the protected member access check will fail. So, we
   9808     // rewrite "protected" access to "public" access in this case, since we
   9809     // know by construction that we're calling from a derived class.
   9810     if (CopyingBaseSubobject) {
   9811       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
   9812            L != LEnd; ++L) {
   9813         if (L.getAccess() == AS_protected)
   9814           L.setAccess(AS_public);
   9815       }
   9816     }
   9817 
   9818     // Create the nested-name-specifier that will be used to qualify the
   9819     // reference to operator=; this is required to suppress the virtual
   9820     // call mechanism.
   9821     CXXScopeSpec SS;
   9822     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
   9823     SS.MakeTrivial(S.Context,
   9824                    NestedNameSpecifier::Create(S.Context, nullptr, false,
   9825                                                CanonicalT),
   9826                    Loc);
   9827 
   9828     // Create the reference to operator=.
   9829     ExprResult OpEqualRef
   9830       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
   9831                                    SS, /*TemplateKWLoc=*/SourceLocation(),
   9832                                    /*FirstQualifierInScope=*/nullptr,
   9833                                    OpLookup,
   9834                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
   9835                                    /*SuppressQualifierCheck=*/true);
   9836     if (OpEqualRef.isInvalid())
   9837       return StmtError();
   9838 
   9839     // Build the call to the assignment operator.
   9840 
   9841     Expr *FromInst = From.build(S, Loc);
   9842     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
   9843                                                   OpEqualRef.getAs<Expr>(),
   9844                                                   Loc, FromInst, Loc);
   9845     if (Call.isInvalid())
   9846       return StmtError();
   9847 
   9848     // If we built a call to a trivial 'operator=' while copying an array,
   9849     // bail out. We'll replace the whole shebang with a memcpy.
   9850     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
   9851     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
   9852       return StmtResult((Stmt*)nullptr);
   9853 
   9854     // Convert to an expression-statement, and clean up any produced
   9855     // temporaries.
   9856     return S.ActOnExprStmt(Call);
   9857   }
   9858 
   9859   //     - if the subobject is of scalar type, the built-in assignment
   9860   //       operator is used.
   9861   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
   9862   if (!ArrayTy) {
   9863     ExprResult Assignment = S.CreateBuiltinBinOp(
   9864         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
   9865     if (Assignment.isInvalid())
   9866       return StmtError();
   9867     return S.ActOnExprStmt(Assignment);
   9868   }
   9869 
   9870   //     - if the subobject is an array, each element is assigned, in the
   9871   //       manner appropriate to the element type;
   9872 
   9873   // Construct a loop over the array bounds, e.g.,
   9874   //
   9875   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
   9876   //
   9877   // that will copy each of the array elements.
   9878   QualType SizeType = S.Context.getSizeType();
   9879 
   9880   // Create the iteration variable.
   9881   IdentifierInfo *IterationVarName = nullptr;
   9882   {
   9883     SmallString<8> Str;
   9884     llvm::raw_svector_ostream OS(Str);
   9885     OS << "__i" << Depth;
   9886     IterationVarName = &S.Context.Idents.get(OS.str());
   9887   }
   9888   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
   9889                                           IterationVarName, SizeType,
   9890                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
   9891                                           SC_None);
   9892 
   9893   // Initialize the iteration variable to zero.
   9894   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
   9895   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
   9896 
   9897   // Creates a reference to the iteration variable.
   9898   RefBuilder IterationVarRef(IterationVar, SizeType);
   9899   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
   9900 
   9901   // Create the DeclStmt that holds the iteration variable.
   9902   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
   9903 
   9904   // Subscript the "from" and "to" expressions with the iteration variable.
   9905   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
   9906   MoveCastBuilder FromIndexMove(FromIndexCopy);
   9907   const ExprBuilder *FromIndex;
   9908   if (Copying)
   9909     FromIndex = &FromIndexCopy;
   9910   else
   9911     FromIndex = &FromIndexMove;
   9912 
   9913   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
   9914 
   9915   // Build the copy/move for an individual element of the array.
   9916   StmtResult Copy =
   9917     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
   9918                                      ToIndex, *FromIndex, CopyingBaseSubobject,
   9919                                      Copying, Depth + 1);
   9920   // Bail out if copying fails or if we determined that we should use memcpy.
   9921   if (Copy.isInvalid() || !Copy.get())
   9922     return Copy;
   9923 
   9924   // Create the comparison against the array bound.
   9925   llvm::APInt Upper
   9926     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
   9927   Expr *Comparison
   9928     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
   9929                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
   9930                                      BO_NE, S.Context.BoolTy,
   9931                                      VK_RValue, OK_Ordinary, Loc, false);
   9932 
   9933   // Create the pre-increment of the iteration variable.
   9934   Expr *Increment
   9935     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
   9936                                     SizeType, VK_LValue, OK_Ordinary, Loc);
   9937 
   9938   // Construct the loop that copies all elements of this array.
   9939   return S.ActOnForStmt(Loc, Loc, InitStmt,
   9940                         S.MakeFullExpr(Comparison),
   9941                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
   9942                         Loc, Copy.get());
   9943 }
   9944 
   9945 static StmtResult
   9946 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
   9947                       const ExprBuilder &To, const ExprBuilder &From,
   9948                       bool CopyingBaseSubobject, bool Copying) {
   9949   // Maybe we should use a memcpy?
   9950   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
   9951       T.isTriviallyCopyableType(S.Context))
   9952     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
   9953 
   9954   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
   9955                                                      CopyingBaseSubobject,
   9956                                                      Copying, 0));
   9957 
   9958   // If we ended up picking a trivial assignment operator for an array of a
   9959   // non-trivially-copyable class type, just emit a memcpy.
   9960   if (!Result.isInvalid() && !Result.get())
   9961     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
   9962 
   9963   return Result;
   9964 }
   9965 
   9966 Sema::ImplicitExceptionSpecification
   9967 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
   9968   CXXRecordDecl *ClassDecl = MD->getParent();
   9969 
   9970   ImplicitExceptionSpecification ExceptSpec(*this);
   9971   if (ClassDecl->isInvalidDecl())
   9972     return ExceptSpec;
   9973 
   9974   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
   9975   assert(T->getNumParams() == 1 && "not a copy assignment op");
   9976   unsigned ArgQuals =
   9977       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
   9978 
   9979   // C++ [except.spec]p14:
   9980   //   An implicitly declared special member function (Clause 12) shall have an
   9981   //   exception-specification. [...]
   9982 
   9983   // It is unspecified whether or not an implicit copy assignment operator
   9984   // attempts to deduplicate calls to assignment operators of virtual bases are
   9985   // made. As such, this exception specification is effectively unspecified.
   9986   // Based on a similar decision made for constness in C++0x, we're erring on
   9987   // the side of assuming such calls to be made regardless of whether they
   9988   // actually happen.
   9989   for (const auto &Base : ClassDecl->bases()) {
   9990     if (Base.isVirtual())
   9991       continue;
   9992 
   9993     CXXRecordDecl *BaseClassDecl
   9994       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
   9995     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
   9996                                                             ArgQuals, false, 0))
   9997       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
   9998   }
   9999 
   10000   for (const auto &Base : ClassDecl->vbases()) {
   10001     CXXRecordDecl *BaseClassDecl
   10002       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
   10003     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
   10004                                                             ArgQuals, false, 0))
   10005       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
   10006   }
   10007 
   10008   for (const auto *Field : ClassDecl->fields()) {
   10009     QualType FieldType = Context.getBaseElementType(Field->getType());
   10010     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
   10011       if (CXXMethodDecl *CopyAssign =
   10012           LookupCopyingAssignment(FieldClassDecl,
   10013                                   ArgQuals | FieldType.getCVRQualifiers(),
   10014                                   false, 0))
   10015         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
   10016     }
   10017   }
   10018 
   10019   return ExceptSpec;
   10020 }
   10021 
   10022 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
   10023   // Note: The following rules are largely analoguous to the copy
   10024   // constructor rules. Note that virtual bases are not taken into account
   10025   // for determining the argument type of the operator. Note also that
   10026   // operators taking an object instead of a reference are allowed.
   10027   assert(ClassDecl->needsImplicitCopyAssignment());
   10028 
   10029   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
   10030   if (DSM.isAlreadyBeingDeclared())
   10031     return nullptr;
   10032 
   10033   QualType ArgType = Context.getTypeDeclType(ClassDecl);
   10034   QualType RetType = Context.getLValueReferenceType(ArgType);
   10035   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
   10036   if (Const)
   10037     ArgType = ArgType.withConst();
   10038   ArgType = Context.getLValueReferenceType(ArgType);
   10039 
   10040   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   10041                                                      CXXCopyAssignment,
   10042                                                      Const);
   10043 
   10044   //   An implicitly-declared copy assignment operator is an inline public
   10045   //   member of its class.
   10046   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
   10047   SourceLocation ClassLoc = ClassDecl->getLocation();
   10048   DeclarationNameInfo NameInfo(Name, ClassLoc);
   10049   CXXMethodDecl *CopyAssignment =
   10050       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
   10051                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
   10052                             /*isInline=*/true, Constexpr, SourceLocation());
   10053   CopyAssignment->setAccess(AS_public);
   10054   CopyAssignment->setDefaulted();
   10055   CopyAssignment->setImplicit();
   10056 
   10057   if (getLangOpts().CUDA) {
   10058     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
   10059                                             CopyAssignment,
   10060                                             /* ConstRHS */ Const,
   10061                                             /* Diagnose */ false);
   10062   }
   10063 
   10064   // Build an exception specification pointing back at this member.
   10065   FunctionProtoType::ExtProtoInfo EPI =
   10066       getImplicitMethodEPI(*this, CopyAssignment);
   10067   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
   10068 
   10069   // Add the parameter to the operator.
   10070   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
   10071                                                ClassLoc, ClassLoc,
   10072                                                /*Id=*/nullptr, ArgType,
   10073                                                /*TInfo=*/nullptr, SC_None,
   10074                                                nullptr);
   10075   CopyAssignment->setParams(FromParam);
   10076 
   10077   AddOverriddenMethods(ClassDecl, CopyAssignment);
   10078 
   10079   CopyAssignment->setTrivial(
   10080     ClassDecl->needsOverloadResolutionForCopyAssignment()
   10081       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
   10082       : ClassDecl->hasTrivialCopyAssignment());
   10083 
   10084   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
   10085     SetDeclDeleted(CopyAssignment, ClassLoc);
   10086 
   10087   // Note that we have added this copy-assignment operator.
   10088   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
   10089 
   10090   if (Scope *S = getScopeForContext(ClassDecl))
   10091     PushOnScopeChains(CopyAssignment, S, false);
   10092   ClassDecl->addDecl(CopyAssignment);
   10093 
   10094   return CopyAssignment;
   10095 }
   10096 
   10097 /// Diagnose an implicit copy operation for a class which is odr-used, but
   10098 /// which is deprecated because the class has a user-declared copy constructor,
   10099 /// copy assignment operator, or destructor.
   10100 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
   10101                                             SourceLocation UseLoc) {
   10102   assert(CopyOp->isImplicit());
   10103 
   10104   CXXRecordDecl *RD = CopyOp->getParent();
   10105   CXXMethodDecl *UserDeclaredOperation = nullptr;
   10106 
   10107   // In Microsoft mode, assignment operations don't affect constructors and
   10108   // vice versa.
   10109   if (RD->hasUserDeclaredDestructor()) {
   10110     UserDeclaredOperation = RD->getDestructor();
   10111   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
   10112              RD->hasUserDeclaredCopyConstructor() &&
   10113              !S.getLangOpts().MSVCCompat) {
   10114     // Find any user-declared copy constructor.
   10115     for (auto *I : RD->ctors()) {
   10116       if (I->isCopyConstructor()) {
   10117         UserDeclaredOperation = I;
   10118         break;
   10119       }
   10120     }
   10121     assert(UserDeclaredOperation);
   10122   } else if (isa<CXXConstructorDecl>(CopyOp) &&
   10123              RD->hasUserDeclaredCopyAssignment() &&
   10124              !S.getLangOpts().MSVCCompat) {
   10125     // Find any user-declared move assignment operator.
   10126     for (auto *I : RD->methods()) {
   10127       if (I->isCopyAssignmentOperator()) {
   10128         UserDeclaredOperation = I;
   10129         break;
   10130       }
   10131     }
   10132     assert(UserDeclaredOperation);
   10133   }
   10134 
   10135   if (UserDeclaredOperation) {
   10136     S.Diag(UserDeclaredOperation->getLocation(),
   10137          diag::warn_deprecated_copy_operation)
   10138       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
   10139       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
   10140     S.Diag(UseLoc, diag::note_member_synthesized_at)
   10141       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
   10142                                           : Sema::CXXCopyAssignment)
   10143       << RD;
   10144   }
   10145 }
   10146 
   10147 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
   10148                                         CXXMethodDecl *CopyAssignOperator) {
   10149   assert((CopyAssignOperator->isDefaulted() &&
   10150           CopyAssignOperator->isOverloadedOperator() &&
   10151           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
   10152           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
   10153           !CopyAssignOperator->isDeleted()) &&
   10154          "DefineImplicitCopyAssignment called for wrong function");
   10155 
   10156   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
   10157 
   10158   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
   10159     CopyAssignOperator->setInvalidDecl();
   10160     return;
   10161   }
   10162 
   10163   // C++11 [class.copy]p18:
   10164   //   The [definition of an implicitly declared copy assignment operator] is
   10165   //   deprecated if the class has a user-declared copy constructor or a
   10166   //   user-declared destructor.
   10167   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
   10168     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
   10169 
   10170   CopyAssignOperator->markUsed(Context);
   10171 
   10172   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
   10173   DiagnosticErrorTrap Trap(Diags);
   10174 
   10175   // C++0x [class.copy]p30:
   10176   //   The implicitly-defined or explicitly-defaulted copy assignment operator
   10177   //   for a non-union class X performs memberwise copy assignment of its
   10178   //   subobjects. The direct base classes of X are assigned first, in the
   10179   //   order of their declaration in the base-specifier-list, and then the
   10180   //   immediate non-static data members of X are assigned, in the order in
   10181   //   which they were declared in the class definition.
   10182 
   10183   // The statements that form the synthesized function body.
   10184   SmallVector<Stmt*, 8> Statements;
   10185 
   10186   // The parameter for the "other" object, which we are copying from.
   10187   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
   10188   Qualifiers OtherQuals = Other->getType().getQualifiers();
   10189   QualType OtherRefType = Other->getType();
   10190   if (const LValueReferenceType *OtherRef
   10191                                 = OtherRefType->getAs<LValueReferenceType>()) {
   10192     OtherRefType = OtherRef->getPointeeType();
   10193     OtherQuals = OtherRefType.getQualifiers();
   10194   }
   10195 
   10196   // Our location for everything implicitly-generated.
   10197   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
   10198                            ? CopyAssignOperator->getLocEnd()
   10199                            : CopyAssignOperator->getLocation();
   10200 
   10201   // Builds a DeclRefExpr for the "other" object.
   10202   RefBuilder OtherRef(Other, OtherRefType);
   10203 
   10204   // Builds the "this" pointer.
   10205   ThisBuilder This;
   10206 
   10207   // Assign base classes.
   10208   bool Invalid = false;
   10209   for (auto &Base : ClassDecl->bases()) {
   10210     // Form the assignment:
   10211     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
   10212     QualType BaseType = Base.getType().getUnqualifiedType();
   10213     if (!BaseType->isRecordType()) {
   10214       Invalid = true;
   10215       continue;
   10216     }
   10217 
   10218     CXXCastPath BasePath;
   10219     BasePath.push_back(&Base);
   10220 
   10221     // Construct the "from" expression, which is an implicit cast to the
   10222     // appropriately-qualified base type.
   10223     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
   10224                      VK_LValue, BasePath);
   10225 
   10226     // Dereference "this".
   10227     DerefBuilder DerefThis(This);
   10228     CastBuilder To(DerefThis,
   10229                    Context.getCVRQualifiedType(
   10230                        BaseType, CopyAssignOperator->getTypeQualifiers()),
   10231                    VK_LValue, BasePath);
   10232 
   10233     // Build the copy.
   10234     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
   10235                                             To, From,
   10236                                             /*CopyingBaseSubobject=*/true,
   10237                                             /*Copying=*/true);
   10238     if (Copy.isInvalid()) {
   10239       Diag(CurrentLocation, diag::note_member_synthesized_at)
   10240         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
   10241       CopyAssignOperator->setInvalidDecl();
   10242       return;
   10243     }
   10244 
   10245     // Success! Record the copy.
   10246     Statements.push_back(Copy.getAs<Expr>());
   10247   }
   10248 
   10249   // Assign non-static members.
   10250   for (auto *Field : ClassDecl->fields()) {
   10251     // FIXME: We should form some kind of AST representation for the implied
   10252     // memcpy in a union copy operation.
   10253     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
   10254       continue;
   10255 
   10256     if (Field->isInvalidDecl()) {
   10257       Invalid = true;
   10258       continue;
   10259     }
   10260 
   10261     // Check for members of reference type; we can't copy those.
   10262     if (Field->getType()->isReferenceType()) {
   10263       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
   10264         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
   10265       Diag(Field->getLocation(), diag::note_declared_at);
   10266       Diag(CurrentLocation, diag::note_member_synthesized_at)
   10267         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
   10268       Invalid = true;
   10269       continue;
   10270     }
   10271 
   10272     // Check for members of const-qualified, non-class type.
   10273     QualType BaseType = Context.getBaseElementType(Field->getType());
   10274     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
   10275       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
   10276         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
   10277       Diag(Field->getLocation(), diag::note_declared_at);
   10278       Diag(CurrentLocation, diag::note_member_synthesized_at)
   10279         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
   10280       Invalid = true;
   10281       continue;
   10282     }
   10283 
   10284     // Suppress assigning zero-width bitfields.
   10285     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
   10286       continue;
   10287 
   10288     QualType FieldType = Field->getType().getNonReferenceType();
   10289     if (FieldType->isIncompleteArrayType()) {
   10290       assert(ClassDecl->hasFlexibleArrayMember() &&
   10291              "Incomplete array type is not valid");
   10292       continue;
   10293     }
   10294 
   10295     // Build references to the field in the object we're copying from and to.
   10296     CXXScopeSpec SS; // Intentionally empty
   10297     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
   10298                               LookupMemberName);
   10299     MemberLookup.addDecl(Field);
   10300     MemberLookup.resolveKind();
   10301 
   10302     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
   10303 
   10304     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
   10305 
   10306     // Build the copy of this field.
   10307     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
   10308                                             To, From,
   10309                                             /*CopyingBaseSubobject=*/false,
   10310                                             /*Copying=*/true);
   10311     if (Copy.isInvalid()) {
   10312       Diag(CurrentLocation, diag::note_member_synthesized_at)
   10313         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
   10314       CopyAssignOperator->setInvalidDecl();
   10315       return;
   10316     }
   10317 
   10318     // Success! Record the copy.
   10319     Statements.push_back(Copy.getAs<Stmt>());
   10320   }
   10321 
   10322   if (!Invalid) {
   10323     // Add a "return *this;"
   10324     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
   10325 
   10326     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
   10327     if (Return.isInvalid())
   10328       Invalid = true;
   10329     else {
   10330       Statements.push_back(Return.getAs<Stmt>());
   10331 
   10332       if (Trap.hasErrorOccurred()) {
   10333         Diag(CurrentLocation, diag::note_member_synthesized_at)
   10334           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
   10335         Invalid = true;
   10336       }
   10337     }
   10338   }
   10339 
   10340   // The exception specification is needed because we are defining the
   10341   // function.
   10342   ResolveExceptionSpec(CurrentLocation,
   10343                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
   10344 
   10345   if (Invalid) {
   10346     CopyAssignOperator->setInvalidDecl();
   10347     return;
   10348   }
   10349 
   10350   StmtResult Body;
   10351   {
   10352     CompoundScopeRAII CompoundScope(*this);
   10353     Body = ActOnCompoundStmt(Loc, Loc, Statements,
   10354                              /*isStmtExpr=*/false);
   10355     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
   10356   }
   10357   CopyAssignOperator->setBody(Body.getAs<Stmt>());
   10358 
   10359   if (ASTMutationListener *L = getASTMutationListener()) {
   10360     L->CompletedImplicitDefinition(CopyAssignOperator);
   10361   }
   10362 }
   10363 
   10364 Sema::ImplicitExceptionSpecification
   10365 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
   10366   CXXRecordDecl *ClassDecl = MD->getParent();
   10367 
   10368   ImplicitExceptionSpecification ExceptSpec(*this);
   10369   if (ClassDecl->isInvalidDecl())
   10370     return ExceptSpec;
   10371 
   10372   // C++0x [except.spec]p14:
   10373   //   An implicitly declared special member function (Clause 12) shall have an
   10374   //   exception-specification. [...]
   10375 
   10376   // It is unspecified whether or not an implicit move assignment operator
   10377   // attempts to deduplicate calls to assignment operators of virtual bases are
   10378   // made. As such, this exception specification is effectively unspecified.
   10379   // Based on a similar decision made for constness in C++0x, we're erring on
   10380   // the side of assuming such calls to be made regardless of whether they
   10381   // actually happen.
   10382   // Note that a move constructor is not implicitly declared when there are
   10383   // virtual bases, but it can still be user-declared and explicitly defaulted.
   10384   for (const auto &Base : ClassDecl->bases()) {
   10385     if (Base.isVirtual())
   10386       continue;
   10387 
   10388     CXXRecordDecl *BaseClassDecl
   10389       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
   10390     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
   10391                                                            0, false, 0))
   10392       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
   10393   }
   10394 
   10395   for (const auto &Base : ClassDecl->vbases()) {
   10396     CXXRecordDecl *BaseClassDecl
   10397       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
   10398     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
   10399                                                            0, false, 0))
   10400       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
   10401   }
   10402 
   10403   for (const auto *Field : ClassDecl->fields()) {
   10404     QualType FieldType = Context.getBaseElementType(Field->getType());
   10405     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
   10406       if (CXXMethodDecl *MoveAssign =
   10407               LookupMovingAssignment(FieldClassDecl,
   10408                                      FieldType.getCVRQualifiers(),
   10409                                      false, 0))
   10410         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
   10411     }
   10412   }
   10413 
   10414   return ExceptSpec;
   10415 }
   10416 
   10417 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
   10418   assert(ClassDecl->needsImplicitMoveAssignment());
   10419 
   10420   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
   10421   if (DSM.isAlreadyBeingDeclared())
   10422     return nullptr;
   10423 
   10424   // Note: The following rules are largely analoguous to the move
   10425   // constructor rules.
   10426 
   10427   QualType ArgType = Context.getTypeDeclType(ClassDecl);
   10428   QualType RetType = Context.getLValueReferenceType(ArgType);
   10429   ArgType = Context.getRValueReferenceType(ArgType);
   10430 
   10431   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   10432                                                      CXXMoveAssignment,
   10433                                                      false);
   10434 
   10435   //   An implicitly-declared move assignment operator is an inline public
   10436   //   member of its class.
   10437   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
   10438   SourceLocation ClassLoc = ClassDecl->getLocation();
   10439   DeclarationNameInfo NameInfo(Name, ClassLoc);
   10440   CXXMethodDecl *MoveAssignment =
   10441       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
   10442                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
   10443                             /*isInline=*/true, Constexpr, SourceLocation());
   10444   MoveAssignment->setAccess(AS_public);
   10445   MoveAssignment->setDefaulted();
   10446   MoveAssignment->setImplicit();
   10447 
   10448   if (getLangOpts().CUDA) {
   10449     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
   10450                                             MoveAssignment,
   10451                                             /* ConstRHS */ false,
   10452                                             /* Diagnose */ false);
   10453   }
   10454 
   10455   // Build an exception specification pointing back at this member.
   10456   FunctionProtoType::ExtProtoInfo EPI =
   10457       getImplicitMethodEPI(*this, MoveAssignment);
   10458   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
   10459 
   10460   // Add the parameter to the operator.
   10461   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
   10462                                                ClassLoc, ClassLoc,
   10463                                                /*Id=*/nullptr, ArgType,
   10464                                                /*TInfo=*/nullptr, SC_None,
   10465                                                nullptr);
   10466   MoveAssignment->setParams(FromParam);
   10467 
   10468   AddOverriddenMethods(ClassDecl, MoveAssignment);
   10469 
   10470   MoveAssignment->setTrivial(
   10471     ClassDecl->needsOverloadResolutionForMoveAssignment()
   10472       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
   10473       : ClassDecl->hasTrivialMoveAssignment());
   10474 
   10475   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
   10476     ClassDecl->setImplicitMoveAssignmentIsDeleted();
   10477     SetDeclDeleted(MoveAssignment, ClassLoc);
   10478   }
   10479 
   10480   // Note that we have added this copy-assignment operator.
   10481   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
   10482 
   10483   if (Scope *S = getScopeForContext(ClassDecl))
   10484     PushOnScopeChains(MoveAssignment, S, false);
   10485   ClassDecl->addDecl(MoveAssignment);
   10486 
   10487   return MoveAssignment;
   10488 }
   10489 
   10490 /// Check if we're implicitly defining a move assignment operator for a class
   10491 /// with virtual bases. Such a move assignment might move-assign the virtual
   10492 /// base multiple times.
   10493 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
   10494                                                SourceLocation CurrentLocation) {
   10495   assert(!Class->isDependentContext() && "should not define dependent move");
   10496 
   10497   // Only a virtual base could get implicitly move-assigned multiple times.
   10498   // Only a non-trivial move assignment can observe this. We only want to
   10499   // diagnose if we implicitly define an assignment operator that assigns
   10500   // two base classes, both of which move-assign the same virtual base.
   10501   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
   10502       Class->getNumBases() < 2)
   10503     return;
   10504 
   10505   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
   10506   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
   10507   VBaseMap VBases;
   10508 
   10509   for (auto &BI : Class->bases()) {
   10510     Worklist.push_back(&BI);
   10511     while (!Worklist.empty()) {
   10512       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
   10513       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
   10514 
   10515       // If the base has no non-trivial move assignment operators,
   10516       // we don't care about moves from it.
   10517       if (!Base->hasNonTrivialMoveAssignment())
   10518         continue;
   10519 
   10520       // If there's nothing virtual here, skip it.
   10521       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
   10522         continue;
   10523 
   10524       // If we're not actually going to call a move assignment for this base,
   10525       // or the selected move assignment is trivial, skip it.
   10526       Sema::SpecialMemberOverloadResult *SMOR =
   10527         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
   10528                               /*ConstArg*/false, /*VolatileArg*/false,
   10529                               /*RValueThis*/true, /*ConstThis*/false,
   10530                               /*VolatileThis*/false);
   10531       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
   10532           !SMOR->getMethod()->isMoveAssignmentOperator())
   10533         continue;
   10534 
   10535       if (BaseSpec->isVirtual()) {
   10536         // We're going to move-assign this virtual base, and its move
   10537         // assignment operator is not trivial. If this can happen for
   10538         // multiple distinct direct bases of Class, diagnose it. (If it
   10539         // only happens in one base, we'll diagnose it when synthesizing
   10540         // that base class's move assignment operator.)
   10541         CXXBaseSpecifier *&Existing =
   10542             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
   10543                 .first->second;
   10544         if (Existing && Existing != &BI) {
   10545           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
   10546             << Class << Base;
   10547           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
   10548             << (Base->getCanonicalDecl() ==
   10549                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
   10550             << Base << Existing->getType() << Existing->getSourceRange();
   10551           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
   10552             << (Base->getCanonicalDecl() ==
   10553                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
   10554             << Base << BI.getType() << BaseSpec->getSourceRange();
   10555 
   10556           // Only diagnose each vbase once.
   10557           Existing = nullptr;
   10558         }
   10559       } else {
   10560         // Only walk over bases that have defaulted move assignment operators.
   10561         // We assume that any user-provided move assignment operator handles
   10562         // the multiple-moves-of-vbase case itself somehow.
   10563         if (!SMOR->getMethod()->isDefaulted())
   10564           continue;
   10565 
   10566         // We're going to move the base classes of Base. Add them to the list.
   10567         for (auto &BI : Base->bases())
   10568           Worklist.push_back(&BI);
   10569       }
   10570     }
   10571   }
   10572 }
   10573 
   10574 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
   10575                                         CXXMethodDecl *MoveAssignOperator) {
   10576   assert((MoveAssignOperator->isDefaulted() &&
   10577           MoveAssignOperator->isOverloadedOperator() &&
   10578           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
   10579           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
   10580           !MoveAssignOperator->isDeleted()) &&
   10581          "DefineImplicitMoveAssignment called for wrong function");
   10582 
   10583   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
   10584 
   10585   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
   10586     MoveAssignOperator->setInvalidDecl();
   10587     return;
   10588   }
   10589 
   10590   MoveAssignOperator->markUsed(Context);
   10591 
   10592   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
   10593   DiagnosticErrorTrap Trap(Diags);
   10594 
   10595   // C++0x [class.copy]p28:
   10596   //   The implicitly-defined or move assignment operator for a non-union class
   10597   //   X performs memberwise move assignment of its subobjects. The direct base
   10598   //   classes of X are assigned first, in the order of their declaration in the
   10599   //   base-specifier-list, and then the immediate non-static data members of X
   10600   //   are assigned, in the order in which they were declared in the class
   10601   //   definition.
   10602 
   10603   // Issue a warning if our implicit move assignment operator will move
   10604   // from a virtual base more than once.
   10605   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
   10606 
   10607   // The statements that form the synthesized function body.
   10608   SmallVector<Stmt*, 8> Statements;
   10609 
   10610   // The parameter for the "other" object, which we are move from.
   10611   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
   10612   QualType OtherRefType = Other->getType()->
   10613       getAs<RValueReferenceType>()->getPointeeType();
   10614   assert(!OtherRefType.getQualifiers() &&
   10615          "Bad argument type of defaulted move assignment");
   10616 
   10617   // Our location for everything implicitly-generated.
   10618   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
   10619                            ? MoveAssignOperator->getLocEnd()
   10620                            : MoveAssignOperator->getLocation();
   10621 
   10622   // Builds a reference to the "other" object.
   10623   RefBuilder OtherRef(Other, OtherRefType);
   10624   // Cast to rvalue.
   10625   MoveCastBuilder MoveOther(OtherRef);
   10626 
   10627   // Builds the "this" pointer.
   10628   ThisBuilder This;
   10629 
   10630   // Assign base classes.
   10631   bool Invalid = false;
   10632   for (auto &Base : ClassDecl->bases()) {
   10633     // C++11 [class.copy]p28:
   10634     //   It is unspecified whether subobjects representing virtual base classes
   10635     //   are assigned more than once by the implicitly-defined copy assignment
   10636     //   operator.
   10637     // FIXME: Do not assign to a vbase that will be assigned by some other base
   10638     // class. For a move-assignment, this can result in the vbase being moved
   10639     // multiple times.
   10640 
   10641     // Form the assignment:
   10642     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
   10643     QualType BaseType = Base.getType().getUnqualifiedType();
   10644     if (!BaseType->isRecordType()) {
   10645       Invalid = true;
   10646       continue;
   10647     }
   10648 
   10649     CXXCastPath BasePath;
   10650     BasePath.push_back(&Base);
   10651 
   10652     // Construct the "from" expression, which is an implicit cast to the
   10653     // appropriately-qualified base type.
   10654     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
   10655 
   10656     // Dereference "this".
   10657     DerefBuilder DerefThis(This);
   10658 
   10659     // Implicitly cast "this" to the appropriately-qualified base type.
   10660     CastBuilder To(DerefThis,
   10661                    Context.getCVRQualifiedType(
   10662                        BaseType, MoveAssignOperator->getTypeQualifiers()),
   10663                    VK_LValue, BasePath);
   10664 
   10665     // Build the move.
   10666     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
   10667                                             To, From,
   10668                                             /*CopyingBaseSubobject=*/true,
   10669                                             /*Copying=*/false);
   10670     if (Move.isInvalid()) {
   10671       Diag(CurrentLocation, diag::note_member_synthesized_at)
   10672         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
   10673       MoveAssignOperator->setInvalidDecl();
   10674       return;
   10675     }
   10676 
   10677     // Success! Record the move.
   10678     Statements.push_back(Move.getAs<Expr>());
   10679   }
   10680 
   10681   // Assign non-static members.
   10682   for (auto *Field : ClassDecl->fields()) {
   10683     // FIXME: We should form some kind of AST representation for the implied
   10684     // memcpy in a union copy operation.
   10685     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
   10686       continue;
   10687 
   10688     if (Field->isInvalidDecl()) {
   10689       Invalid = true;
   10690       continue;
   10691     }
   10692 
   10693     // Check for members of reference type; we can't move those.
   10694     if (Field->getType()->isReferenceType()) {
   10695       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
   10696         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
   10697       Diag(Field->getLocation(), diag::note_declared_at);
   10698       Diag(CurrentLocation, diag::note_member_synthesized_at)
   10699         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
   10700       Invalid = true;
   10701       continue;
   10702     }
   10703 
   10704     // Check for members of const-qualified, non-class type.
   10705     QualType BaseType = Context.getBaseElementType(Field->getType());
   10706     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
   10707       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
   10708         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
   10709       Diag(Field->getLocation(), diag::note_declared_at);
   10710       Diag(CurrentLocation, diag::note_member_synthesized_at)
   10711         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
   10712       Invalid = true;
   10713       continue;
   10714     }
   10715 
   10716     // Suppress assigning zero-width bitfields.
   10717     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
   10718       continue;
   10719 
   10720     QualType FieldType = Field->getType().getNonReferenceType();
   10721     if (FieldType->isIncompleteArrayType()) {
   10722       assert(ClassDecl->hasFlexibleArrayMember() &&
   10723              "Incomplete array type is not valid");
   10724       continue;
   10725     }
   10726 
   10727     // Build references to the field in the object we're copying from and to.
   10728     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
   10729                               LookupMemberName);
   10730     MemberLookup.addDecl(Field);
   10731     MemberLookup.resolveKind();
   10732     MemberBuilder From(MoveOther, OtherRefType,
   10733                        /*IsArrow=*/false, MemberLookup);
   10734     MemberBuilder To(This, getCurrentThisType(),
   10735                      /*IsArrow=*/true, MemberLookup);
   10736 
   10737     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
   10738         "Member reference with rvalue base must be rvalue except for reference "
   10739         "members, which aren't allowed for move assignment.");
   10740 
   10741     // Build the move of this field.
   10742     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
   10743                                             To, From,
   10744                                             /*CopyingBaseSubobject=*/false,
   10745                                             /*Copying=*/false);
   10746     if (Move.isInvalid()) {
   10747       Diag(CurrentLocation, diag::note_member_synthesized_at)
   10748         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
   10749       MoveAssignOperator->setInvalidDecl();
   10750       return;
   10751     }
   10752 
   10753     // Success! Record the copy.
   10754     Statements.push_back(Move.getAs<Stmt>());
   10755   }
   10756 
   10757   if (!Invalid) {
   10758     // Add a "return *this;"
   10759     ExprResult ThisObj =
   10760         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
   10761 
   10762     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
   10763     if (Return.isInvalid())
   10764       Invalid = true;
   10765     else {
   10766       Statements.push_back(Return.getAs<Stmt>());
   10767 
   10768       if (Trap.hasErrorOccurred()) {
   10769         Diag(CurrentLocation, diag::note_member_synthesized_at)
   10770           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
   10771         Invalid = true;
   10772       }
   10773     }
   10774   }
   10775 
   10776   // The exception specification is needed because we are defining the
   10777   // function.
   10778   ResolveExceptionSpec(CurrentLocation,
   10779                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
   10780 
   10781   if (Invalid) {
   10782     MoveAssignOperator->setInvalidDecl();
   10783     return;
   10784   }
   10785 
   10786   StmtResult Body;
   10787   {
   10788     CompoundScopeRAII CompoundScope(*this);
   10789     Body = ActOnCompoundStmt(Loc, Loc, Statements,
   10790                              /*isStmtExpr=*/false);
   10791     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
   10792   }
   10793   MoveAssignOperator->setBody(Body.getAs<Stmt>());
   10794 
   10795   if (ASTMutationListener *L = getASTMutationListener()) {
   10796     L->CompletedImplicitDefinition(MoveAssignOperator);
   10797   }
   10798 }
   10799 
   10800 Sema::ImplicitExceptionSpecification
   10801 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
   10802   CXXRecordDecl *ClassDecl = MD->getParent();
   10803 
   10804   ImplicitExceptionSpecification ExceptSpec(*this);
   10805   if (ClassDecl->isInvalidDecl())
   10806     return ExceptSpec;
   10807 
   10808   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
   10809   assert(T->getNumParams() >= 1 && "not a copy ctor");
   10810   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
   10811 
   10812   // C++ [except.spec]p14:
   10813   //   An implicitly declared special member function (Clause 12) shall have an
   10814   //   exception-specification. [...]
   10815   for (const auto &Base : ClassDecl->bases()) {
   10816     // Virtual bases are handled below.
   10817     if (Base.isVirtual())
   10818       continue;
   10819 
   10820     CXXRecordDecl *BaseClassDecl
   10821       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
   10822     if (CXXConstructorDecl *CopyConstructor =
   10823           LookupCopyingConstructor(BaseClassDecl, Quals))
   10824       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
   10825   }
   10826   for (const auto &Base : ClassDecl->vbases()) {
   10827     CXXRecordDecl *BaseClassDecl
   10828       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
   10829     if (CXXConstructorDecl *CopyConstructor =
   10830           LookupCopyingConstructor(BaseClassDecl, Quals))
   10831       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
   10832   }
   10833   for (const auto *Field : ClassDecl->fields()) {
   10834     QualType FieldType = Context.getBaseElementType(Field->getType());
   10835     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
   10836       if (CXXConstructorDecl *CopyConstructor =
   10837               LookupCopyingConstructor(FieldClassDecl,
   10838                                        Quals | FieldType.getCVRQualifiers()))
   10839       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
   10840     }
   10841   }
   10842 
   10843   return ExceptSpec;
   10844 }
   10845 
   10846 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
   10847                                                     CXXRecordDecl *ClassDecl) {
   10848   // C++ [class.copy]p4:
   10849   //   If the class definition does not explicitly declare a copy
   10850   //   constructor, one is declared implicitly.
   10851   assert(ClassDecl->needsImplicitCopyConstructor());
   10852 
   10853   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
   10854   if (DSM.isAlreadyBeingDeclared())
   10855     return nullptr;
   10856 
   10857   QualType ClassType = Context.getTypeDeclType(ClassDecl);
   10858   QualType ArgType = ClassType;
   10859   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
   10860   if (Const)
   10861     ArgType = ArgType.withConst();
   10862   ArgType = Context.getLValueReferenceType(ArgType);
   10863 
   10864   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   10865                                                      CXXCopyConstructor,
   10866                                                      Const);
   10867 
   10868   DeclarationName Name
   10869     = Context.DeclarationNames.getCXXConstructorName(
   10870                                            Context.getCanonicalType(ClassType));
   10871   SourceLocation ClassLoc = ClassDecl->getLocation();
   10872   DeclarationNameInfo NameInfo(Name, ClassLoc);
   10873 
   10874   //   An implicitly-declared copy constructor is an inline public
   10875   //   member of its class.
   10876   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
   10877       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
   10878       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
   10879       Constexpr);
   10880   CopyConstructor->setAccess(AS_public);
   10881   CopyConstructor->setDefaulted();
   10882 
   10883   if (getLangOpts().CUDA) {
   10884     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
   10885                                             CopyConstructor,
   10886                                             /* ConstRHS */ Const,
   10887                                             /* Diagnose */ false);
   10888   }
   10889 
   10890   // Build an exception specification pointing back at this member.
   10891   FunctionProtoType::ExtProtoInfo EPI =
   10892       getImplicitMethodEPI(*this, CopyConstructor);
   10893   CopyConstructor->setType(
   10894       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
   10895 
   10896   // Add the parameter to the constructor.
   10897   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
   10898                                                ClassLoc, ClassLoc,
   10899                                                /*IdentifierInfo=*/nullptr,
   10900                                                ArgType, /*TInfo=*/nullptr,
   10901                                                SC_None, nullptr);
   10902   CopyConstructor->setParams(FromParam);
   10903 
   10904   CopyConstructor->setTrivial(
   10905     ClassDecl->needsOverloadResolutionForCopyConstructor()
   10906       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
   10907       : ClassDecl->hasTrivialCopyConstructor());
   10908 
   10909   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
   10910     SetDeclDeleted(CopyConstructor, ClassLoc);
   10911 
   10912   // Note that we have declared this constructor.
   10913   ++ASTContext::NumImplicitCopyConstructorsDeclared;
   10914 
   10915   if (Scope *S = getScopeForContext(ClassDecl))
   10916     PushOnScopeChains(CopyConstructor, S, false);
   10917   ClassDecl->addDecl(CopyConstructor);
   10918 
   10919   return CopyConstructor;
   10920 }
   10921 
   10922 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
   10923                                    CXXConstructorDecl *CopyConstructor) {
   10924   assert((CopyConstructor->isDefaulted() &&
   10925           CopyConstructor->isCopyConstructor() &&
   10926           !CopyConstructor->doesThisDeclarationHaveABody() &&
   10927           !CopyConstructor->isDeleted()) &&
   10928          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
   10929 
   10930   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
   10931   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
   10932 
   10933   // C++11 [class.copy]p7:
   10934   //   The [definition of an implicitly declared copy constructor] is
   10935   //   deprecated if the class has a user-declared copy assignment operator
   10936   //   or a user-declared destructor.
   10937   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
   10938     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
   10939 
   10940   SynthesizedFunctionScope Scope(*this, CopyConstructor);
   10941   DiagnosticErrorTrap Trap(Diags);
   10942 
   10943   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
   10944       Trap.hasErrorOccurred()) {
   10945     Diag(CurrentLocation, diag::note_member_synthesized_at)
   10946       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
   10947     CopyConstructor->setInvalidDecl();
   10948   }  else {
   10949     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
   10950                              ? CopyConstructor->getLocEnd()
   10951                              : CopyConstructor->getLocation();
   10952     Sema::CompoundScopeRAII CompoundScope(*this);
   10953     CopyConstructor->setBody(
   10954         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
   10955   }
   10956 
   10957   // The exception specification is needed because we are defining the
   10958   // function.
   10959   ResolveExceptionSpec(CurrentLocation,
   10960                        CopyConstructor->getType()->castAs<FunctionProtoType>());
   10961 
   10962   CopyConstructor->markUsed(Context);
   10963   MarkVTableUsed(CurrentLocation, ClassDecl);
   10964 
   10965   if (ASTMutationListener *L = getASTMutationListener()) {
   10966     L->CompletedImplicitDefinition(CopyConstructor);
   10967   }
   10968 }
   10969 
   10970 Sema::ImplicitExceptionSpecification
   10971 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
   10972   CXXRecordDecl *ClassDecl = MD->getParent();
   10973 
   10974   // C++ [except.spec]p14:
   10975   //   An implicitly declared special member function (Clause 12) shall have an
   10976   //   exception-specification. [...]
   10977   ImplicitExceptionSpecification ExceptSpec(*this);
   10978   if (ClassDecl->isInvalidDecl())
   10979     return ExceptSpec;
   10980 
   10981   // Direct base-class constructors.
   10982   for (const auto &B : ClassDecl->bases()) {
   10983     if (B.isVirtual()) // Handled below.
   10984       continue;
   10985 
   10986     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
   10987       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   10988       CXXConstructorDecl *Constructor =
   10989           LookupMovingConstructor(BaseClassDecl, 0);
   10990       // If this is a deleted function, add it anyway. This might be conformant
   10991       // with the standard. This might not. I'm not sure. It might not matter.
   10992       if (Constructor)
   10993         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
   10994     }
   10995   }
   10996 
   10997   // Virtual base-class constructors.
   10998   for (const auto &B : ClassDecl->vbases()) {
   10999     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
   11000       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
   11001       CXXConstructorDecl *Constructor =
   11002           LookupMovingConstructor(BaseClassDecl, 0);
   11003       // If this is a deleted function, add it anyway. This might be conformant
   11004       // with the standard. This might not. I'm not sure. It might not matter.
   11005       if (Constructor)
   11006         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
   11007     }
   11008   }
   11009 
   11010   // Field constructors.
   11011   for (const auto *F : ClassDecl->fields()) {
   11012     QualType FieldType = Context.getBaseElementType(F->getType());
   11013     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
   11014       CXXConstructorDecl *Constructor =
   11015           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
   11016       // If this is a deleted function, add it anyway. This might be conformant
   11017       // with the standard. This might not. I'm not sure. It might not matter.
   11018       // In particular, the problem is that this function never gets called. It
   11019       // might just be ill-formed because this function attempts to refer to
   11020       // a deleted function here.
   11021       if (Constructor)
   11022         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
   11023     }
   11024   }
   11025 
   11026   return ExceptSpec;
   11027 }
   11028 
   11029 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
   11030                                                     CXXRecordDecl *ClassDecl) {
   11031   assert(ClassDecl->needsImplicitMoveConstructor());
   11032 
   11033   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
   11034   if (DSM.isAlreadyBeingDeclared())
   11035     return nullptr;
   11036 
   11037   QualType ClassType = Context.getTypeDeclType(ClassDecl);
   11038   QualType ArgType = Context.getRValueReferenceType(ClassType);
   11039 
   11040   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
   11041                                                      CXXMoveConstructor,
   11042                                                      false);
   11043 
   11044   DeclarationName Name
   11045     = Context.DeclarationNames.getCXXConstructorName(
   11046                                            Context.getCanonicalType(ClassType));
   11047   SourceLocation ClassLoc = ClassDecl->getLocation();
   11048   DeclarationNameInfo NameInfo(Name, ClassLoc);
   11049 
   11050   // C++11 [class.copy]p11:
   11051   //   An implicitly-declared copy/move constructor is an inline public
   11052   //   member of its class.
   11053   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
   11054       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
   11055       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
   11056       Constexpr);
   11057   MoveConstructor->setAccess(AS_public);
   11058   MoveConstructor->setDefaulted();
   11059 
   11060   if (getLangOpts().CUDA) {
   11061     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
   11062                                             MoveConstructor,
   11063                                             /* ConstRHS */ false,
   11064                                             /* Diagnose */ false);
   11065   }
   11066 
   11067   // Build an exception specification pointing back at this member.
   11068   FunctionProtoType::ExtProtoInfo EPI =
   11069       getImplicitMethodEPI(*this, MoveConstructor);
   11070   MoveConstructor->setType(
   11071       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
   11072 
   11073   // Add the parameter to the constructor.
   11074   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
   11075                                                ClassLoc, ClassLoc,
   11076                                                /*IdentifierInfo=*/nullptr,
   11077                                                ArgType, /*TInfo=*/nullptr,
   11078                                                SC_None, nullptr);
   11079   MoveConstructor->setParams(FromParam);
   11080 
   11081   MoveConstructor->setTrivial(
   11082     ClassDecl->needsOverloadResolutionForMoveConstructor()
   11083       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
   11084       : ClassDecl->hasTrivialMoveConstructor());
   11085 
   11086   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
   11087     ClassDecl->setImplicitMoveConstructorIsDeleted();
   11088     SetDeclDeleted(MoveConstructor, ClassLoc);
   11089   }
   11090 
   11091   // Note that we have declared this constructor.
   11092   ++ASTContext::NumImplicitMoveConstructorsDeclared;
   11093 
   11094   if (Scope *S = getScopeForContext(ClassDecl))
   11095     PushOnScopeChains(MoveConstructor, S, false);
   11096   ClassDecl->addDecl(MoveConstructor);
   11097 
   11098   return MoveConstructor;
   11099 }
   11100 
   11101 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
   11102                                    CXXConstructorDecl *MoveConstructor) {
   11103   assert((MoveConstructor->isDefaulted() &&
   11104           MoveConstructor->isMoveConstructor() &&
   11105           !MoveConstructor->doesThisDeclarationHaveABody() &&
   11106           !MoveConstructor->isDeleted()) &&
   11107          "DefineImplicitMoveConstructor - call it for implicit move ctor");
   11108 
   11109   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
   11110   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
   11111 
   11112   SynthesizedFunctionScope Scope(*this, MoveConstructor);
   11113   DiagnosticErrorTrap Trap(Diags);
   11114 
   11115   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
   11116       Trap.hasErrorOccurred()) {
   11117     Diag(CurrentLocation, diag::note_member_synthesized_at)
   11118       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
   11119     MoveConstructor->setInvalidDecl();
   11120   }  else {
   11121     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
   11122                              ? MoveConstructor->getLocEnd()
   11123                              : MoveConstructor->getLocation();
   11124     Sema::CompoundScopeRAII CompoundScope(*this);
   11125     MoveConstructor->setBody(ActOnCompoundStmt(
   11126         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
   11127   }
   11128 
   11129   // The exception specification is needed because we are defining the
   11130   // function.
   11131   ResolveExceptionSpec(CurrentLocation,
   11132                        MoveConstructor->getType()->castAs<FunctionProtoType>());
   11133 
   11134   MoveConstructor->markUsed(Context);
   11135   MarkVTableUsed(CurrentLocation, ClassDecl);
   11136 
   11137   if (ASTMutationListener *L = getASTMutationListener()) {
   11138     L->CompletedImplicitDefinition(MoveConstructor);
   11139   }
   11140 }
   11141 
   11142 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
   11143   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
   11144 }
   11145 
   11146 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
   11147                             SourceLocation CurrentLocation,
   11148                             CXXConversionDecl *Conv) {
   11149   CXXRecordDecl *Lambda = Conv->getParent();
   11150   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
   11151   // If we are defining a specialization of a conversion to function-ptr
   11152   // cache the deduced template arguments for this specialization
   11153   // so that we can use them to retrieve the corresponding call-operator
   11154   // and static-invoker.
   11155   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
   11156 
   11157   // Retrieve the corresponding call-operator specialization.
   11158   if (Lambda->isGenericLambda()) {
   11159     assert(Conv->isFunctionTemplateSpecialization());
   11160     FunctionTemplateDecl *CallOpTemplate =
   11161         CallOp->getDescribedFunctionTemplate();
   11162     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
   11163     void *InsertPos = nullptr;
   11164     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
   11165                                                 DeducedTemplateArgs->asArray(),
   11166                                                 InsertPos);
   11167     assert(CallOpSpec &&
   11168           "Conversion operator must have a corresponding call operator");
   11169     CallOp = cast<CXXMethodDecl>(CallOpSpec);
   11170   }
   11171   // Mark the call operator referenced (and add to pending instantiations
   11172   // if necessary).
   11173   // For both the conversion and static-invoker template specializations
   11174   // we construct their body's in this function, so no need to add them
   11175   // to the PendingInstantiations.
   11176   MarkFunctionReferenced(CurrentLocation, CallOp);
   11177 
   11178   SynthesizedFunctionScope Scope(*this, Conv);
   11179   DiagnosticErrorTrap Trap(Diags);
   11180 
   11181   // Retrieve the static invoker...
   11182   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
   11183   // ... and get the corresponding specialization for a generic lambda.
   11184   if (Lambda->isGenericLambda()) {
   11185     assert(DeducedTemplateArgs &&
   11186       "Must have deduced template arguments from Conversion Operator");
   11187     FunctionTemplateDecl *InvokeTemplate =
   11188                           Invoker->getDescribedFunctionTemplate();
   11189     void *InsertPos = nullptr;
   11190     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
   11191                                                 DeducedTemplateArgs->asArray(),
   11192                                                 InsertPos);
   11193     assert(InvokeSpec &&
   11194       "Must have a corresponding static invoker specialization");
   11195     Invoker = cast<CXXMethodDecl>(InvokeSpec);
   11196   }
   11197   // Construct the body of the conversion function { return __invoke; }.
   11198   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
   11199                                         VK_LValue, Conv->getLocation()).get();
   11200    assert(FunctionRef && "Can't refer to __invoke function?");
   11201    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
   11202    Conv->setBody(new (Context) CompoundStmt(Context, Return,
   11203                                             Conv->getLocation(),
   11204                                             Conv->getLocation()));
   11205 
   11206   Conv->markUsed(Context);
   11207   Conv->setReferenced();
   11208 
   11209   // Fill in the __invoke function with a dummy implementation. IR generation
   11210   // will fill in the actual details.
   11211   Invoker->markUsed(Context);
   11212   Invoker->setReferenced();
   11213   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
   11214 
   11215   if (ASTMutationListener *L = getASTMutationListener()) {
   11216     L->CompletedImplicitDefinition(Conv);
   11217     L->CompletedImplicitDefinition(Invoker);
   11218    }
   11219 }
   11220 
   11221 
   11222 
   11223 void Sema::DefineImplicitLambdaToBlockPointerConversion(
   11224        SourceLocation CurrentLocation,
   11225        CXXConversionDecl *Conv)
   11226 {
   11227   assert(!Conv->getParent()->isGenericLambda());
   11228 
   11229   Conv->markUsed(Context);
   11230 
   11231   SynthesizedFunctionScope Scope(*this, Conv);
   11232   DiagnosticErrorTrap Trap(Diags);
   11233 
   11234   // Copy-initialize the lambda object as needed to capture it.
   11235   Expr *This = ActOnCXXThis(CurrentLocation).get();
   11236   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
   11237 
   11238   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
   11239                                                         Conv->getLocation(),
   11240                                                         Conv, DerefThis);
   11241 
   11242   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
   11243   // behavior.  Note that only the general conversion function does this
   11244   // (since it's unusable otherwise); in the case where we inline the
   11245   // block literal, it has block literal lifetime semantics.
   11246   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
   11247     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
   11248                                           CK_CopyAndAutoreleaseBlockObject,
   11249                                           BuildBlock.get(), nullptr, VK_RValue);
   11250 
   11251   if (BuildBlock.isInvalid()) {
   11252     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
   11253     Conv->setInvalidDecl();
   11254     return;
   11255   }
   11256 
   11257   // Create the return statement that returns the block from the conversion
   11258   // function.
   11259   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
   11260   if (Return.isInvalid()) {
   11261     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
   11262     Conv->setInvalidDecl();
   11263     return;
   11264   }
   11265 
   11266   // Set the body of the conversion function.
   11267   Stmt *ReturnS = Return.get();
   11268   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
   11269                                            Conv->getLocation(),
   11270                                            Conv->getLocation()));
   11271 
   11272   // We're done; notify the mutation listener, if any.
   11273   if (ASTMutationListener *L = getASTMutationListener()) {
   11274     L->CompletedImplicitDefinition(Conv);
   11275   }
   11276 }
   11277 
   11278 /// \brief Determine whether the given list arguments contains exactly one
   11279 /// "real" (non-default) argument.
   11280 static bool hasOneRealArgument(MultiExprArg Args) {
   11281   switch (Args.size()) {
   11282   case 0:
   11283     return false;
   11284 
   11285   default:
   11286     if (!Args[1]->isDefaultArgument())
   11287       return false;
   11288 
   11289     // fall through
   11290   case 1:
   11291     return !Args[0]->isDefaultArgument();
   11292   }
   11293 
   11294   return false;
   11295 }
   11296 
   11297 ExprResult
   11298 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   11299                             CXXConstructorDecl *Constructor,
   11300                             MultiExprArg ExprArgs,
   11301                             bool HadMultipleCandidates,
   11302                             bool IsListInitialization,
   11303                             bool IsStdInitListInitialization,
   11304                             bool RequiresZeroInit,
   11305                             unsigned ConstructKind,
   11306                             SourceRange ParenRange) {
   11307   bool Elidable = false;
   11308 
   11309   // C++0x [class.copy]p34:
   11310   //   When certain criteria are met, an implementation is allowed to
   11311   //   omit the copy/move construction of a class object, even if the
   11312   //   copy/move constructor and/or destructor for the object have
   11313   //   side effects. [...]
   11314   //     - when a temporary class object that has not been bound to a
   11315   //       reference (12.2) would be copied/moved to a class object
   11316   //       with the same cv-unqualified type, the copy/move operation
   11317   //       can be omitted by constructing the temporary object
   11318   //       directly into the target of the omitted copy/move
   11319   if (ConstructKind == CXXConstructExpr::CK_Complete &&
   11320       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
   11321     Expr *SubExpr = ExprArgs[0];
   11322     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
   11323   }
   11324 
   11325   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
   11326                                Elidable, ExprArgs, HadMultipleCandidates,
   11327                                IsListInitialization,
   11328                                IsStdInitListInitialization, RequiresZeroInit,
   11329                                ConstructKind, ParenRange);
   11330 }
   11331 
   11332 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
   11333 /// including handling of its default argument expressions.
   11334 ExprResult
   11335 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
   11336                             CXXConstructorDecl *Constructor, bool Elidable,
   11337                             MultiExprArg ExprArgs,
   11338                             bool HadMultipleCandidates,
   11339                             bool IsListInitialization,
   11340                             bool IsStdInitListInitialization,
   11341                             bool RequiresZeroInit,
   11342                             unsigned ConstructKind,
   11343                             SourceRange ParenRange) {
   11344   MarkFunctionReferenced(ConstructLoc, Constructor);
   11345   return CXXConstructExpr::Create(
   11346       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
   11347       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
   11348       RequiresZeroInit,
   11349       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
   11350       ParenRange);
   11351 }
   11352 
   11353 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
   11354   assert(Field->hasInClassInitializer());
   11355 
   11356   // If we already have the in-class initializer nothing needs to be done.
   11357   if (Field->getInClassInitializer())
   11358     return CXXDefaultInitExpr::Create(Context, Loc, Field);
   11359 
   11360   // Maybe we haven't instantiated the in-class initializer. Go check the
   11361   // pattern FieldDecl to see if it has one.
   11362   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
   11363 
   11364   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
   11365     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
   11366     DeclContext::lookup_result Lookup =
   11367         ClassPattern->lookup(Field->getDeclName());
   11368     assert(Lookup.size() == 1);
   11369     FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
   11370     if (InstantiateInClassInitializer(Loc, Field, Pattern,
   11371                                       getTemplateInstantiationArgs(Field)))
   11372       return ExprError();
   11373     return CXXDefaultInitExpr::Create(Context, Loc, Field);
   11374   }
   11375 
   11376   // DR1351:
   11377   //   If the brace-or-equal-initializer of a non-static data member
   11378   //   invokes a defaulted default constructor of its class or of an
   11379   //   enclosing class in a potentially evaluated subexpression, the
   11380   //   program is ill-formed.
   11381   //
   11382   // This resolution is unworkable: the exception specification of the
   11383   // default constructor can be needed in an unevaluated context, in
   11384   // particular, in the operand of a noexcept-expression, and we can be
   11385   // unable to compute an exception specification for an enclosed class.
   11386   //
   11387   // Any attempt to resolve the exception specification of a defaulted default
   11388   // constructor before the initializer is lexically complete will ultimately
   11389   // come here at which point we can diagnose it.
   11390   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
   11391   if (OutermostClass == ParentRD) {
   11392     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
   11393         << ParentRD << Field;
   11394   } else {
   11395     Diag(Field->getLocEnd(),
   11396          diag::err_in_class_initializer_not_yet_parsed_outer_class)
   11397         << ParentRD << OutermostClass << Field;
   11398   }
   11399 
   11400   return ExprError();
   11401 }
   11402 
   11403 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
   11404   if (VD->isInvalidDecl()) return;
   11405 
   11406   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
   11407   if (ClassDecl->isInvalidDecl()) return;
   11408   if (ClassDecl->hasIrrelevantDestructor()) return;
   11409   if (ClassDecl->isDependentContext()) return;
   11410 
   11411   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
   11412   MarkFunctionReferenced(VD->getLocation(), Destructor);
   11413   CheckDestructorAccess(VD->getLocation(), Destructor,
   11414                         PDiag(diag::err_access_dtor_var)
   11415                         << VD->getDeclName()
   11416                         << VD->getType());
   11417   DiagnoseUseOfDecl(Destructor, VD->getLocation());
   11418 
   11419   if (Destructor->isTrivial()) return;
   11420   if (!VD->hasGlobalStorage()) return;
   11421 
   11422   // Emit warning for non-trivial dtor in global scope (a real global,
   11423   // class-static, function-static).
   11424   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
   11425 
   11426   // TODO: this should be re-enabled for static locals by !CXAAtExit
   11427   if (!VD->isStaticLocal())
   11428     Diag(VD->getLocation(), diag::warn_global_destructor);
   11429 }
   11430 
   11431 /// \brief Given a constructor and the set of arguments provided for the
   11432 /// constructor, convert the arguments and add any required default arguments
   11433 /// to form a proper call to this constructor.
   11434 ///
   11435 /// \returns true if an error occurred, false otherwise.
   11436 bool
   11437 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
   11438                               MultiExprArg ArgsPtr,
   11439                               SourceLocation Loc,
   11440                               SmallVectorImpl<Expr*> &ConvertedArgs,
   11441                               bool AllowExplicit,
   11442                               bool IsListInitialization) {
   11443   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
   11444   unsigned NumArgs = ArgsPtr.size();
   11445   Expr **Args = ArgsPtr.data();
   11446 
   11447   const FunctionProtoType *Proto
   11448     = Constructor->getType()->getAs<FunctionProtoType>();
   11449   assert(Proto && "Constructor without a prototype?");
   11450   unsigned NumParams = Proto->getNumParams();
   11451 
   11452   // If too few arguments are available, we'll fill in the rest with defaults.
   11453   if (NumArgs < NumParams)
   11454     ConvertedArgs.reserve(NumParams);
   11455   else
   11456     ConvertedArgs.reserve(NumArgs);
   11457 
   11458   VariadicCallType CallType =
   11459     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
   11460   SmallVector<Expr *, 8> AllArgs;
   11461   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
   11462                                         Proto, 0,
   11463                                         llvm::makeArrayRef(Args, NumArgs),
   11464                                         AllArgs,
   11465                                         CallType, AllowExplicit,
   11466                                         IsListInitialization);
   11467   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
   11468 
   11469   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
   11470 
   11471   CheckConstructorCall(Constructor,
   11472                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
   11473                        Proto, Loc);
   11474 
   11475   return Invalid;
   11476 }
   11477 
   11478 static inline bool
   11479 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
   11480                                        const FunctionDecl *FnDecl) {
   11481   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
   11482   if (isa<NamespaceDecl>(DC)) {
   11483     return SemaRef.Diag(FnDecl->getLocation(),
   11484                         diag::err_operator_new_delete_declared_in_namespace)
   11485       << FnDecl->getDeclName();
   11486   }
   11487 
   11488   if (isa<TranslationUnitDecl>(DC) &&
   11489       FnDecl->getStorageClass() == SC_Static) {
   11490     return SemaRef.Diag(FnDecl->getLocation(),
   11491                         diag::err_operator_new_delete_declared_static)
   11492       << FnDecl->getDeclName();
   11493   }
   11494 
   11495   return false;
   11496 }
   11497 
   11498 static inline bool
   11499 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
   11500                             CanQualType ExpectedResultType,
   11501                             CanQualType ExpectedFirstParamType,
   11502                             unsigned DependentParamTypeDiag,
   11503                             unsigned InvalidParamTypeDiag) {
   11504   QualType ResultType =
   11505       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
   11506 
   11507   // Check that the result type is not dependent.
   11508   if (ResultType->isDependentType())
   11509     return SemaRef.Diag(FnDecl->getLocation(),
   11510                         diag::err_operator_new_delete_dependent_result_type)
   11511     << FnDecl->getDeclName() << ExpectedResultType;
   11512 
   11513   // Check that the result type is what we expect.
   11514   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
   11515     return SemaRef.Diag(FnDecl->getLocation(),
   11516                         diag::err_operator_new_delete_invalid_result_type)
   11517     << FnDecl->getDeclName() << ExpectedResultType;
   11518 
   11519   // A function template must have at least 2 parameters.
   11520   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
   11521     return SemaRef.Diag(FnDecl->getLocation(),
   11522                       diag::err_operator_new_delete_template_too_few_parameters)
   11523         << FnDecl->getDeclName();
   11524 
   11525   // The function decl must have at least 1 parameter.
   11526   if (FnDecl->getNumParams() == 0)
   11527     return SemaRef.Diag(FnDecl->getLocation(),
   11528                         diag::err_operator_new_delete_too_few_parameters)
   11529       << FnDecl->getDeclName();
   11530 
   11531   // Check the first parameter type is not dependent.
   11532   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
   11533   if (FirstParamType->isDependentType())
   11534     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
   11535       << FnDecl->getDeclName() << ExpectedFirstParamType;
   11536 
   11537   // Check that the first parameter type is what we expect.
   11538   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
   11539       ExpectedFirstParamType)
   11540     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
   11541     << FnDecl->getDeclName() << ExpectedFirstParamType;
   11542 
   11543   return false;
   11544 }
   11545 
   11546 static bool
   11547 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
   11548   // C++ [basic.stc.dynamic.allocation]p1:
   11549   //   A program is ill-formed if an allocation function is declared in a
   11550   //   namespace scope other than global scope or declared static in global
   11551   //   scope.
   11552   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
   11553     return true;
   11554 
   11555   CanQualType SizeTy =
   11556     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
   11557 
   11558   // C++ [basic.stc.dynamic.allocation]p1:
   11559   //  The return type shall be void*. The first parameter shall have type
   11560   //  std::size_t.
   11561   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
   11562                                   SizeTy,
   11563                                   diag::err_operator_new_dependent_param_type,
   11564                                   diag::err_operator_new_param_type))
   11565     return true;
   11566 
   11567   // C++ [basic.stc.dynamic.allocation]p1:
   11568   //  The first parameter shall not have an associated default argument.
   11569   if (FnDecl->getParamDecl(0)->hasDefaultArg())
   11570     return SemaRef.Diag(FnDecl->getLocation(),
   11571                         diag::err_operator_new_default_arg)
   11572       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
   11573 
   11574   return false;
   11575 }
   11576 
   11577 static bool
   11578 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
   11579   // C++ [basic.stc.dynamic.deallocation]p1:
   11580   //   A program is ill-formed if deallocation functions are declared in a
   11581   //   namespace scope other than global scope or declared static in global
   11582   //   scope.
   11583   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
   11584     return true;
   11585 
   11586   // C++ [basic.stc.dynamic.deallocation]p2:
   11587   //   Each deallocation function shall return void and its first parameter
   11588   //   shall be void*.
   11589   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
   11590                                   SemaRef.Context.VoidPtrTy,
   11591                                  diag::err_operator_delete_dependent_param_type,
   11592                                  diag::err_operator_delete_param_type))
   11593     return true;
   11594 
   11595   return false;
   11596 }
   11597 
   11598 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
   11599 /// of this overloaded operator is well-formed. If so, returns false;
   11600 /// otherwise, emits appropriate diagnostics and returns true.
   11601 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
   11602   assert(FnDecl && FnDecl->isOverloadedOperator() &&
   11603          "Expected an overloaded operator declaration");
   11604 
   11605   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
   11606 
   11607   // C++ [over.oper]p5:
   11608   //   The allocation and deallocation functions, operator new,
   11609   //   operator new[], operator delete and operator delete[], are
   11610   //   described completely in 3.7.3. The attributes and restrictions
   11611   //   found in the rest of this subclause do not apply to them unless
   11612   //   explicitly stated in 3.7.3.
   11613   if (Op == OO_Delete || Op == OO_Array_Delete)
   11614     return CheckOperatorDeleteDeclaration(*this, FnDecl);
   11615 
   11616   if (Op == OO_New || Op == OO_Array_New)
   11617     return CheckOperatorNewDeclaration(*this, FnDecl);
   11618 
   11619   // C++ [over.oper]p6:
   11620   //   An operator function shall either be a non-static member
   11621   //   function or be a non-member function and have at least one
   11622   //   parameter whose type is a class, a reference to a class, an
   11623   //   enumeration, or a reference to an enumeration.
   11624   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
   11625     if (MethodDecl->isStatic())
   11626       return Diag(FnDecl->getLocation(),
   11627                   diag::err_operator_overload_static) << FnDecl->getDeclName();
   11628   } else {
   11629     bool ClassOrEnumParam = false;
   11630     for (auto Param : FnDecl->params()) {
   11631       QualType ParamType = Param->getType().getNonReferenceType();
   11632       if (ParamType->isDependentType() || ParamType->isRecordType() ||
   11633           ParamType->isEnumeralType()) {
   11634         ClassOrEnumParam = true;
   11635         break;
   11636       }
   11637     }
   11638 
   11639     if (!ClassOrEnumParam)
   11640       return Diag(FnDecl->getLocation(),
   11641                   diag::err_operator_overload_needs_class_or_enum)
   11642         << FnDecl->getDeclName();
   11643   }
   11644 
   11645   // C++ [over.oper]p8:
   11646   //   An operator function cannot have default arguments (8.3.6),
   11647   //   except where explicitly stated below.
   11648   //
   11649   // Only the function-call operator allows default arguments
   11650   // (C++ [over.call]p1).
   11651   if (Op != OO_Call) {
   11652     for (auto Param : FnDecl->params()) {
   11653       if (Param->hasDefaultArg())
   11654         return Diag(Param->getLocation(),
   11655                     diag::err_operator_overload_default_arg)
   11656           << FnDecl->getDeclName() << Param->getDefaultArgRange();
   11657     }
   11658   }
   11659 
   11660   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
   11661     { false, false, false }
   11662 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
   11663     , { Unary, Binary, MemberOnly }
   11664 #include "clang/Basic/OperatorKinds.def"
   11665   };
   11666 
   11667   bool CanBeUnaryOperator = OperatorUses[Op][0];
   11668   bool CanBeBinaryOperator = OperatorUses[Op][1];
   11669   bool MustBeMemberOperator = OperatorUses[Op][2];
   11670 
   11671   // C++ [over.oper]p8:
   11672   //   [...] Operator functions cannot have more or fewer parameters
   11673   //   than the number required for the corresponding operator, as
   11674   //   described in the rest of this subclause.
   11675   unsigned NumParams = FnDecl->getNumParams()
   11676                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
   11677   if (Op != OO_Call &&
   11678       ((NumParams == 1 && !CanBeUnaryOperator) ||
   11679        (NumParams == 2 && !CanBeBinaryOperator) ||
   11680        (NumParams < 1) || (NumParams > 2))) {
   11681     // We have the wrong number of parameters.
   11682     unsigned ErrorKind;
   11683     if (CanBeUnaryOperator && CanBeBinaryOperator) {
   11684       ErrorKind = 2;  // 2 -> unary or binary.
   11685     } else if (CanBeUnaryOperator) {
   11686       ErrorKind = 0;  // 0 -> unary
   11687     } else {
   11688       assert(CanBeBinaryOperator &&
   11689              "All non-call overloaded operators are unary or binary!");
   11690       ErrorKind = 1;  // 1 -> binary
   11691     }
   11692 
   11693     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
   11694       << FnDecl->getDeclName() << NumParams << ErrorKind;
   11695   }
   11696 
   11697   // Overloaded operators other than operator() cannot be variadic.
   11698   if (Op != OO_Call &&
   11699       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
   11700     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
   11701       << FnDecl->getDeclName();
   11702   }
   11703 
   11704   // Some operators must be non-static member functions.
   11705   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
   11706     return Diag(FnDecl->getLocation(),
   11707                 diag::err_operator_overload_must_be_member)
   11708       << FnDecl->getDeclName();
   11709   }
   11710 
   11711   // C++ [over.inc]p1:
   11712   //   The user-defined function called operator++ implements the
   11713   //   prefix and postfix ++ operator. If this function is a member
   11714   //   function with no parameters, or a non-member function with one
   11715   //   parameter of class or enumeration type, it defines the prefix
   11716   //   increment operator ++ for objects of that type. If the function
   11717   //   is a member function with one parameter (which shall be of type
   11718   //   int) or a non-member function with two parameters (the second
   11719   //   of which shall be of type int), it defines the postfix
   11720   //   increment operator ++ for objects of that type.
   11721   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
   11722     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
   11723     QualType ParamType = LastParam->getType();
   11724 
   11725     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
   11726         !ParamType->isDependentType())
   11727       return Diag(LastParam->getLocation(),
   11728                   diag::err_operator_overload_post_incdec_must_be_int)
   11729         << LastParam->getType() << (Op == OO_MinusMinus);
   11730   }
   11731 
   11732   return false;
   11733 }
   11734 
   11735 /// CheckLiteralOperatorDeclaration - Check whether the declaration
   11736 /// of this literal operator function is well-formed. If so, returns
   11737 /// false; otherwise, emits appropriate diagnostics and returns true.
   11738 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
   11739   if (isa<CXXMethodDecl>(FnDecl)) {
   11740     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
   11741       << FnDecl->getDeclName();
   11742     return true;
   11743   }
   11744 
   11745   if (FnDecl->isExternC()) {
   11746     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
   11747     return true;
   11748   }
   11749 
   11750   bool Valid = false;
   11751 
   11752   // This might be the definition of a literal operator template.
   11753   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
   11754   // This might be a specialization of a literal operator template.
   11755   if (!TpDecl)
   11756     TpDecl = FnDecl->getPrimaryTemplate();
   11757 
   11758   // template <char...> type operator "" name() and
   11759   // template <class T, T...> type operator "" name() are the only valid
   11760   // template signatures, and the only valid signatures with no parameters.
   11761   if (TpDecl) {
   11762     if (FnDecl->param_size() == 0) {
   11763       // Must have one or two template parameters
   11764       TemplateParameterList *Params = TpDecl->getTemplateParameters();
   11765       if (Params->size() == 1) {
   11766         NonTypeTemplateParmDecl *PmDecl =
   11767           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
   11768 
   11769         // The template parameter must be a char parameter pack.
   11770         if (PmDecl && PmDecl->isTemplateParameterPack() &&
   11771             Context.hasSameType(PmDecl->getType(), Context.CharTy))
   11772           Valid = true;
   11773       } else if (Params->size() == 2) {
   11774         TemplateTypeParmDecl *PmType =
   11775           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
   11776         NonTypeTemplateParmDecl *PmArgs =
   11777           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
   11778 
   11779         // The second template parameter must be a parameter pack with the
   11780         // first template parameter as its type.
   11781         if (PmType && PmArgs &&
   11782             !PmType->isTemplateParameterPack() &&
   11783             PmArgs->isTemplateParameterPack()) {
   11784           const TemplateTypeParmType *TArgs =
   11785             PmArgs->getType()->getAs<TemplateTypeParmType>();
   11786           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
   11787               TArgs->getIndex() == PmType->getIndex()) {
   11788             Valid = true;
   11789             if (ActiveTemplateInstantiations.empty())
   11790               Diag(FnDecl->getLocation(),
   11791                    diag::ext_string_literal_operator_template);
   11792           }
   11793         }
   11794       }
   11795     }
   11796   } else if (FnDecl->param_size()) {
   11797     // Check the first parameter
   11798     FunctionDecl::param_iterator Param = FnDecl->param_begin();
   11799 
   11800     QualType T = (*Param)->getType().getUnqualifiedType();
   11801 
   11802     // unsigned long long int, long double, and any character type are allowed
   11803     // as the only parameters.
   11804     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
   11805         Context.hasSameType(T, Context.LongDoubleTy) ||
   11806         Context.hasSameType(T, Context.CharTy) ||
   11807         Context.hasSameType(T, Context.WideCharTy) ||
   11808         Context.hasSameType(T, Context.Char16Ty) ||
   11809         Context.hasSameType(T, Context.Char32Ty)) {
   11810       if (++Param == FnDecl->param_end())
   11811         Valid = true;
   11812       goto FinishedParams;
   11813     }
   11814 
   11815     // Otherwise it must be a pointer to const; let's strip those qualifiers.
   11816     const PointerType *PT = T->getAs<PointerType>();
   11817     if (!PT)
   11818       goto FinishedParams;
   11819     T = PT->getPointeeType();
   11820     if (!T.isConstQualified() || T.isVolatileQualified())
   11821       goto FinishedParams;
   11822     T = T.getUnqualifiedType();
   11823 
   11824     // Move on to the second parameter;
   11825     ++Param;
   11826 
   11827     // If there is no second parameter, the first must be a const char *
   11828     if (Param == FnDecl->param_end()) {
   11829       if (Context.hasSameType(T, Context.CharTy))
   11830         Valid = true;
   11831       goto FinishedParams;
   11832     }
   11833 
   11834     // const char *, const wchar_t*, const char16_t*, and const char32_t*
   11835     // are allowed as the first parameter to a two-parameter function
   11836     if (!(Context.hasSameType(T, Context.CharTy) ||
   11837           Context.hasSameType(T, Context.WideCharTy) ||
   11838           Context.hasSameType(T, Context.Char16Ty) ||
   11839           Context.hasSameType(T, Context.Char32Ty)))
   11840       goto FinishedParams;
   11841 
   11842     // The second and final parameter must be an std::size_t
   11843     T = (*Param)->getType().getUnqualifiedType();
   11844     if (Context.hasSameType(T, Context.getSizeType()) &&
   11845         ++Param == FnDecl->param_end())
   11846       Valid = true;
   11847   }
   11848 
   11849   // FIXME: This diagnostic is absolutely terrible.
   11850 FinishedParams:
   11851   if (!Valid) {
   11852     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
   11853       << FnDecl->getDeclName();
   11854     return true;
   11855   }
   11856 
   11857   // A parameter-declaration-clause containing a default argument is not
   11858   // equivalent to any of the permitted forms.
   11859   for (auto Param : FnDecl->params()) {
   11860     if (Param->hasDefaultArg()) {
   11861       Diag(Param->getDefaultArgRange().getBegin(),
   11862            diag::err_literal_operator_default_argument)
   11863         << Param->getDefaultArgRange();
   11864       break;
   11865     }
   11866   }
   11867 
   11868   StringRef LiteralName
   11869     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
   11870   if (LiteralName[0] != '_') {
   11871     // C++11 [usrlit.suffix]p1:
   11872     //   Literal suffix identifiers that do not start with an underscore
   11873     //   are reserved for future standardization.
   11874     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
   11875       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
   11876   }
   11877 
   11878   return false;
   11879 }
   11880 
   11881 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
   11882 /// linkage specification, including the language and (if present)
   11883 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
   11884 /// language string literal. LBraceLoc, if valid, provides the location of
   11885 /// the '{' brace. Otherwise, this linkage specification does not
   11886 /// have any braces.
   11887 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
   11888                                            Expr *LangStr,
   11889                                            SourceLocation LBraceLoc) {
   11890   StringLiteral *Lit = cast<StringLiteral>(LangStr);
   11891   if (!Lit->isAscii()) {
   11892     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
   11893       << LangStr->getSourceRange();
   11894     return nullptr;
   11895   }
   11896 
   11897   StringRef Lang = Lit->getString();
   11898   LinkageSpecDecl::LanguageIDs Language;
   11899   if (Lang == "C")
   11900     Language = LinkageSpecDecl::lang_c;
   11901   else if (Lang == "C++")
   11902     Language = LinkageSpecDecl::lang_cxx;
   11903   else {
   11904     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
   11905       << LangStr->getSourceRange();
   11906     return nullptr;
   11907   }
   11908 
   11909   // FIXME: Add all the various semantics of linkage specifications
   11910 
   11911   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
   11912                                                LangStr->getExprLoc(), Language,
   11913                                                LBraceLoc.isValid());
   11914   CurContext->addDecl(D);
   11915   PushDeclContext(S, D);
   11916   return D;
   11917 }
   11918 
   11919 /// ActOnFinishLinkageSpecification - Complete the definition of
   11920 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
   11921 /// valid, it's the position of the closing '}' brace in a linkage
   11922 /// specification that uses braces.
   11923 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
   11924                                             Decl *LinkageSpec,
   11925                                             SourceLocation RBraceLoc) {
   11926   if (RBraceLoc.isValid()) {
   11927     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
   11928     LSDecl->setRBraceLoc(RBraceLoc);
   11929   }
   11930   PopDeclContext();
   11931   return LinkageSpec;
   11932 }
   11933 
   11934 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
   11935                                   AttributeList *AttrList,
   11936                                   SourceLocation SemiLoc) {
   11937   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
   11938   // Attribute declarations appertain to empty declaration so we handle
   11939   // them here.
   11940   if (AttrList)
   11941     ProcessDeclAttributeList(S, ED, AttrList);
   11942 
   11943   CurContext->addDecl(ED);
   11944   return ED;
   11945 }
   11946 
   11947 /// \brief Perform semantic analysis for the variable declaration that
   11948 /// occurs within a C++ catch clause, returning the newly-created
   11949 /// variable.
   11950 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
   11951                                          TypeSourceInfo *TInfo,
   11952                                          SourceLocation StartLoc,
   11953                                          SourceLocation Loc,
   11954                                          IdentifierInfo *Name) {
   11955   bool Invalid = false;
   11956   QualType ExDeclType = TInfo->getType();
   11957 
   11958   // Arrays and functions decay.
   11959   if (ExDeclType->isArrayType())
   11960     ExDeclType = Context.getArrayDecayedType(ExDeclType);
   11961   else if (ExDeclType->isFunctionType())
   11962     ExDeclType = Context.getPointerType(ExDeclType);
   11963 
   11964   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
   11965   // The exception-declaration shall not denote a pointer or reference to an
   11966   // incomplete type, other than [cv] void*.
   11967   // N2844 forbids rvalue references.
   11968   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
   11969     Diag(Loc, diag::err_catch_rvalue_ref);
   11970     Invalid = true;
   11971   }
   11972 
   11973   QualType BaseType = ExDeclType;
   11974   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
   11975   unsigned DK = diag::err_catch_incomplete;
   11976   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
   11977     BaseType = Ptr->getPointeeType();
   11978     Mode = 1;
   11979     DK = diag::err_catch_incomplete_ptr;
   11980   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
   11981     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
   11982     BaseType = Ref->getPointeeType();
   11983     Mode = 2;
   11984     DK = diag::err_catch_incomplete_ref;
   11985   }
   11986   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
   11987       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
   11988     Invalid = true;
   11989 
   11990   if (!Invalid && !ExDeclType->isDependentType() &&
   11991       RequireNonAbstractType(Loc, ExDeclType,
   11992                              diag::err_abstract_type_in_decl,
   11993                              AbstractVariableType))
   11994     Invalid = true;
   11995 
   11996   // Only the non-fragile NeXT runtime currently supports C++ catches
   11997   // of ObjC types, and no runtime supports catching ObjC types by value.
   11998   if (!Invalid && getLangOpts().ObjC1) {
   11999     QualType T = ExDeclType;
   12000     if (const ReferenceType *RT = T->getAs<ReferenceType>())
   12001       T = RT->getPointeeType();
   12002 
   12003     if (T->isObjCObjectType()) {
   12004       Diag(Loc, diag::err_objc_object_catch);
   12005       Invalid = true;
   12006     } else if (T->isObjCObjectPointerType()) {
   12007       // FIXME: should this be a test for macosx-fragile specifically?
   12008       if (getLangOpts().ObjCRuntime.isFragile())
   12009         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
   12010     }
   12011   }
   12012 
   12013   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
   12014                                     ExDeclType, TInfo, SC_None);
   12015   ExDecl->setExceptionVariable(true);
   12016 
   12017   // In ARC, infer 'retaining' for variables of retainable type.
   12018   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
   12019     Invalid = true;
   12020 
   12021   if (!Invalid && !ExDeclType->isDependentType()) {
   12022     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
   12023       // Insulate this from anything else we might currently be parsing.
   12024       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
   12025 
   12026       // C++ [except.handle]p16:
   12027       //   The object declared in an exception-declaration or, if the
   12028       //   exception-declaration does not specify a name, a temporary (12.2) is
   12029       //   copy-initialized (8.5) from the exception object. [...]
   12030       //   The object is destroyed when the handler exits, after the destruction
   12031       //   of any automatic objects initialized within the handler.
   12032       //
   12033       // We just pretend to initialize the object with itself, then make sure
   12034       // it can be destroyed later.
   12035       QualType initType = Context.getExceptionObjectType(ExDeclType);
   12036 
   12037       InitializedEntity entity =
   12038         InitializedEntity::InitializeVariable(ExDecl);
   12039       InitializationKind initKind =
   12040         InitializationKind::CreateCopy(Loc, SourceLocation());
   12041 
   12042       Expr *opaqueValue =
   12043         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
   12044       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
   12045       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
   12046       if (result.isInvalid())
   12047         Invalid = true;
   12048       else {
   12049         // If the constructor used was non-trivial, set this as the
   12050         // "initializer".
   12051         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
   12052         if (!construct->getConstructor()->isTrivial()) {
   12053           Expr *init = MaybeCreateExprWithCleanups(construct);
   12054           ExDecl->setInit(init);
   12055         }
   12056 
   12057         // And make sure it's destructable.
   12058         FinalizeVarWithDestructor(ExDecl, recordType);
   12059       }
   12060     }
   12061   }
   12062 
   12063   if (Invalid)
   12064     ExDecl->setInvalidDecl();
   12065 
   12066   return ExDecl;
   12067 }
   12068 
   12069 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
   12070 /// handler.
   12071 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
   12072   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   12073   bool Invalid = D.isInvalidType();
   12074 
   12075   // Check for unexpanded parameter packs.
   12076   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
   12077                                       UPPC_ExceptionType)) {
   12078     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
   12079                                              D.getIdentifierLoc());
   12080     Invalid = true;
   12081   }
   12082 
   12083   IdentifierInfo *II = D.getIdentifier();
   12084   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
   12085                                              LookupOrdinaryName,
   12086                                              ForRedeclaration)) {
   12087     // The scope should be freshly made just for us. There is just no way
   12088     // it contains any previous declaration, except for function parameters in
   12089     // a function-try-block's catch statement.
   12090     assert(!S->isDeclScope(PrevDecl));
   12091     if (isDeclInScope(PrevDecl, CurContext, S)) {
   12092       Diag(D.getIdentifierLoc(), diag::err_redefinition)
   12093         << D.getIdentifier();
   12094       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
   12095       Invalid = true;
   12096     } else if (PrevDecl->isTemplateParameter())
   12097       // Maybe we will complain about the shadowed template parameter.
   12098       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
   12099   }
   12100 
   12101   if (D.getCXXScopeSpec().isSet() && !Invalid) {
   12102     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
   12103       << D.getCXXScopeSpec().getRange();
   12104     Invalid = true;
   12105   }
   12106 
   12107   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
   12108                                               D.getLocStart(),
   12109                                               D.getIdentifierLoc(),
   12110                                               D.getIdentifier());
   12111   if (Invalid)
   12112     ExDecl->setInvalidDecl();
   12113 
   12114   // Add the exception declaration into this scope.
   12115   if (II)
   12116     PushOnScopeChains(ExDecl, S);
   12117   else
   12118     CurContext->addDecl(ExDecl);
   12119 
   12120   ProcessDeclAttributes(S, ExDecl, D);
   12121   return ExDecl;
   12122 }
   12123 
   12124 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
   12125                                          Expr *AssertExpr,
   12126                                          Expr *AssertMessageExpr,
   12127                                          SourceLocation RParenLoc) {
   12128   StringLiteral *AssertMessage =
   12129       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
   12130 
   12131   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
   12132     return nullptr;
   12133 
   12134   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
   12135                                       AssertMessage, RParenLoc, false);
   12136 }
   12137 
   12138 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
   12139                                          Expr *AssertExpr,
   12140                                          StringLiteral *AssertMessage,
   12141                                          SourceLocation RParenLoc,
   12142                                          bool Failed) {
   12143   assert(AssertExpr != nullptr && "Expected non-null condition");
   12144   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
   12145       !Failed) {
   12146     // In a static_assert-declaration, the constant-expression shall be a
   12147     // constant expression that can be contextually converted to bool.
   12148     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
   12149     if (Converted.isInvalid())
   12150       Failed = true;
   12151 
   12152     llvm::APSInt Cond;
   12153     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
   12154           diag::err_static_assert_expression_is_not_constant,
   12155           /*AllowFold=*/false).isInvalid())
   12156       Failed = true;
   12157 
   12158     if (!Failed && !Cond) {
   12159       SmallString<256> MsgBuffer;
   12160       llvm::raw_svector_ostream Msg(MsgBuffer);
   12161       if (AssertMessage)
   12162         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
   12163       Diag(StaticAssertLoc, diag::err_static_assert_failed)
   12164         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
   12165       Failed = true;
   12166     }
   12167   }
   12168 
   12169   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
   12170                                         AssertExpr, AssertMessage, RParenLoc,
   12171                                         Failed);
   12172 
   12173   CurContext->addDecl(Decl);
   12174   return Decl;
   12175 }
   12176 
   12177 /// \brief Perform semantic analysis of the given friend type declaration.
   12178 ///
   12179 /// \returns A friend declaration that.
   12180 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
   12181                                       SourceLocation FriendLoc,
   12182                                       TypeSourceInfo *TSInfo) {
   12183   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
   12184 
   12185   QualType T = TSInfo->getType();
   12186   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
   12187 
   12188   // C++03 [class.friend]p2:
   12189   //   An elaborated-type-specifier shall be used in a friend declaration
   12190   //   for a class.*
   12191   //
   12192   //   * The class-key of the elaborated-type-specifier is required.
   12193   if (!ActiveTemplateInstantiations.empty()) {
   12194     // Do not complain about the form of friend template types during
   12195     // template instantiation; we will already have complained when the
   12196     // template was declared.
   12197   } else {
   12198     if (!T->isElaboratedTypeSpecifier()) {
   12199       // If we evaluated the type to a record type, suggest putting
   12200       // a tag in front.
   12201       if (const RecordType *RT = T->getAs<RecordType>()) {
   12202         RecordDecl *RD = RT->getDecl();
   12203 
   12204         SmallString<16> InsertionText(" ");
   12205         InsertionText += RD->getKindName();
   12206 
   12207         Diag(TypeRange.getBegin(),
   12208              getLangOpts().CPlusPlus11 ?
   12209                diag::warn_cxx98_compat_unelaborated_friend_type :
   12210                diag::ext_unelaborated_friend_type)
   12211           << (unsigned) RD->getTagKind()
   12212           << T
   12213           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
   12214                                         InsertionText);
   12215       } else {
   12216         Diag(FriendLoc,
   12217              getLangOpts().CPlusPlus11 ?
   12218                diag::warn_cxx98_compat_nonclass_type_friend :
   12219                diag::ext_nonclass_type_friend)
   12220           << T
   12221           << TypeRange;
   12222       }
   12223     } else if (T->getAs<EnumType>()) {
   12224       Diag(FriendLoc,
   12225            getLangOpts().CPlusPlus11 ?
   12226              diag::warn_cxx98_compat_enum_friend :
   12227              diag::ext_enum_friend)
   12228         << T
   12229         << TypeRange;
   12230     }
   12231 
   12232     // C++11 [class.friend]p3:
   12233     //   A friend declaration that does not declare a function shall have one
   12234     //   of the following forms:
   12235     //     friend elaborated-type-specifier ;
   12236     //     friend simple-type-specifier ;
   12237     //     friend typename-specifier ;
   12238     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
   12239       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
   12240   }
   12241 
   12242   //   If the type specifier in a friend declaration designates a (possibly
   12243   //   cv-qualified) class type, that class is declared as a friend; otherwise,
   12244   //   the friend declaration is ignored.
   12245   return FriendDecl::Create(Context, CurContext,
   12246                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
   12247                             FriendLoc);
   12248 }
   12249 
   12250 /// Handle a friend tag declaration where the scope specifier was
   12251 /// templated.
   12252 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
   12253                                     unsigned TagSpec, SourceLocation TagLoc,
   12254                                     CXXScopeSpec &SS,
   12255                                     IdentifierInfo *Name,
   12256                                     SourceLocation NameLoc,
   12257                                     AttributeList *Attr,
   12258                                     MultiTemplateParamsArg TempParamLists) {
   12259   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
   12260 
   12261   bool isExplicitSpecialization = false;
   12262   bool Invalid = false;
   12263 
   12264   if (TemplateParameterList *TemplateParams =
   12265           MatchTemplateParametersToScopeSpecifier(
   12266               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
   12267               isExplicitSpecialization, Invalid)) {
   12268     if (TemplateParams->size() > 0) {
   12269       // This is a declaration of a class template.
   12270       if (Invalid)
   12271         return nullptr;
   12272 
   12273       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
   12274                                 NameLoc, Attr, TemplateParams, AS_public,
   12275                                 /*ModulePrivateLoc=*/SourceLocation(),
   12276                                 FriendLoc, TempParamLists.size() - 1,
   12277                                 TempParamLists.data()).get();
   12278     } else {
   12279       // The "template<>" header is extraneous.
   12280       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
   12281         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
   12282       isExplicitSpecialization = true;
   12283     }
   12284   }
   12285 
   12286   if (Invalid) return nullptr;
   12287 
   12288   bool isAllExplicitSpecializations = true;
   12289   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
   12290     if (TempParamLists[I]->size()) {
   12291       isAllExplicitSpecializations = false;
   12292       break;
   12293     }
   12294   }
   12295 
   12296   // FIXME: don't ignore attributes.
   12297 
   12298   // If it's explicit specializations all the way down, just forget
   12299   // about the template header and build an appropriate non-templated
   12300   // friend.  TODO: for source fidelity, remember the headers.
   12301   if (isAllExplicitSpecializations) {
   12302     if (SS.isEmpty()) {
   12303       bool Owned = false;
   12304       bool IsDependent = false;
   12305       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
   12306                       Attr, AS_public,
   12307                       /*ModulePrivateLoc=*/SourceLocation(),
   12308                       MultiTemplateParamsArg(), Owned, IsDependent,
   12309                       /*ScopedEnumKWLoc=*/SourceLocation(),
   12310                       /*ScopedEnumUsesClassTag=*/false,
   12311                       /*UnderlyingType=*/TypeResult(),
   12312                       /*IsTypeSpecifier=*/false);
   12313     }
   12314 
   12315     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
   12316     ElaboratedTypeKeyword Keyword
   12317       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
   12318     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
   12319                                    *Name, NameLoc);
   12320     if (T.isNull())
   12321       return nullptr;
   12322 
   12323     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
   12324     if (isa<DependentNameType>(T)) {
   12325       DependentNameTypeLoc TL =
   12326           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
   12327       TL.setElaboratedKeywordLoc(TagLoc);
   12328       TL.setQualifierLoc(QualifierLoc);
   12329       TL.setNameLoc(NameLoc);
   12330     } else {
   12331       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
   12332       TL.setElaboratedKeywordLoc(TagLoc);
   12333       TL.setQualifierLoc(QualifierLoc);
   12334       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
   12335     }
   12336 
   12337     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
   12338                                             TSI, FriendLoc, TempParamLists);
   12339     Friend->setAccess(AS_public);
   12340     CurContext->addDecl(Friend);
   12341     return Friend;
   12342   }
   12343 
   12344   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
   12345 
   12346 
   12347 
   12348   // Handle the case of a templated-scope friend class.  e.g.
   12349   //   template <class T> class A<T>::B;
   12350   // FIXME: we don't support these right now.
   12351   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
   12352     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
   12353   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
   12354   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
   12355   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
   12356   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
   12357   TL.setElaboratedKeywordLoc(TagLoc);
   12358   TL.setQualifierLoc(SS.getWithLocInContext(Context));
   12359   TL.setNameLoc(NameLoc);
   12360 
   12361   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
   12362                                           TSI, FriendLoc, TempParamLists);
   12363   Friend->setAccess(AS_public);
   12364   Friend->setUnsupportedFriend(true);
   12365   CurContext->addDecl(Friend);
   12366   return Friend;
   12367 }
   12368 
   12369 
   12370 /// Handle a friend type declaration.  This works in tandem with
   12371 /// ActOnTag.
   12372 ///
   12373 /// Notes on friend class templates:
   12374 ///
   12375 /// We generally treat friend class declarations as if they were
   12376 /// declaring a class.  So, for example, the elaborated type specifier
   12377 /// in a friend declaration is required to obey the restrictions of a
   12378 /// class-head (i.e. no typedefs in the scope chain), template
   12379 /// parameters are required to match up with simple template-ids, &c.
   12380 /// However, unlike when declaring a template specialization, it's
   12381 /// okay to refer to a template specialization without an empty
   12382 /// template parameter declaration, e.g.
   12383 ///   friend class A<T>::B<unsigned>;
   12384 /// We permit this as a special case; if there are any template
   12385 /// parameters present at all, require proper matching, i.e.
   12386 ///   template <> template \<class T> friend class A<int>::B;
   12387 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
   12388                                 MultiTemplateParamsArg TempParams) {
   12389   SourceLocation Loc = DS.getLocStart();
   12390 
   12391   assert(DS.isFriendSpecified());
   12392   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
   12393 
   12394   // Try to convert the decl specifier to a type.  This works for
   12395   // friend templates because ActOnTag never produces a ClassTemplateDecl
   12396   // for a TUK_Friend.
   12397   Declarator TheDeclarator(DS, Declarator::MemberContext);
   12398   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
   12399   QualType T = TSI->getType();
   12400   if (TheDeclarator.isInvalidType())
   12401     return nullptr;
   12402 
   12403   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
   12404     return nullptr;
   12405 
   12406   // This is definitely an error in C++98.  It's probably meant to
   12407   // be forbidden in C++0x, too, but the specification is just
   12408   // poorly written.
   12409   //
   12410   // The problem is with declarations like the following:
   12411   //   template <T> friend A<T>::foo;
   12412   // where deciding whether a class C is a friend or not now hinges
   12413   // on whether there exists an instantiation of A that causes
   12414   // 'foo' to equal C.  There are restrictions on class-heads
   12415   // (which we declare (by fiat) elaborated friend declarations to
   12416   // be) that makes this tractable.
   12417   //
   12418   // FIXME: handle "template <> friend class A<T>;", which
   12419   // is possibly well-formed?  Who even knows?
   12420   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
   12421     Diag(Loc, diag::err_tagless_friend_type_template)
   12422       << DS.getSourceRange();
   12423     return nullptr;
   12424   }
   12425 
   12426   // C++98 [class.friend]p1: A friend of a class is a function
   12427   //   or class that is not a member of the class . . .
   12428   // This is fixed in DR77, which just barely didn't make the C++03
   12429   // deadline.  It's also a very silly restriction that seriously
   12430   // affects inner classes and which nobody else seems to implement;
   12431   // thus we never diagnose it, not even in -pedantic.
   12432   //
   12433   // But note that we could warn about it: it's always useless to
   12434   // friend one of your own members (it's not, however, worthless to
   12435   // friend a member of an arbitrary specialization of your template).
   12436 
   12437   Decl *D;
   12438   if (unsigned NumTempParamLists = TempParams.size())
   12439     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
   12440                                    NumTempParamLists,
   12441                                    TempParams.data(),
   12442                                    TSI,
   12443                                    DS.getFriendSpecLoc());
   12444   else
   12445     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
   12446 
   12447   if (!D)
   12448     return nullptr;
   12449 
   12450   D->setAccess(AS_public);
   12451   CurContext->addDecl(D);
   12452 
   12453   return D;
   12454 }
   12455 
   12456 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
   12457                                         MultiTemplateParamsArg TemplateParams) {
   12458   const DeclSpec &DS = D.getDeclSpec();
   12459 
   12460   assert(DS.isFriendSpecified());
   12461   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
   12462 
   12463   SourceLocation Loc = D.getIdentifierLoc();
   12464   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   12465 
   12466   // C++ [class.friend]p1
   12467   //   A friend of a class is a function or class....
   12468   // Note that this sees through typedefs, which is intended.
   12469   // It *doesn't* see through dependent types, which is correct
   12470   // according to [temp.arg.type]p3:
   12471   //   If a declaration acquires a function type through a
   12472   //   type dependent on a template-parameter and this causes
   12473   //   a declaration that does not use the syntactic form of a
   12474   //   function declarator to have a function type, the program
   12475   //   is ill-formed.
   12476   if (!TInfo->getType()->isFunctionType()) {
   12477     Diag(Loc, diag::err_unexpected_friend);
   12478 
   12479     // It might be worthwhile to try to recover by creating an
   12480     // appropriate declaration.
   12481     return nullptr;
   12482   }
   12483 
   12484   // C++ [namespace.memdef]p3
   12485   //  - If a friend declaration in a non-local class first declares a
   12486   //    class or function, the friend class or function is a member
   12487   //    of the innermost enclosing namespace.
   12488   //  - The name of the friend is not found by simple name lookup
   12489   //    until a matching declaration is provided in that namespace
   12490   //    scope (either before or after the class declaration granting
   12491   //    friendship).
   12492   //  - If a friend function is called, its name may be found by the
   12493   //    name lookup that considers functions from namespaces and
   12494   //    classes associated with the types of the function arguments.
   12495   //  - When looking for a prior declaration of a class or a function
   12496   //    declared as a friend, scopes outside the innermost enclosing
   12497   //    namespace scope are not considered.
   12498 
   12499   CXXScopeSpec &SS = D.getCXXScopeSpec();
   12500   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
   12501   DeclarationName Name = NameInfo.getName();
   12502   assert(Name);
   12503 
   12504   // Check for unexpanded parameter packs.
   12505   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
   12506       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
   12507       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
   12508     return nullptr;
   12509 
   12510   // The context we found the declaration in, or in which we should
   12511   // create the declaration.
   12512   DeclContext *DC;
   12513   Scope *DCScope = S;
   12514   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
   12515                         ForRedeclaration);
   12516 
   12517   // There are five cases here.
   12518   //   - There's no scope specifier and we're in a local class. Only look
   12519   //     for functions declared in the immediately-enclosing block scope.
   12520   // We recover from invalid scope qualifiers as if they just weren't there.
   12521   FunctionDecl *FunctionContainingLocalClass = nullptr;
   12522   if ((SS.isInvalid() || !SS.isSet()) &&
   12523       (FunctionContainingLocalClass =
   12524            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
   12525     // C++11 [class.friend]p11:
   12526     //   If a friend declaration appears in a local class and the name
   12527     //   specified is an unqualified name, a prior declaration is
   12528     //   looked up without considering scopes that are outside the
   12529     //   innermost enclosing non-class scope. For a friend function
   12530     //   declaration, if there is no prior declaration, the program is
   12531     //   ill-formed.
   12532 
   12533     // Find the innermost enclosing non-class scope. This is the block
   12534     // scope containing the local class definition (or for a nested class,
   12535     // the outer local class).
   12536     DCScope = S->getFnParent();
   12537 
   12538     // Look up the function name in the scope.
   12539     Previous.clear(LookupLocalFriendName);
   12540     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
   12541 
   12542     if (!Previous.empty()) {
   12543       // All possible previous declarations must have the same context:
   12544       // either they were declared at block scope or they are members of
   12545       // one of the enclosing local classes.
   12546       DC = Previous.getRepresentativeDecl()->getDeclContext();
   12547     } else {
   12548       // This is ill-formed, but provide the context that we would have
   12549       // declared the function in, if we were permitted to, for error recovery.
   12550       DC = FunctionContainingLocalClass;
   12551     }
   12552     adjustContextForLocalExternDecl(DC);
   12553 
   12554     // C++ [class.friend]p6:
   12555     //   A function can be defined in a friend declaration of a class if and
   12556     //   only if the class is a non-local class (9.8), the function name is
   12557     //   unqualified, and the function has namespace scope.
   12558     if (D.isFunctionDefinition()) {
   12559       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
   12560     }
   12561 
   12562   //   - There's no scope specifier, in which case we just go to the
   12563   //     appropriate scope and look for a function or function template
   12564   //     there as appropriate.
   12565   } else if (SS.isInvalid() || !SS.isSet()) {
   12566     // C++11 [namespace.memdef]p3:
   12567     //   If the name in a friend declaration is neither qualified nor
   12568     //   a template-id and the declaration is a function or an
   12569     //   elaborated-type-specifier, the lookup to determine whether
   12570     //   the entity has been previously declared shall not consider
   12571     //   any scopes outside the innermost enclosing namespace.
   12572     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
   12573 
   12574     // Find the appropriate context according to the above.
   12575     DC = CurContext;
   12576 
   12577     // Skip class contexts.  If someone can cite chapter and verse
   12578     // for this behavior, that would be nice --- it's what GCC and
   12579     // EDG do, and it seems like a reasonable intent, but the spec
   12580     // really only says that checks for unqualified existing
   12581     // declarations should stop at the nearest enclosing namespace,
   12582     // not that they should only consider the nearest enclosing
   12583     // namespace.
   12584     while (DC->isRecord())
   12585       DC = DC->getParent();
   12586 
   12587     DeclContext *LookupDC = DC;
   12588     while (LookupDC->isTransparentContext())
   12589       LookupDC = LookupDC->getParent();
   12590 
   12591     while (true) {
   12592       LookupQualifiedName(Previous, LookupDC);
   12593 
   12594       if (!Previous.empty()) {
   12595         DC = LookupDC;
   12596         break;
   12597       }
   12598 
   12599       if (isTemplateId) {
   12600         if (isa<TranslationUnitDecl>(LookupDC)) break;
   12601       } else {
   12602         if (LookupDC->isFileContext()) break;
   12603       }
   12604       LookupDC = LookupDC->getParent();
   12605     }
   12606 
   12607     DCScope = getScopeForDeclContext(S, DC);
   12608 
   12609   //   - There's a non-dependent scope specifier, in which case we
   12610   //     compute it and do a previous lookup there for a function
   12611   //     or function template.
   12612   } else if (!SS.getScopeRep()->isDependent()) {
   12613     DC = computeDeclContext(SS);
   12614     if (!DC) return nullptr;
   12615 
   12616     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
   12617 
   12618     LookupQualifiedName(Previous, DC);
   12619 
   12620     // Ignore things found implicitly in the wrong scope.
   12621     // TODO: better diagnostics for this case.  Suggesting the right
   12622     // qualified scope would be nice...
   12623     LookupResult::Filter F = Previous.makeFilter();
   12624     while (F.hasNext()) {
   12625       NamedDecl *D = F.next();
   12626       if (!DC->InEnclosingNamespaceSetOf(
   12627               D->getDeclContext()->getRedeclContext()))
   12628         F.erase();
   12629     }
   12630     F.done();
   12631 
   12632     if (Previous.empty()) {
   12633       D.setInvalidType();
   12634       Diag(Loc, diag::err_qualified_friend_not_found)
   12635           << Name << TInfo->getType();
   12636       return nullptr;
   12637     }
   12638 
   12639     // C++ [class.friend]p1: A friend of a class is a function or
   12640     //   class that is not a member of the class . . .
   12641     if (DC->Equals(CurContext))
   12642       Diag(DS.getFriendSpecLoc(),
   12643            getLangOpts().CPlusPlus11 ?
   12644              diag::warn_cxx98_compat_friend_is_member :
   12645              diag::err_friend_is_member);
   12646 
   12647     if (D.isFunctionDefinition()) {
   12648       // C++ [class.friend]p6:
   12649       //   A function can be defined in a friend declaration of a class if and
   12650       //   only if the class is a non-local class (9.8), the function name is
   12651       //   unqualified, and the function has namespace scope.
   12652       SemaDiagnosticBuilder DB
   12653         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
   12654 
   12655       DB << SS.getScopeRep();
   12656       if (DC->isFileContext())
   12657         DB << FixItHint::CreateRemoval(SS.getRange());
   12658       SS.clear();
   12659     }
   12660 
   12661   //   - There's a scope specifier that does not match any template
   12662   //     parameter lists, in which case we use some arbitrary context,
   12663   //     create a method or method template, and wait for instantiation.
   12664   //   - There's a scope specifier that does match some template
   12665   //     parameter lists, which we don't handle right now.
   12666   } else {
   12667     if (D.isFunctionDefinition()) {
   12668       // C++ [class.friend]p6:
   12669       //   A function can be defined in a friend declaration of a class if and
   12670       //   only if the class is a non-local class (9.8), the function name is
   12671       //   unqualified, and the function has namespace scope.
   12672       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
   12673         << SS.getScopeRep();
   12674     }
   12675 
   12676     DC = CurContext;
   12677     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
   12678   }
   12679 
   12680   if (!DC->isRecord()) {
   12681     int DiagArg = -1;
   12682     switch (D.getName().getKind()) {
   12683     case UnqualifiedId::IK_ConstructorTemplateId:
   12684     case UnqualifiedId::IK_ConstructorName:
   12685       DiagArg = 0;
   12686       break;
   12687     case UnqualifiedId::IK_DestructorName:
   12688       DiagArg = 1;
   12689       break;
   12690     case UnqualifiedId::IK_ConversionFunctionId:
   12691       DiagArg = 2;
   12692       break;
   12693     case UnqualifiedId::IK_Identifier:
   12694     case UnqualifiedId::IK_ImplicitSelfParam:
   12695     case UnqualifiedId::IK_LiteralOperatorId:
   12696     case UnqualifiedId::IK_OperatorFunctionId:
   12697     case UnqualifiedId::IK_TemplateId:
   12698       break;
   12699     }
   12700     // This implies that it has to be an operator or function.
   12701     if (DiagArg >= 0) {
   12702       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
   12703       return nullptr;
   12704     }
   12705   }
   12706 
   12707   // FIXME: This is an egregious hack to cope with cases where the scope stack
   12708   // does not contain the declaration context, i.e., in an out-of-line
   12709   // definition of a class.
   12710   Scope FakeDCScope(S, Scope::DeclScope, Diags);
   12711   if (!DCScope) {
   12712     FakeDCScope.setEntity(DC);
   12713     DCScope = &FakeDCScope;
   12714   }
   12715 
   12716   bool AddToScope = true;
   12717   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
   12718                                           TemplateParams, AddToScope);
   12719   if (!ND) return nullptr;
   12720 
   12721   assert(ND->getLexicalDeclContext() == CurContext);
   12722 
   12723   // If we performed typo correction, we might have added a scope specifier
   12724   // and changed the decl context.
   12725   DC = ND->getDeclContext();
   12726 
   12727   // Add the function declaration to the appropriate lookup tables,
   12728   // adjusting the redeclarations list as necessary.  We don't
   12729   // want to do this yet if the friending class is dependent.
   12730   //
   12731   // Also update the scope-based lookup if the target context's
   12732   // lookup context is in lexical scope.
   12733   if (!CurContext->isDependentContext()) {
   12734     DC = DC->getRedeclContext();
   12735     DC->makeDeclVisibleInContext(ND);
   12736     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
   12737       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
   12738   }
   12739 
   12740   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
   12741                                        D.getIdentifierLoc(), ND,
   12742                                        DS.getFriendSpecLoc());
   12743   FrD->setAccess(AS_public);
   12744   CurContext->addDecl(FrD);
   12745 
   12746   if (ND->isInvalidDecl()) {
   12747     FrD->setInvalidDecl();
   12748   } else {
   12749     if (DC->isRecord()) CheckFriendAccess(ND);
   12750 
   12751     FunctionDecl *FD;
   12752     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
   12753       FD = FTD->getTemplatedDecl();
   12754     else
   12755       FD = cast<FunctionDecl>(ND);
   12756 
   12757     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
   12758     // default argument expression, that declaration shall be a definition
   12759     // and shall be the only declaration of the function or function
   12760     // template in the translation unit.
   12761     if (functionDeclHasDefaultArgument(FD)) {
   12762       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
   12763         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
   12764         Diag(OldFD->getLocation(), diag::note_previous_declaration);
   12765       } else if (!D.isFunctionDefinition())
   12766         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
   12767     }
   12768 
   12769     // Mark templated-scope function declarations as unsupported.
   12770     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
   12771       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
   12772         << SS.getScopeRep() << SS.getRange()
   12773         << cast<CXXRecordDecl>(CurContext);
   12774       FrD->setUnsupportedFriend(true);
   12775     }
   12776   }
   12777 
   12778   return ND;
   12779 }
   12780 
   12781 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
   12782   AdjustDeclIfTemplate(Dcl);
   12783 
   12784   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
   12785   if (!Fn) {
   12786     Diag(DelLoc, diag::err_deleted_non_function);
   12787     return;
   12788   }
   12789 
   12790   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
   12791     // Don't consider the implicit declaration we generate for explicit
   12792     // specializations. FIXME: Do not generate these implicit declarations.
   12793     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
   12794          Prev->getPreviousDecl()) &&
   12795         !Prev->isDefined()) {
   12796       Diag(DelLoc, diag::err_deleted_decl_not_first);
   12797       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
   12798            Prev->isImplicit() ? diag::note_previous_implicit_declaration
   12799                               : diag::note_previous_declaration);
   12800     }
   12801     // If the declaration wasn't the first, we delete the function anyway for
   12802     // recovery.
   12803     Fn = Fn->getCanonicalDecl();
   12804   }
   12805 
   12806   // dllimport/dllexport cannot be deleted.
   12807   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
   12808     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
   12809     Fn->setInvalidDecl();
   12810   }
   12811 
   12812   if (Fn->isDeleted())
   12813     return;
   12814 
   12815   // See if we're deleting a function which is already known to override a
   12816   // non-deleted virtual function.
   12817   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
   12818     bool IssuedDiagnostic = false;
   12819     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
   12820                                         E = MD->end_overridden_methods();
   12821          I != E; ++I) {
   12822       if (!(*MD->begin_overridden_methods())->isDeleted()) {
   12823         if (!IssuedDiagnostic) {
   12824           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
   12825           IssuedDiagnostic = true;
   12826         }
   12827         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
   12828       }
   12829     }
   12830   }
   12831 
   12832   // C++11 [basic.start.main]p3:
   12833   //   A program that defines main as deleted [...] is ill-formed.
   12834   if (Fn->isMain())
   12835     Diag(DelLoc, diag::err_deleted_main);
   12836 
   12837   Fn->setDeletedAsWritten();
   12838 }
   12839 
   12840 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
   12841   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
   12842 
   12843   if (MD) {
   12844     if (MD->getParent()->isDependentType()) {
   12845       MD->setDefaulted();
   12846       MD->setExplicitlyDefaulted();
   12847       return;
   12848     }
   12849 
   12850     CXXSpecialMember Member = getSpecialMember(MD);
   12851     if (Member == CXXInvalid) {
   12852       if (!MD->isInvalidDecl())
   12853         Diag(DefaultLoc, diag::err_default_special_members);
   12854       return;
   12855     }
   12856 
   12857     MD->setDefaulted();
   12858     MD->setExplicitlyDefaulted();
   12859 
   12860     // If this definition appears within the record, do the checking when
   12861     // the record is complete.
   12862     const FunctionDecl *Primary = MD;
   12863     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
   12864       // Find the uninstantiated declaration that actually had the '= default'
   12865       // on it.
   12866       Pattern->isDefined(Primary);
   12867 
   12868     // If the method was defaulted on its first declaration, we will have
   12869     // already performed the checking in CheckCompletedCXXClass. Such a
   12870     // declaration doesn't trigger an implicit definition.
   12871     if (Primary == Primary->getCanonicalDecl())
   12872       return;
   12873 
   12874     CheckExplicitlyDefaultedSpecialMember(MD);
   12875 
   12876     if (MD->isInvalidDecl())
   12877       return;
   12878 
   12879     switch (Member) {
   12880     case CXXDefaultConstructor:
   12881       DefineImplicitDefaultConstructor(DefaultLoc,
   12882                                        cast<CXXConstructorDecl>(MD));
   12883       break;
   12884     case CXXCopyConstructor:
   12885       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
   12886       break;
   12887     case CXXCopyAssignment:
   12888       DefineImplicitCopyAssignment(DefaultLoc, MD);
   12889       break;
   12890     case CXXDestructor:
   12891       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
   12892       break;
   12893     case CXXMoveConstructor:
   12894       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
   12895       break;
   12896     case CXXMoveAssignment:
   12897       DefineImplicitMoveAssignment(DefaultLoc, MD);
   12898       break;
   12899     case CXXInvalid:
   12900       llvm_unreachable("Invalid special member.");
   12901     }
   12902   } else {
   12903     Diag(DefaultLoc, diag::err_default_special_members);
   12904   }
   12905 }
   12906 
   12907 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
   12908   for (Stmt *SubStmt : S->children()) {
   12909     if (!SubStmt)
   12910       continue;
   12911     if (isa<ReturnStmt>(SubStmt))
   12912       Self.Diag(SubStmt->getLocStart(),
   12913            diag::err_return_in_constructor_handler);
   12914     if (!isa<Expr>(SubStmt))
   12915       SearchForReturnInStmt(Self, SubStmt);
   12916   }
   12917 }
   12918 
   12919 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
   12920   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
   12921     CXXCatchStmt *Handler = TryBlock->getHandler(I);
   12922     SearchForReturnInStmt(*this, Handler);
   12923   }
   12924 }
   12925 
   12926 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
   12927                                              const CXXMethodDecl *Old) {
   12928   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
   12929   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
   12930 
   12931   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
   12932 
   12933   // If the calling conventions match, everything is fine
   12934   if (NewCC == OldCC)
   12935     return false;
   12936 
   12937   // If the calling conventions mismatch because the new function is static,
   12938   // suppress the calling convention mismatch error; the error about static
   12939   // function override (err_static_overrides_virtual from
   12940   // Sema::CheckFunctionDeclaration) is more clear.
   12941   if (New->getStorageClass() == SC_Static)
   12942     return false;
   12943 
   12944   Diag(New->getLocation(),
   12945        diag::err_conflicting_overriding_cc_attributes)
   12946     << New->getDeclName() << New->getType() << Old->getType();
   12947   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
   12948   return true;
   12949 }
   12950 
   12951 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
   12952                                              const CXXMethodDecl *Old) {
   12953   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
   12954   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
   12955 
   12956   if (Context.hasSameType(NewTy, OldTy) ||
   12957       NewTy->isDependentType() || OldTy->isDependentType())
   12958     return false;
   12959 
   12960   // Check if the return types are covariant
   12961   QualType NewClassTy, OldClassTy;
   12962 
   12963   /// Both types must be pointers or references to classes.
   12964   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
   12965     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
   12966       NewClassTy = NewPT->getPointeeType();
   12967       OldClassTy = OldPT->getPointeeType();
   12968     }
   12969   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
   12970     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
   12971       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
   12972         NewClassTy = NewRT->getPointeeType();
   12973         OldClassTy = OldRT->getPointeeType();
   12974       }
   12975     }
   12976   }
   12977 
   12978   // The return types aren't either both pointers or references to a class type.
   12979   if (NewClassTy.isNull()) {
   12980     Diag(New->getLocation(),
   12981          diag::err_different_return_type_for_overriding_virtual_function)
   12982         << New->getDeclName() << NewTy << OldTy
   12983         << New->getReturnTypeSourceRange();
   12984     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   12985         << Old->getReturnTypeSourceRange();
   12986 
   12987     return true;
   12988   }
   12989 
   12990   // C++ [class.virtual]p6:
   12991   //   If the return type of D::f differs from the return type of B::f, the
   12992   //   class type in the return type of D::f shall be complete at the point of
   12993   //   declaration of D::f or shall be the class type D.
   12994   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
   12995     if (!RT->isBeingDefined() &&
   12996         RequireCompleteType(New->getLocation(), NewClassTy,
   12997                             diag::err_covariant_return_incomplete,
   12998                             New->getDeclName()))
   12999     return true;
   13000   }
   13001 
   13002   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
   13003     // Check if the new class derives from the old class.
   13004     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
   13005       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
   13006           << New->getDeclName() << NewTy << OldTy
   13007           << New->getReturnTypeSourceRange();
   13008       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   13009           << Old->getReturnTypeSourceRange();
   13010       return true;
   13011     }
   13012 
   13013     // Check if we the conversion from derived to base is valid.
   13014     if (CheckDerivedToBaseConversion(
   13015             NewClassTy, OldClassTy,
   13016             diag::err_covariant_return_inaccessible_base,
   13017             diag::err_covariant_return_ambiguous_derived_to_base_conv,
   13018             New->getLocation(), New->getReturnTypeSourceRange(),
   13019             New->getDeclName(), nullptr)) {
   13020       // FIXME: this note won't trigger for delayed access control
   13021       // diagnostics, and it's impossible to get an undelayed error
   13022       // here from access control during the original parse because
   13023       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
   13024       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   13025           << Old->getReturnTypeSourceRange();
   13026       return true;
   13027     }
   13028   }
   13029 
   13030   // The qualifiers of the return types must be the same.
   13031   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
   13032     Diag(New->getLocation(),
   13033          diag::err_covariant_return_type_different_qualifications)
   13034         << New->getDeclName() << NewTy << OldTy
   13035         << New->getReturnTypeSourceRange();
   13036     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   13037         << Old->getReturnTypeSourceRange();
   13038     return true;
   13039   };
   13040 
   13041 
   13042   // The new class type must have the same or less qualifiers as the old type.
   13043   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
   13044     Diag(New->getLocation(),
   13045          diag::err_covariant_return_type_class_type_more_qualified)
   13046         << New->getDeclName() << NewTy << OldTy
   13047         << New->getReturnTypeSourceRange();
   13048     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
   13049         << Old->getReturnTypeSourceRange();
   13050     return true;
   13051   };
   13052 
   13053   return false;
   13054 }
   13055 
   13056 /// \brief Mark the given method pure.
   13057 ///
   13058 /// \param Method the method to be marked pure.
   13059 ///
   13060 /// \param InitRange the source range that covers the "0" initializer.
   13061 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
   13062   SourceLocation EndLoc = InitRange.getEnd();
   13063   if (EndLoc.isValid())
   13064     Method->setRangeEnd(EndLoc);
   13065 
   13066   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
   13067     Method->setPure();
   13068     return false;
   13069   }
   13070 
   13071   if (!Method->isInvalidDecl())
   13072     Diag(Method->getLocation(), diag::err_non_virtual_pure)
   13073       << Method->getDeclName() << InitRange;
   13074   return true;
   13075 }
   13076 
   13077 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
   13078   if (D->getFriendObjectKind())
   13079     Diag(D->getLocation(), diag::err_pure_friend);
   13080   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
   13081     CheckPureMethod(M, ZeroLoc);
   13082   else
   13083     Diag(D->getLocation(), diag::err_illegal_initializer);
   13084 }
   13085 
   13086 /// \brief Determine whether the given declaration is a static data member.
   13087 static bool isStaticDataMember(const Decl *D) {
   13088   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
   13089     return Var->isStaticDataMember();
   13090 
   13091   return false;
   13092 }
   13093 
   13094 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
   13095 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
   13096 /// is a fresh scope pushed for just this purpose.
   13097 ///
   13098 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
   13099 /// static data member of class X, names should be looked up in the scope of
   13100 /// class X.
   13101 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
   13102   // If there is no declaration, there was an error parsing it.
   13103   if (!D || D->isInvalidDecl())
   13104     return;
   13105 
   13106   // We will always have a nested name specifier here, but this declaration
   13107   // might not be out of line if the specifier names the current namespace:
   13108   //   extern int n;
   13109   //   int ::n = 0;
   13110   if (D->isOutOfLine())
   13111     EnterDeclaratorContext(S, D->getDeclContext());
   13112 
   13113   // If we are parsing the initializer for a static data member, push a
   13114   // new expression evaluation context that is associated with this static
   13115   // data member.
   13116   if (isStaticDataMember(D))
   13117     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
   13118 }
   13119 
   13120 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
   13121 /// initializer for the out-of-line declaration 'D'.
   13122 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
   13123   // If there is no declaration, there was an error parsing it.
   13124   if (!D || D->isInvalidDecl())
   13125     return;
   13126 
   13127   if (isStaticDataMember(D))
   13128     PopExpressionEvaluationContext();
   13129 
   13130   if (D->isOutOfLine())
   13131     ExitDeclaratorContext(S);
   13132 }
   13133 
   13134 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
   13135 /// C++ if/switch/while/for statement.
   13136 /// e.g: "if (int x = f()) {...}"
   13137 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
   13138   // C++ 6.4p2:
   13139   // The declarator shall not specify a function or an array.
   13140   // The type-specifier-seq shall not contain typedef and shall not declare a
   13141   // new class or enumeration.
   13142   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
   13143          "Parser allowed 'typedef' as storage class of condition decl.");
   13144 
   13145   Decl *Dcl = ActOnDeclarator(S, D);
   13146   if (!Dcl)
   13147     return true;
   13148 
   13149   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
   13150     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
   13151       << D.getSourceRange();
   13152     return true;
   13153   }
   13154 
   13155   return Dcl;
   13156 }
   13157 
   13158 void Sema::LoadExternalVTableUses() {
   13159   if (!ExternalSource)
   13160     return;
   13161 
   13162   SmallVector<ExternalVTableUse, 4> VTables;
   13163   ExternalSource->ReadUsedVTables(VTables);
   13164   SmallVector<VTableUse, 4> NewUses;
   13165   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
   13166     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
   13167       = VTablesUsed.find(VTables[I].Record);
   13168     // Even if a definition wasn't required before, it may be required now.
   13169     if (Pos != VTablesUsed.end()) {
   13170       if (!Pos->second && VTables[I].DefinitionRequired)
   13171         Pos->second = true;
   13172       continue;
   13173     }
   13174 
   13175     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
   13176     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
   13177   }
   13178 
   13179   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
   13180 }
   13181 
   13182 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
   13183                           bool DefinitionRequired) {
   13184   // Ignore any vtable uses in unevaluated operands or for classes that do
   13185   // not have a vtable.
   13186   if (!Class->isDynamicClass() || Class->isDependentContext() ||
   13187       CurContext->isDependentContext() || isUnevaluatedContext())
   13188     return;
   13189 
   13190   // Try to insert this class into the map.
   13191   LoadExternalVTableUses();
   13192   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
   13193   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
   13194     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
   13195   if (!Pos.second) {
   13196     // If we already had an entry, check to see if we are promoting this vtable
   13197     // to require a definition. If so, we need to reappend to the VTableUses
   13198     // list, since we may have already processed the first entry.
   13199     if (DefinitionRequired && !Pos.first->second) {
   13200       Pos.first->second = true;
   13201     } else {
   13202       // Otherwise, we can early exit.
   13203       return;
   13204     }
   13205   } else {
   13206     // The Microsoft ABI requires that we perform the destructor body
   13207     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
   13208     // the deleting destructor is emitted with the vtable, not with the
   13209     // destructor definition as in the Itanium ABI.
   13210     // If it has a definition, we do the check at that point instead.
   13211     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
   13212         Class->hasUserDeclaredDestructor() &&
   13213         !Class->getDestructor()->isDefined() &&
   13214         !Class->getDestructor()->isDeleted()) {
   13215       CXXDestructorDecl *DD = Class->getDestructor();
   13216       ContextRAII SavedContext(*this, DD);
   13217       CheckDestructor(DD);
   13218     }
   13219   }
   13220 
   13221   // Local classes need to have their virtual members marked
   13222   // immediately. For all other classes, we mark their virtual members
   13223   // at the end of the translation unit.
   13224   if (Class->isLocalClass())
   13225     MarkVirtualMembersReferenced(Loc, Class);
   13226   else
   13227     VTableUses.push_back(std::make_pair(Class, Loc));
   13228 }
   13229 
   13230 bool Sema::DefineUsedVTables() {
   13231   LoadExternalVTableUses();
   13232   if (VTableUses.empty())
   13233     return false;
   13234 
   13235   // Note: The VTableUses vector could grow as a result of marking
   13236   // the members of a class as "used", so we check the size each
   13237   // time through the loop and prefer indices (which are stable) to
   13238   // iterators (which are not).
   13239   bool DefinedAnything = false;
   13240   for (unsigned I = 0; I != VTableUses.size(); ++I) {
   13241     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
   13242     if (!Class)
   13243       continue;
   13244 
   13245     SourceLocation Loc = VTableUses[I].second;
   13246 
   13247     bool DefineVTable = true;
   13248 
   13249     // If this class has a key function, but that key function is
   13250     // defined in another translation unit, we don't need to emit the
   13251     // vtable even though we're using it.
   13252     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
   13253     if (KeyFunction && !KeyFunction->hasBody()) {
   13254       // The key function is in another translation unit.
   13255       DefineVTable = false;
   13256       TemplateSpecializationKind TSK =
   13257           KeyFunction->getTemplateSpecializationKind();
   13258       assert(TSK != TSK_ExplicitInstantiationDefinition &&
   13259              TSK != TSK_ImplicitInstantiation &&
   13260              "Instantiations don't have key functions");
   13261       (void)TSK;
   13262     } else if (!KeyFunction) {
   13263       // If we have a class with no key function that is the subject
   13264       // of an explicit instantiation declaration, suppress the
   13265       // vtable; it will live with the explicit instantiation
   13266       // definition.
   13267       bool IsExplicitInstantiationDeclaration
   13268         = Class->getTemplateSpecializationKind()
   13269                                       == TSK_ExplicitInstantiationDeclaration;
   13270       for (auto R : Class->redecls()) {
   13271         TemplateSpecializationKind TSK
   13272           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
   13273         if (TSK == TSK_ExplicitInstantiationDeclaration)
   13274           IsExplicitInstantiationDeclaration = true;
   13275         else if (TSK == TSK_ExplicitInstantiationDefinition) {
   13276           IsExplicitInstantiationDeclaration = false;
   13277           break;
   13278         }
   13279       }
   13280 
   13281       if (IsExplicitInstantiationDeclaration)
   13282         DefineVTable = false;
   13283     }
   13284 
   13285     // The exception specifications for all virtual members may be needed even
   13286     // if we are not providing an authoritative form of the vtable in this TU.
   13287     // We may choose to emit it available_externally anyway.
   13288     if (!DefineVTable) {
   13289       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
   13290       continue;
   13291     }
   13292 
   13293     // Mark all of the virtual members of this class as referenced, so
   13294     // that we can build a vtable. Then, tell the AST consumer that a
   13295     // vtable for this class is required.
   13296     DefinedAnything = true;
   13297     MarkVirtualMembersReferenced(Loc, Class);
   13298     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
   13299     if (VTablesUsed[Canonical])
   13300       Consumer.HandleVTable(Class);
   13301 
   13302     // Optionally warn if we're emitting a weak vtable.
   13303     if (Class->isExternallyVisible() &&
   13304         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
   13305       const FunctionDecl *KeyFunctionDef = nullptr;
   13306       if (!KeyFunction ||
   13307           (KeyFunction->hasBody(KeyFunctionDef) &&
   13308            KeyFunctionDef->isInlined()))
   13309         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
   13310              TSK_ExplicitInstantiationDefinition
   13311              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
   13312           << Class;
   13313     }
   13314   }
   13315   VTableUses.clear();
   13316 
   13317   return DefinedAnything;
   13318 }
   13319 
   13320 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
   13321                                                  const CXXRecordDecl *RD) {
   13322   for (const auto *I : RD->methods())
   13323     if (I->isVirtual() && !I->isPure())
   13324       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
   13325 }
   13326 
   13327 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
   13328                                         const CXXRecordDecl *RD) {
   13329   // Mark all functions which will appear in RD's vtable as used.
   13330   CXXFinalOverriderMap FinalOverriders;
   13331   RD->getFinalOverriders(FinalOverriders);
   13332   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
   13333                                             E = FinalOverriders.end();
   13334        I != E; ++I) {
   13335     for (OverridingMethods::const_iterator OI = I->second.begin(),
   13336                                            OE = I->second.end();
   13337          OI != OE; ++OI) {
   13338       assert(OI->second.size() > 0 && "no final overrider");
   13339       CXXMethodDecl *Overrider = OI->second.front().Method;
   13340 
   13341       // C++ [basic.def.odr]p2:
   13342       //   [...] A virtual member function is used if it is not pure. [...]
   13343       if (!Overrider->isPure())
   13344         MarkFunctionReferenced(Loc, Overrider);
   13345     }
   13346   }
   13347 
   13348   // Only classes that have virtual bases need a VTT.
   13349   if (RD->getNumVBases() == 0)
   13350     return;
   13351 
   13352   for (const auto &I : RD->bases()) {
   13353     const CXXRecordDecl *Base =
   13354         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
   13355     if (Base->getNumVBases() == 0)
   13356       continue;
   13357     MarkVirtualMembersReferenced(Loc, Base);
   13358   }
   13359 }
   13360 
   13361 /// SetIvarInitializers - This routine builds initialization ASTs for the
   13362 /// Objective-C implementation whose ivars need be initialized.
   13363 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
   13364   if (!getLangOpts().CPlusPlus)
   13365     return;
   13366   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
   13367     SmallVector<ObjCIvarDecl*, 8> ivars;
   13368     CollectIvarsToConstructOrDestruct(OID, ivars);
   13369     if (ivars.empty())
   13370       return;
   13371     SmallVector<CXXCtorInitializer*, 32> AllToInit;
   13372     for (unsigned i = 0; i < ivars.size(); i++) {
   13373       FieldDecl *Field = ivars[i];
   13374       if (Field->isInvalidDecl())
   13375         continue;
   13376 
   13377       CXXCtorInitializer *Member;
   13378       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
   13379       InitializationKind InitKind =
   13380         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
   13381 
   13382       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
   13383       ExprResult MemberInit =
   13384         InitSeq.Perform(*this, InitEntity, InitKind, None);
   13385       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
   13386       // Note, MemberInit could actually come back empty if no initialization
   13387       // is required (e.g., because it would call a trivial default constructor)
   13388       if (!MemberInit.get() || MemberInit.isInvalid())
   13389         continue;
   13390 
   13391       Member =
   13392         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
   13393                                          SourceLocation(),
   13394                                          MemberInit.getAs<Expr>(),
   13395                                          SourceLocation());
   13396       AllToInit.push_back(Member);
   13397 
   13398       // Be sure that the destructor is accessible and is marked as referenced.
   13399       if (const RecordType *RecordTy =
   13400               Context.getBaseElementType(Field->getType())
   13401                   ->getAs<RecordType>()) {
   13402         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
   13403         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
   13404           MarkFunctionReferenced(Field->getLocation(), Destructor);
   13405           CheckDestructorAccess(Field->getLocation(), Destructor,
   13406                             PDiag(diag::err_access_dtor_ivar)
   13407                               << Context.getBaseElementType(Field->getType()));
   13408         }
   13409       }
   13410     }
   13411     ObjCImplementation->setIvarInitializers(Context,
   13412                                             AllToInit.data(), AllToInit.size());
   13413   }
   13414 }
   13415 
   13416 static
   13417 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
   13418                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
   13419                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
   13420                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
   13421                            Sema &S) {
   13422   if (Ctor->isInvalidDecl())
   13423     return;
   13424 
   13425   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
   13426 
   13427   // Target may not be determinable yet, for instance if this is a dependent
   13428   // call in an uninstantiated template.
   13429   if (Target) {
   13430     const FunctionDecl *FNTarget = nullptr;
   13431     (void)Target->hasBody(FNTarget);
   13432     Target = const_cast<CXXConstructorDecl*>(
   13433       cast_or_null<CXXConstructorDecl>(FNTarget));
   13434   }
   13435 
   13436   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
   13437                      // Avoid dereferencing a null pointer here.
   13438                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
   13439 
   13440   if (!Current.insert(Canonical).second)
   13441     return;
   13442 
   13443   // We know that beyond here, we aren't chaining into a cycle.
   13444   if (!Target || !Target->isDelegatingConstructor() ||
   13445       Target->isInvalidDecl() || Valid.count(TCanonical)) {
   13446     Valid.insert(Current.begin(), Current.end());
   13447     Current.clear();
   13448   // We've hit a cycle.
   13449   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
   13450              Current.count(TCanonical)) {
   13451     // If we haven't diagnosed this cycle yet, do so now.
   13452     if (!Invalid.count(TCanonical)) {
   13453       S.Diag((*Ctor->init_begin())->getSourceLocation(),
   13454              diag::warn_delegating_ctor_cycle)
   13455         << Ctor;
   13456 
   13457       // Don't add a note for a function delegating directly to itself.
   13458       if (TCanonical != Canonical)
   13459         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
   13460 
   13461       CXXConstructorDecl *C = Target;
   13462       while (C->getCanonicalDecl() != Canonical) {
   13463         const FunctionDecl *FNTarget = nullptr;
   13464         (void)C->getTargetConstructor()->hasBody(FNTarget);
   13465         assert(FNTarget && "Ctor cycle through bodiless function");
   13466 
   13467         C = const_cast<CXXConstructorDecl*>(
   13468           cast<CXXConstructorDecl>(FNTarget));
   13469         S.Diag(C->getLocation(), diag::note_which_delegates_to);
   13470       }
   13471     }
   13472 
   13473     Invalid.insert(Current.begin(), Current.end());
   13474     Current.clear();
   13475   } else {
   13476     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
   13477   }
   13478 }
   13479 
   13480 
   13481 void Sema::CheckDelegatingCtorCycles() {
   13482   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
   13483 
   13484   for (DelegatingCtorDeclsType::iterator
   13485          I = DelegatingCtorDecls.begin(ExternalSource),
   13486          E = DelegatingCtorDecls.end();
   13487        I != E; ++I)
   13488     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
   13489 
   13490   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
   13491                                                          CE = Invalid.end();
   13492        CI != CE; ++CI)
   13493     (*CI)->setInvalidDecl();
   13494 }
   13495 
   13496 namespace {
   13497   /// \brief AST visitor that finds references to the 'this' expression.
   13498   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
   13499     Sema &S;
   13500 
   13501   public:
   13502     explicit FindCXXThisExpr(Sema &S) : S(S) { }
   13503 
   13504     bool VisitCXXThisExpr(CXXThisExpr *E) {
   13505       S.Diag(E->getLocation(), diag::err_this_static_member_func)
   13506         << E->isImplicit();
   13507       return false;
   13508     }
   13509   };
   13510 }
   13511 
   13512 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
   13513   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
   13514   if (!TSInfo)
   13515     return false;
   13516 
   13517   TypeLoc TL = TSInfo->getTypeLoc();
   13518   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
   13519   if (!ProtoTL)
   13520     return false;
   13521 
   13522   // C++11 [expr.prim.general]p3:
   13523   //   [The expression this] shall not appear before the optional
   13524   //   cv-qualifier-seq and it shall not appear within the declaration of a
   13525   //   static member function (although its type and value category are defined
   13526   //   within a static member function as they are within a non-static member
   13527   //   function). [ Note: this is because declaration matching does not occur
   13528   //  until the complete declarator is known. - end note ]
   13529   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
   13530   FindCXXThisExpr Finder(*this);
   13531 
   13532   // If the return type came after the cv-qualifier-seq, check it now.
   13533   if (Proto->hasTrailingReturn() &&
   13534       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
   13535     return true;
   13536 
   13537   // Check the exception specification.
   13538   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
   13539     return true;
   13540 
   13541   return checkThisInStaticMemberFunctionAttributes(Method);
   13542 }
   13543 
   13544 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
   13545   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
   13546   if (!TSInfo)
   13547     return false;
   13548 
   13549   TypeLoc TL = TSInfo->getTypeLoc();
   13550   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
   13551   if (!ProtoTL)
   13552     return false;
   13553 
   13554   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
   13555   FindCXXThisExpr Finder(*this);
   13556 
   13557   switch (Proto->getExceptionSpecType()) {
   13558   case EST_Unparsed:
   13559   case EST_Uninstantiated:
   13560   case EST_Unevaluated:
   13561   case EST_BasicNoexcept:
   13562   case EST_DynamicNone:
   13563   case EST_MSAny:
   13564   case EST_None:
   13565     break;
   13566 
   13567   case EST_ComputedNoexcept:
   13568     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
   13569       return true;
   13570 
   13571   case EST_Dynamic:
   13572     for (const auto &E : Proto->exceptions()) {
   13573       if (!Finder.TraverseType(E))
   13574         return true;
   13575     }
   13576     break;
   13577   }
   13578 
   13579   return false;
   13580 }
   13581 
   13582 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
   13583   FindCXXThisExpr Finder(*this);
   13584 
   13585   // Check attributes.
   13586   for (const auto *A : Method->attrs()) {
   13587     // FIXME: This should be emitted by tblgen.
   13588     Expr *Arg = nullptr;
   13589     ArrayRef<Expr *> Args;
   13590     if (const auto *G = dyn_cast<GuardedByAttr>(A))
   13591       Arg = G->getArg();
   13592     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
   13593       Arg = G->getArg();
   13594     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
   13595       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
   13596     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
   13597       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
   13598     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
   13599       Arg = ETLF->getSuccessValue();
   13600       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
   13601     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
   13602       Arg = STLF->getSuccessValue();
   13603       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
   13604     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
   13605       Arg = LR->getArg();
   13606     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
   13607       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
   13608     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
   13609       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
   13610     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
   13611       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
   13612     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
   13613       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
   13614     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
   13615       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
   13616 
   13617     if (Arg && !Finder.TraverseStmt(Arg))
   13618       return true;
   13619 
   13620     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
   13621       if (!Finder.TraverseStmt(Args[I]))
   13622         return true;
   13623     }
   13624   }
   13625 
   13626   return false;
   13627 }
   13628 
   13629 void Sema::checkExceptionSpecification(
   13630     bool IsTopLevel, ExceptionSpecificationType EST,
   13631     ArrayRef<ParsedType> DynamicExceptions,
   13632     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
   13633     SmallVectorImpl<QualType> &Exceptions,
   13634     FunctionProtoType::ExceptionSpecInfo &ESI) {
   13635   Exceptions.clear();
   13636   ESI.Type = EST;
   13637   if (EST == EST_Dynamic) {
   13638     Exceptions.reserve(DynamicExceptions.size());
   13639     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
   13640       // FIXME: Preserve type source info.
   13641       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
   13642 
   13643       if (IsTopLevel) {
   13644         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   13645         collectUnexpandedParameterPacks(ET, Unexpanded);
   13646         if (!Unexpanded.empty()) {
   13647           DiagnoseUnexpandedParameterPacks(
   13648               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
   13649               Unexpanded);
   13650           continue;
   13651         }
   13652       }
   13653 
   13654       // Check that the type is valid for an exception spec, and
   13655       // drop it if not.
   13656       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
   13657         Exceptions.push_back(ET);
   13658     }
   13659     ESI.Exceptions = Exceptions;
   13660     return;
   13661   }
   13662 
   13663   if (EST == EST_ComputedNoexcept) {
   13664     // If an error occurred, there's no expression here.
   13665     if (NoexceptExpr) {
   13666       assert((NoexceptExpr->isTypeDependent() ||
   13667               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
   13668               Context.BoolTy) &&
   13669              "Parser should have made sure that the expression is boolean");
   13670       if (IsTopLevel && NoexceptExpr &&
   13671           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
   13672         ESI.Type = EST_BasicNoexcept;
   13673         return;
   13674       }
   13675 
   13676       if (!NoexceptExpr->isValueDependent())
   13677         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
   13678                          diag::err_noexcept_needs_constant_expression,
   13679                          /*AllowFold*/ false).get();
   13680       ESI.NoexceptExpr = NoexceptExpr;
   13681     }
   13682     return;
   13683   }
   13684 }
   13685 
   13686 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
   13687              ExceptionSpecificationType EST,
   13688              SourceRange SpecificationRange,
   13689              ArrayRef<ParsedType> DynamicExceptions,
   13690              ArrayRef<SourceRange> DynamicExceptionRanges,
   13691              Expr *NoexceptExpr) {
   13692   if (!MethodD)
   13693     return;
   13694 
   13695   // Dig out the method we're referring to.
   13696   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
   13697     MethodD = FunTmpl->getTemplatedDecl();
   13698 
   13699   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
   13700   if (!Method)
   13701     return;
   13702 
   13703   // Check the exception specification.
   13704   llvm::SmallVector<QualType, 4> Exceptions;
   13705   FunctionProtoType::ExceptionSpecInfo ESI;
   13706   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
   13707                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
   13708                               ESI);
   13709 
   13710   // Update the exception specification on the function type.
   13711   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
   13712 
   13713   if (Method->isStatic())
   13714     checkThisInStaticMemberFunctionExceptionSpec(Method);
   13715 
   13716   if (Method->isVirtual()) {
   13717     // Check overrides, which we previously had to delay.
   13718     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
   13719                                      OEnd = Method->end_overridden_methods();
   13720          O != OEnd; ++O)
   13721       CheckOverridingFunctionExceptionSpec(Method, *O);
   13722   }
   13723 }
   13724 
   13725 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
   13726 ///
   13727 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
   13728                                        SourceLocation DeclStart,
   13729                                        Declarator &D, Expr *BitWidth,
   13730                                        InClassInitStyle InitStyle,
   13731                                        AccessSpecifier AS,
   13732                                        AttributeList *MSPropertyAttr) {
   13733   IdentifierInfo *II = D.getIdentifier();
   13734   if (!II) {
   13735     Diag(DeclStart, diag::err_anonymous_property);
   13736     return nullptr;
   13737   }
   13738   SourceLocation Loc = D.getIdentifierLoc();
   13739 
   13740   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
   13741   QualType T = TInfo->getType();
   13742   if (getLangOpts().CPlusPlus) {
   13743     CheckExtraCXXDefaultArguments(D);
   13744 
   13745     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
   13746                                         UPPC_DataMemberType)) {
   13747       D.setInvalidType();
   13748       T = Context.IntTy;
   13749       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
   13750     }
   13751   }
   13752 
   13753   DiagnoseFunctionSpecifiers(D.getDeclSpec());
   13754 
   13755   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
   13756     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
   13757          diag::err_invalid_thread)
   13758       << DeclSpec::getSpecifierName(TSCS);
   13759 
   13760   // Check to see if this name was declared as a member previously
   13761   NamedDecl *PrevDecl = nullptr;
   13762   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
   13763   LookupName(Previous, S);
   13764   switch (Previous.getResultKind()) {
   13765   case LookupResult::Found:
   13766   case LookupResult::FoundUnresolvedValue:
   13767     PrevDecl = Previous.getAsSingle<NamedDecl>();
   13768     break;
   13769 
   13770   case LookupResult::FoundOverloaded:
   13771     PrevDecl = Previous.getRepresentativeDecl();
   13772     break;
   13773 
   13774   case LookupResult::NotFound:
   13775   case LookupResult::NotFoundInCurrentInstantiation:
   13776   case LookupResult::Ambiguous:
   13777     break;
   13778   }
   13779 
   13780   if (PrevDecl && PrevDecl->isTemplateParameter()) {
   13781     // Maybe we will complain about the shadowed template parameter.
   13782     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
   13783     // Just pretend that we didn't see the previous declaration.
   13784     PrevDecl = nullptr;
   13785   }
   13786 
   13787   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
   13788     PrevDecl = nullptr;
   13789 
   13790   SourceLocation TSSL = D.getLocStart();
   13791   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
   13792   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
   13793       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
   13794   ProcessDeclAttributes(TUScope, NewPD, D);
   13795   NewPD->setAccess(AS);
   13796 
   13797   if (NewPD->isInvalidDecl())
   13798     Record->setInvalidDecl();
   13799 
   13800   if (D.getDeclSpec().isModulePrivateSpecified())
   13801     NewPD->setModulePrivate();
   13802 
   13803   if (NewPD->isInvalidDecl() && PrevDecl) {
   13804     // Don't introduce NewFD into scope; there's already something
   13805     // with the same name in the same scope.
   13806   } else if (II) {
   13807     PushOnScopeChains(NewPD, S);
   13808   } else
   13809     Record->addDecl(NewPD);
   13810 
   13811   return NewPD;
   13812 }
   13813