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)