clang API Documentation

SemaDeclCXX.cpp
Go to the documentation of this file.
00001 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for C++ declarations.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "clang/AST/ASTConsumer.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/ASTLambda.h"
00018 #include "clang/AST/ASTMutationListener.h"
00019 #include "clang/AST/CXXInheritance.h"
00020 #include "clang/AST/CharUnits.h"
00021 #include "clang/AST/EvaluatedExprVisitor.h"
00022 #include "clang/AST/ExprCXX.h"
00023 #include "clang/AST/RecordLayout.h"
00024 #include "clang/AST/RecursiveASTVisitor.h"
00025 #include "clang/AST/StmtVisitor.h"
00026 #include "clang/AST/TypeLoc.h"
00027 #include "clang/AST/TypeOrdering.h"
00028 #include "clang/Basic/PartialDiagnostic.h"
00029 #include "clang/Basic/TargetInfo.h"
00030 #include "clang/Lex/LiteralSupport.h"
00031 #include "clang/Lex/Preprocessor.h"
00032 #include "clang/Sema/CXXFieldCollector.h"
00033 #include "clang/Sema/DeclSpec.h"
00034 #include "clang/Sema/Initialization.h"
00035 #include "clang/Sema/Lookup.h"
00036 #include "clang/Sema/ParsedTemplate.h"
00037 #include "clang/Sema/Scope.h"
00038 #include "clang/Sema/ScopeInfo.h"
00039 #include "clang/Sema/Template.h"
00040 #include "llvm/ADT/STLExtras.h"
00041 #include "llvm/ADT/SmallString.h"
00042 #include <map>
00043 #include <set>
00044 
00045 using namespace clang;
00046 
00047 //===----------------------------------------------------------------------===//
00048 // CheckDefaultArgumentVisitor
00049 //===----------------------------------------------------------------------===//
00050 
00051 namespace {
00052   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
00053   /// the default argument of a parameter to determine whether it
00054   /// contains any ill-formed subexpressions. For example, this will
00055   /// diagnose the use of local variables or parameters within the
00056   /// default argument expression.
00057   class CheckDefaultArgumentVisitor
00058     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
00059     Expr *DefaultArg;
00060     Sema *S;
00061 
00062   public:
00063     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
00064       : DefaultArg(defarg), S(s) {}
00065 
00066     bool VisitExpr(Expr *Node);
00067     bool VisitDeclRefExpr(DeclRefExpr *DRE);
00068     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
00069     bool VisitLambdaExpr(LambdaExpr *Lambda);
00070     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
00071   };
00072 
00073   /// VisitExpr - Visit all of the children of this expression.
00074   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
00075     bool IsInvalid = false;
00076     for (Stmt::child_range I = Node->children(); I; ++I)
00077       IsInvalid |= Visit(*I);
00078     return IsInvalid;
00079   }
00080 
00081   /// VisitDeclRefExpr - Visit a reference to a declaration, to
00082   /// determine whether this declaration can be used in the default
00083   /// argument expression.
00084   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
00085     NamedDecl *Decl = DRE->getDecl();
00086     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
00087       // C++ [dcl.fct.default]p9
00088       //   Default arguments are evaluated each time the function is
00089       //   called. The order of evaluation of function arguments is
00090       //   unspecified. Consequently, parameters of a function shall not
00091       //   be used in default argument expressions, even if they are not
00092       //   evaluated. Parameters of a function declared before a default
00093       //   argument expression are in scope and can hide namespace and
00094       //   class member names.
00095       return S->Diag(DRE->getLocStart(),
00096                      diag::err_param_default_argument_references_param)
00097          << Param->getDeclName() << DefaultArg->getSourceRange();
00098     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
00099       // C++ [dcl.fct.default]p7
00100       //   Local variables shall not be used in default argument
00101       //   expressions.
00102       if (VDecl->isLocalVarDecl())
00103         return S->Diag(DRE->getLocStart(),
00104                        diag::err_param_default_argument_references_local)
00105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
00106     }
00107 
00108     return false;
00109   }
00110 
00111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
00112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
00113     // C++ [dcl.fct.default]p8:
00114     //   The keyword this shall not be used in a default argument of a
00115     //   member function.
00116     return S->Diag(ThisE->getLocStart(),
00117                    diag::err_param_default_argument_references_this)
00118                << ThisE->getSourceRange();
00119   }
00120 
00121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
00122     bool Invalid = false;
00123     for (PseudoObjectExpr::semantics_iterator
00124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
00125       Expr *E = *i;
00126 
00127       // Look through bindings.
00128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
00129         E = OVE->getSourceExpr();
00130         assert(E && "pseudo-object binding without source expression?");
00131       }
00132 
00133       Invalid |= Visit(E);
00134     }
00135     return Invalid;
00136   }
00137 
00138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
00139     // C++11 [expr.lambda.prim]p13:
00140     //   A lambda-expression appearing in a default argument shall not
00141     //   implicitly or explicitly capture any entity.
00142     if (Lambda->capture_begin() == Lambda->capture_end())
00143       return false;
00144 
00145     return S->Diag(Lambda->getLocStart(), 
00146                    diag::err_lambda_capture_default_arg);
00147   }
00148 }
00149 
00150 void
00151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
00152                                                  const CXXMethodDecl *Method) {
00153   // If we have an MSAny spec already, don't bother.
00154   if (!Method || ComputedEST == EST_MSAny)
00155     return;
00156 
00157   const FunctionProtoType *Proto
00158     = Method->getType()->getAs<FunctionProtoType>();
00159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
00160   if (!Proto)
00161     return;
00162 
00163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
00164 
00165   // If this function can throw any exceptions, make a note of that.
00166   if (EST == EST_MSAny || EST == EST_None) {
00167     ClearExceptions();
00168     ComputedEST = EST;
00169     return;
00170   }
00171 
00172   // FIXME: If the call to this decl is using any of its default arguments, we
00173   // need to search them for potentially-throwing calls.
00174 
00175   // If this function has a basic noexcept, it doesn't affect the outcome.
00176   if (EST == EST_BasicNoexcept)
00177     return;
00178 
00179   // If we have a throw-all spec at this point, ignore the function.
00180   if (ComputedEST == EST_None)
00181     return;
00182 
00183   // If we're still at noexcept(true) and there's a nothrow() callee,
00184   // change to that specification.
00185   if (EST == EST_DynamicNone) {
00186     if (ComputedEST == EST_BasicNoexcept)
00187       ComputedEST = EST_DynamicNone;
00188     return;
00189   }
00190 
00191   // Check out noexcept specs.
00192   if (EST == EST_ComputedNoexcept) {
00193     FunctionProtoType::NoexceptResult NR =
00194         Proto->getNoexceptSpec(Self->Context);
00195     assert(NR != FunctionProtoType::NR_NoNoexcept &&
00196            "Must have noexcept result for EST_ComputedNoexcept.");
00197     assert(NR != FunctionProtoType::NR_Dependent &&
00198            "Should not generate implicit declarations for dependent cases, "
00199            "and don't know how to handle them anyway.");
00200 
00201     // noexcept(false) -> no spec on the new function
00202     if (NR == FunctionProtoType::NR_Throw) {
00203       ClearExceptions();
00204       ComputedEST = EST_None;
00205     }
00206     // noexcept(true) won't change anything either.
00207     return;
00208   }
00209 
00210   assert(EST == EST_Dynamic && "EST case not considered earlier.");
00211   assert(ComputedEST != EST_None &&
00212          "Shouldn't collect exceptions when throw-all is guaranteed.");
00213   ComputedEST = EST_Dynamic;
00214   // Record the exceptions in this function's exception specification.
00215   for (const auto &E : Proto->exceptions())
00216     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)))
00217       Exceptions.push_back(E);
00218 }
00219 
00220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
00221   if (!E || ComputedEST == EST_MSAny)
00222     return;
00223 
00224   // FIXME:
00225   //
00226   // C++0x [except.spec]p14:
00227   //   [An] implicit exception-specification specifies the type-id T if and
00228   // only if T is allowed by the exception-specification of a function directly
00229   // invoked by f's implicit definition; f shall allow all exceptions if any
00230   // function it directly invokes allows all exceptions, and f shall allow no
00231   // exceptions if every function it directly invokes allows no exceptions.
00232   //
00233   // Note in particular that if an implicit exception-specification is generated
00234   // for a function containing a throw-expression, that specification can still
00235   // be noexcept(true).
00236   //
00237   // Note also that 'directly invoked' is not defined in the standard, and there
00238   // is no indication that we should only consider potentially-evaluated calls.
00239   //
00240   // Ultimately we should implement the intent of the standard: the exception
00241   // specification should be the set of exceptions which can be thrown by the
00242   // implicit definition. For now, we assume that any non-nothrow expression can
00243   // throw any exception.
00244 
00245   if (Self->canThrow(E))
00246     ComputedEST = EST_None;
00247 }
00248 
00249 bool
00250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
00251                               SourceLocation EqualLoc) {
00252   if (RequireCompleteType(Param->getLocation(), Param->getType(),
00253                           diag::err_typecheck_decl_incomplete_type)) {
00254     Param->setInvalidDecl();
00255     return true;
00256   }
00257 
00258   // C++ [dcl.fct.default]p5
00259   //   A default argument expression is implicitly converted (clause
00260   //   4) to the parameter type. The default argument expression has
00261   //   the same semantic constraints as the initializer expression in
00262   //   a declaration of a variable of the parameter type, using the
00263   //   copy-initialization semantics (8.5).
00264   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
00265                                                                     Param);
00266   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
00267                                                            EqualLoc);
00268   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
00269   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
00270   if (Result.isInvalid())
00271     return true;
00272   Arg = Result.getAs<Expr>();
00273 
00274   CheckCompletedExpr(Arg, EqualLoc);
00275   Arg = MaybeCreateExprWithCleanups(Arg);
00276 
00277   // Okay: add the default argument to the parameter
00278   Param->setDefaultArg(Arg);
00279 
00280   // We have already instantiated this parameter; provide each of the 
00281   // instantiations with the uninstantiated default argument.
00282   UnparsedDefaultArgInstantiationsMap::iterator InstPos
00283     = UnparsedDefaultArgInstantiations.find(Param);
00284   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
00285     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
00286       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
00287     
00288     // We're done tracking this parameter's instantiations.
00289     UnparsedDefaultArgInstantiations.erase(InstPos);
00290   }
00291   
00292   return false;
00293 }
00294 
00295 /// ActOnParamDefaultArgument - Check whether the default argument
00296 /// provided for a function parameter is well-formed. If so, attach it
00297 /// to the parameter declaration.
00298 void
00299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
00300                                 Expr *DefaultArg) {
00301   if (!param || !DefaultArg)
00302     return;
00303 
00304   ParmVarDecl *Param = cast<ParmVarDecl>(param);
00305   UnparsedDefaultArgLocs.erase(Param);
00306 
00307   // Default arguments are only permitted in C++
00308   if (!getLangOpts().CPlusPlus) {
00309     Diag(EqualLoc, diag::err_param_default_argument)
00310       << DefaultArg->getSourceRange();
00311     Param->setInvalidDecl();
00312     return;
00313   }
00314 
00315   // Check for unexpanded parameter packs.
00316   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
00317     Param->setInvalidDecl();
00318     return;
00319   }    
00320       
00321   // Check that the default argument is well-formed
00322   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
00323   if (DefaultArgChecker.Visit(DefaultArg)) {
00324     Param->setInvalidDecl();
00325     return;
00326   }
00327 
00328   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
00329 }
00330 
00331 /// ActOnParamUnparsedDefaultArgument - We've seen a default
00332 /// argument for a function parameter, but we can't parse it yet
00333 /// because we're inside a class definition. Note that this default
00334 /// argument will be parsed later.
00335 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
00336                                              SourceLocation EqualLoc,
00337                                              SourceLocation ArgLoc) {
00338   if (!param)
00339     return;
00340 
00341   ParmVarDecl *Param = cast<ParmVarDecl>(param);
00342   Param->setUnparsedDefaultArg();
00343   UnparsedDefaultArgLocs[Param] = ArgLoc;
00344 }
00345 
00346 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
00347 /// the default argument for the parameter param failed.
00348 void Sema::ActOnParamDefaultArgumentError(Decl *param,
00349                                           SourceLocation EqualLoc) {
00350   if (!param)
00351     return;
00352 
00353   ParmVarDecl *Param = cast<ParmVarDecl>(param);
00354   Param->setInvalidDecl();
00355   UnparsedDefaultArgLocs.erase(Param);
00356   Param->setDefaultArg(new(Context)
00357                        OpaqueValueExpr(EqualLoc,
00358                                        Param->getType().getNonReferenceType(),
00359                                        VK_RValue));
00360 }
00361 
00362 /// CheckExtraCXXDefaultArguments - Check for any extra default
00363 /// arguments in the declarator, which is not a function declaration
00364 /// or definition and therefore is not permitted to have default
00365 /// arguments. This routine should be invoked for every declarator
00366 /// that is not a function declaration or definition.
00367 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
00368   // C++ [dcl.fct.default]p3
00369   //   A default argument expression shall be specified only in the
00370   //   parameter-declaration-clause of a function declaration or in a
00371   //   template-parameter (14.1). It shall not be specified for a
00372   //   parameter pack. If it is specified in a
00373   //   parameter-declaration-clause, it shall not occur within a
00374   //   declarator or abstract-declarator of a parameter-declaration.
00375   bool MightBeFunction = D.isFunctionDeclarationContext();
00376   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
00377     DeclaratorChunk &chunk = D.getTypeObject(i);
00378     if (chunk.Kind == DeclaratorChunk::Function) {
00379       if (MightBeFunction) {
00380         // This is a function declaration. It can have default arguments, but
00381         // keep looking in case its return type is a function type with default
00382         // arguments.
00383         MightBeFunction = false;
00384         continue;
00385       }
00386       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
00387            ++argIdx) {
00388         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
00389         if (Param->hasUnparsedDefaultArg()) {
00390           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
00391           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
00392             << SourceRange((*Toks)[1].getLocation(),
00393                            Toks->back().getLocation());
00394           delete Toks;
00395           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
00396         } else if (Param->getDefaultArg()) {
00397           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
00398             << Param->getDefaultArg()->getSourceRange();
00399           Param->setDefaultArg(nullptr);
00400         }
00401       }
00402     } else if (chunk.Kind != DeclaratorChunk::Paren) {
00403       MightBeFunction = false;
00404     }
00405   }
00406 }
00407 
00408 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
00409   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
00410     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
00411     if (!PVD->hasDefaultArg())
00412       return false;
00413     if (!PVD->hasInheritedDefaultArg())
00414       return true;
00415   }
00416   return false;
00417 }
00418 
00419 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
00420 /// function, once we already know that they have the same
00421 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
00422 /// error, false otherwise.
00423 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
00424                                 Scope *S) {
00425   bool Invalid = false;
00426 
00427   // C++ [dcl.fct.default]p4:
00428   //   For non-template functions, default arguments can be added in
00429   //   later declarations of a function in the same
00430   //   scope. Declarations in different scopes have completely
00431   //   distinct sets of default arguments. That is, declarations in
00432   //   inner scopes do not acquire default arguments from
00433   //   declarations in outer scopes, and vice versa. In a given
00434   //   function declaration, all parameters subsequent to a
00435   //   parameter with a default argument shall have default
00436   //   arguments supplied in this or previous declarations. A
00437   //   default argument shall not be redefined by a later
00438   //   declaration (not even to the same value).
00439   //
00440   // C++ [dcl.fct.default]p6:
00441   //   Except for member functions of class templates, the default arguments
00442   //   in a member function definition that appears outside of the class
00443   //   definition are added to the set of default arguments provided by the
00444   //   member function declaration in the class definition.
00445   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
00446     ParmVarDecl *OldParam = Old->getParamDecl(p);
00447     ParmVarDecl *NewParam = New->getParamDecl(p);
00448 
00449     bool OldParamHasDfl = OldParam->hasDefaultArg();
00450     bool NewParamHasDfl = NewParam->hasDefaultArg();
00451 
00452     // The declaration context corresponding to the scope is the semantic
00453     // parent, unless this is a local function declaration, in which case
00454     // it is that surrounding function.
00455     DeclContext *ScopeDC = New->isLocalExternDecl()
00456                                ? New->getLexicalDeclContext()
00457                                : New->getDeclContext();
00458     if (S && !isDeclInScope(Old, ScopeDC, S) &&
00459         !New->getDeclContext()->isRecord())
00460       // Ignore default parameters of old decl if they are not in
00461       // the same scope and this is not an out-of-line definition of
00462       // a member function.
00463       OldParamHasDfl = false;
00464     if (New->isLocalExternDecl() != Old->isLocalExternDecl())
00465       // If only one of these is a local function declaration, then they are
00466       // declared in different scopes, even though isDeclInScope may think
00467       // they're in the same scope. (If both are local, the scope check is
00468       // sufficent, and if neither is local, then they are in the same scope.)
00469       OldParamHasDfl = false;
00470 
00471     if (OldParamHasDfl && NewParamHasDfl) {
00472 
00473       unsigned DiagDefaultParamID =
00474         diag::err_param_default_argument_redefinition;
00475 
00476       // MSVC accepts that default parameters be redefined for member functions
00477       // of template class. The new default parameter's value is ignored.
00478       Invalid = true;
00479       if (getLangOpts().MicrosoftExt) {
00480         CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
00481         if (MD && MD->getParent()->getDescribedClassTemplate()) {
00482           // Merge the old default argument into the new parameter.
00483           NewParam->setHasInheritedDefaultArg();
00484           if (OldParam->hasUninstantiatedDefaultArg())
00485             NewParam->setUninstantiatedDefaultArg(
00486                                       OldParam->getUninstantiatedDefaultArg());
00487           else
00488             NewParam->setDefaultArg(OldParam->getInit());
00489           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
00490           Invalid = false;
00491         }
00492       }
00493       
00494       // FIXME: If we knew where the '=' was, we could easily provide a fix-it 
00495       // hint here. Alternatively, we could walk the type-source information
00496       // for NewParam to find the last source location in the type... but it
00497       // isn't worth the effort right now. This is the kind of test case that
00498       // is hard to get right:
00499       //   int f(int);
00500       //   void g(int (*fp)(int) = f);
00501       //   void g(int (*fp)(int) = &f);
00502       Diag(NewParam->getLocation(), DiagDefaultParamID)
00503         << NewParam->getDefaultArgRange();
00504       
00505       // Look for the function declaration where the default argument was
00506       // actually written, which may be a declaration prior to Old.
00507       for (FunctionDecl *Older = Old->getPreviousDecl();
00508            Older; Older = Older->getPreviousDecl()) {
00509         if (!Older->getParamDecl(p)->hasDefaultArg())
00510           break;
00511         
00512         OldParam = Older->getParamDecl(p);
00513       }        
00514       
00515       Diag(OldParam->getLocation(), diag::note_previous_definition)
00516         << OldParam->getDefaultArgRange();
00517     } else if (OldParamHasDfl) {
00518       // Merge the old default argument into the new parameter.
00519       // It's important to use getInit() here;  getDefaultArg()
00520       // strips off any top-level ExprWithCleanups.
00521       NewParam->setHasInheritedDefaultArg();
00522       if (OldParam->hasUninstantiatedDefaultArg())
00523         NewParam->setUninstantiatedDefaultArg(
00524                                       OldParam->getUninstantiatedDefaultArg());
00525       else
00526         NewParam->setDefaultArg(OldParam->getInit());
00527     } else if (NewParamHasDfl) {
00528       if (New->getDescribedFunctionTemplate()) {
00529         // Paragraph 4, quoted above, only applies to non-template functions.
00530         Diag(NewParam->getLocation(),
00531              diag::err_param_default_argument_template_redecl)
00532           << NewParam->getDefaultArgRange();
00533         Diag(Old->getLocation(), diag::note_template_prev_declaration)
00534           << false;
00535       } else if (New->getTemplateSpecializationKind()
00536                    != TSK_ImplicitInstantiation &&
00537                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
00538         // C++ [temp.expr.spec]p21:
00539         //   Default function arguments shall not be specified in a declaration
00540         //   or a definition for one of the following explicit specializations:
00541         //     - the explicit specialization of a function template;
00542         //     - the explicit specialization of a member function template;
00543         //     - the explicit specialization of a member function of a class 
00544         //       template where the class template specialization to which the
00545         //       member function specialization belongs is implicitly 
00546         //       instantiated.
00547         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
00548           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
00549           << New->getDeclName()
00550           << NewParam->getDefaultArgRange();
00551       } else if (New->getDeclContext()->isDependentContext()) {
00552         // C++ [dcl.fct.default]p6 (DR217):
00553         //   Default arguments for a member function of a class template shall 
00554         //   be specified on the initial declaration of the member function 
00555         //   within the class template.
00556         //
00557         // Reading the tea leaves a bit in DR217 and its reference to DR205 
00558         // leads me to the conclusion that one cannot add default function 
00559         // arguments for an out-of-line definition of a member function of a 
00560         // dependent type.
00561         int WhichKind = 2;
00562         if (CXXRecordDecl *Record 
00563               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
00564           if (Record->getDescribedClassTemplate())
00565             WhichKind = 0;
00566           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
00567             WhichKind = 1;
00568           else
00569             WhichKind = 2;
00570         }
00571         
00572         Diag(NewParam->getLocation(), 
00573              diag::err_param_default_argument_member_template_redecl)
00574           << WhichKind
00575           << NewParam->getDefaultArgRange();
00576       }
00577     }
00578   }
00579 
00580   // DR1344: If a default argument is added outside a class definition and that
00581   // default argument makes the function a special member function, the program
00582   // is ill-formed. This can only happen for constructors.
00583   if (isa<CXXConstructorDecl>(New) &&
00584       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
00585     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
00586                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
00587     if (NewSM != OldSM) {
00588       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
00589       assert(NewParam->hasDefaultArg());
00590       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
00591         << NewParam->getDefaultArgRange() << NewSM;
00592       Diag(Old->getLocation(), diag::note_previous_declaration);
00593     }
00594   }
00595 
00596   const FunctionDecl *Def;
00597   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
00598   // template has a constexpr specifier then all its declarations shall
00599   // contain the constexpr specifier.
00600   if (New->isConstexpr() != Old->isConstexpr()) {
00601     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
00602       << New << New->isConstexpr();
00603     Diag(Old->getLocation(), diag::note_previous_declaration);
00604     Invalid = true;
00605   } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
00606     // C++11 [dcl.fcn.spec]p4:
00607     //   If the definition of a function appears in a translation unit before its
00608     //   first declaration as inline, the program is ill-formed.
00609     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
00610     Diag(Def->getLocation(), diag::note_previous_definition);
00611     Invalid = true;
00612   }
00613 
00614   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
00615   // argument expression, that declaration shall be a definition and shall be
00616   // the only declaration of the function or function template in the
00617   // translation unit.
00618   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
00619       functionDeclHasDefaultArgument(Old)) {
00620     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
00621     Diag(Old->getLocation(), diag::note_previous_declaration);
00622     Invalid = true;
00623   }
00624 
00625   if (CheckEquivalentExceptionSpec(Old, New))
00626     Invalid = true;
00627 
00628   return Invalid;
00629 }
00630 
00631 /// \brief Merge the exception specifications of two variable declarations.
00632 ///
00633 /// This is called when there's a redeclaration of a VarDecl. The function
00634 /// checks if the redeclaration might have an exception specification and
00635 /// validates compatibility and merges the specs if necessary.
00636 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
00637   // Shortcut if exceptions are disabled.
00638   if (!getLangOpts().CXXExceptions)
00639     return;
00640 
00641   assert(Context.hasSameType(New->getType(), Old->getType()) &&
00642          "Should only be called if types are otherwise the same.");
00643 
00644   QualType NewType = New->getType();
00645   QualType OldType = Old->getType();
00646 
00647   // We're only interested in pointers and references to functions, as well
00648   // as pointers to member functions.
00649   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
00650     NewType = R->getPointeeType();
00651     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
00652   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
00653     NewType = P->getPointeeType();
00654     OldType = OldType->getAs<PointerType>()->getPointeeType();
00655   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
00656     NewType = M->getPointeeType();
00657     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
00658   }
00659 
00660   if (!NewType->isFunctionProtoType())
00661     return;
00662 
00663   // There's lots of special cases for functions. For function pointers, system
00664   // libraries are hopefully not as broken so that we don't need these
00665   // workarounds.
00666   if (CheckEquivalentExceptionSpec(
00667         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
00668         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
00669     New->setInvalidDecl();
00670   }
00671 }
00672 
00673 /// CheckCXXDefaultArguments - Verify that the default arguments for a
00674 /// function declaration are well-formed according to C++
00675 /// [dcl.fct.default].
00676 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
00677   unsigned NumParams = FD->getNumParams();
00678   unsigned p;
00679 
00680   // Find first parameter with a default argument
00681   for (p = 0; p < NumParams; ++p) {
00682     ParmVarDecl *Param = FD->getParamDecl(p);
00683     if (Param->hasDefaultArg())
00684       break;
00685   }
00686 
00687   // C++ [dcl.fct.default]p4:
00688   //   In a given function declaration, all parameters
00689   //   subsequent to a parameter with a default argument shall
00690   //   have default arguments supplied in this or previous
00691   //   declarations. A default argument shall not be redefined
00692   //   by a later declaration (not even to the same value).
00693   unsigned LastMissingDefaultArg = 0;
00694   for (; p < NumParams; ++p) {
00695     ParmVarDecl *Param = FD->getParamDecl(p);
00696     if (!Param->hasDefaultArg()) {
00697       if (Param->isInvalidDecl())
00698         /* We already complained about this parameter. */;
00699       else if (Param->getIdentifier())
00700         Diag(Param->getLocation(),
00701              diag::err_param_default_argument_missing_name)
00702           << Param->getIdentifier();
00703       else
00704         Diag(Param->getLocation(),
00705              diag::err_param_default_argument_missing);
00706 
00707       LastMissingDefaultArg = p;
00708     }
00709   }
00710 
00711   if (LastMissingDefaultArg > 0) {
00712     // Some default arguments were missing. Clear out all of the
00713     // default arguments up to (and including) the last missing
00714     // default argument, so that we leave the function parameters
00715     // in a semantically valid state.
00716     for (p = 0; p <= LastMissingDefaultArg; ++p) {
00717       ParmVarDecl *Param = FD->getParamDecl(p);
00718       if (Param->hasDefaultArg()) {
00719         Param->setDefaultArg(nullptr);
00720       }
00721     }
00722   }
00723 }
00724 
00725 // CheckConstexprParameterTypes - Check whether a function's parameter types
00726 // are all literal types. If so, return true. If not, produce a suitable
00727 // diagnostic and return false.
00728 static bool CheckConstexprParameterTypes(Sema &SemaRef,
00729                                          const FunctionDecl *FD) {
00730   unsigned ArgIndex = 0;
00731   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
00732   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
00733                                               e = FT->param_type_end();
00734        i != e; ++i, ++ArgIndex) {
00735     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
00736     SourceLocation ParamLoc = PD->getLocation();
00737     if (!(*i)->isDependentType() &&
00738         SemaRef.RequireLiteralType(ParamLoc, *i,
00739                                    diag::err_constexpr_non_literal_param,
00740                                    ArgIndex+1, PD->getSourceRange(),
00741                                    isa<CXXConstructorDecl>(FD)))
00742       return false;
00743   }
00744   return true;
00745 }
00746 
00747 /// \brief Get diagnostic %select index for tag kind for
00748 /// record diagnostic message.
00749 /// WARNING: Indexes apply to particular diagnostics only!
00750 ///
00751 /// \returns diagnostic %select index.
00752 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
00753   switch (Tag) {
00754   case TTK_Struct: return 0;
00755   case TTK_Interface: return 1;
00756   case TTK_Class:  return 2;
00757   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
00758   }
00759 }
00760 
00761 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
00762 // the requirements of a constexpr function definition or a constexpr
00763 // constructor definition. If so, return true. If not, produce appropriate
00764 // diagnostics and return false.
00765 //
00766 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
00767 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
00768   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
00769   if (MD && MD->isInstance()) {
00770     // C++11 [dcl.constexpr]p4:
00771     //  The definition of a constexpr constructor shall satisfy the following
00772     //  constraints:
00773     //  - the class shall not have any virtual base classes;
00774     const CXXRecordDecl *RD = MD->getParent();
00775     if (RD->getNumVBases()) {
00776       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
00777         << isa<CXXConstructorDecl>(NewFD)
00778         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
00779       for (const auto &I : RD->vbases())
00780         Diag(I.getLocStart(),
00781              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
00782       return false;
00783     }
00784   }
00785 
00786   if (!isa<CXXConstructorDecl>(NewFD)) {
00787     // C++11 [dcl.constexpr]p3:
00788     //  The definition of a constexpr function shall satisfy the following
00789     //  constraints:
00790     // - it shall not be virtual;
00791     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
00792     if (Method && Method->isVirtual()) {
00793       Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
00794 
00795       // If it's not obvious why this function is virtual, find an overridden
00796       // function which uses the 'virtual' keyword.
00797       const CXXMethodDecl *WrittenVirtual = Method;
00798       while (!WrittenVirtual->isVirtualAsWritten())
00799         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
00800       if (WrittenVirtual != Method)
00801         Diag(WrittenVirtual->getLocation(),
00802              diag::note_overridden_virtual_function);
00803       return false;
00804     }
00805 
00806     // - its return type shall be a literal type;
00807     QualType RT = NewFD->getReturnType();
00808     if (!RT->isDependentType() &&
00809         RequireLiteralType(NewFD->getLocation(), RT,
00810                            diag::err_constexpr_non_literal_return))
00811       return false;
00812   }
00813 
00814   // - each of its parameter types shall be a literal type;
00815   if (!CheckConstexprParameterTypes(*this, NewFD))
00816     return false;
00817 
00818   return true;
00819 }
00820 
00821 /// Check the given declaration statement is legal within a constexpr function
00822 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
00823 ///
00824 /// \return true if the body is OK (maybe only as an extension), false if we
00825 ///         have diagnosed a problem.
00826 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
00827                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
00828   // C++11 [dcl.constexpr]p3 and p4:
00829   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
00830   //  contain only
00831   for (const auto *DclIt : DS->decls()) {
00832     switch (DclIt->getKind()) {
00833     case Decl::StaticAssert:
00834     case Decl::Using:
00835     case Decl::UsingShadow:
00836     case Decl::UsingDirective:
00837     case Decl::UnresolvedUsingTypename:
00838     case Decl::UnresolvedUsingValue:
00839       //   - static_assert-declarations
00840       //   - using-declarations,
00841       //   - using-directives,
00842       continue;
00843 
00844     case Decl::Typedef:
00845     case Decl::TypeAlias: {
00846       //   - typedef declarations and alias-declarations that do not define
00847       //     classes or enumerations,
00848       const auto *TN = cast<TypedefNameDecl>(DclIt);
00849       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
00850         // Don't allow variably-modified types in constexpr functions.
00851         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
00852         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
00853           << TL.getSourceRange() << TL.getType()
00854           << isa<CXXConstructorDecl>(Dcl);
00855         return false;
00856       }
00857       continue;
00858     }
00859 
00860     case Decl::Enum:
00861     case Decl::CXXRecord:
00862       // C++1y allows types to be defined, not just declared.
00863       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
00864         SemaRef.Diag(DS->getLocStart(),
00865                      SemaRef.getLangOpts().CPlusPlus14
00866                        ? diag::warn_cxx11_compat_constexpr_type_definition
00867                        : diag::ext_constexpr_type_definition)
00868           << isa<CXXConstructorDecl>(Dcl);
00869       continue;
00870 
00871     case Decl::EnumConstant:
00872     case Decl::IndirectField:
00873     case Decl::ParmVar:
00874       // These can only appear with other declarations which are banned in
00875       // C++11 and permitted in C++1y, so ignore them.
00876       continue;
00877 
00878     case Decl::Var: {
00879       // C++1y [dcl.constexpr]p3 allows anything except:
00880       //   a definition of a variable of non-literal type or of static or
00881       //   thread storage duration or for which no initialization is performed.
00882       const auto *VD = cast<VarDecl>(DclIt);
00883       if (VD->isThisDeclarationADefinition()) {
00884         if (VD->isStaticLocal()) {
00885           SemaRef.Diag(VD->getLocation(),
00886                        diag::err_constexpr_local_var_static)
00887             << isa<CXXConstructorDecl>(Dcl)
00888             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
00889           return false;
00890         }
00891         if (!VD->getType()->isDependentType() &&
00892             SemaRef.RequireLiteralType(
00893               VD->getLocation(), VD->getType(),
00894               diag::err_constexpr_local_var_non_literal_type,
00895               isa<CXXConstructorDecl>(Dcl)))
00896           return false;
00897         if (!VD->getType()->isDependentType() &&
00898             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
00899           SemaRef.Diag(VD->getLocation(),
00900                        diag::err_constexpr_local_var_no_init)
00901             << isa<CXXConstructorDecl>(Dcl);
00902           return false;
00903         }
00904       }
00905       SemaRef.Diag(VD->getLocation(),
00906                    SemaRef.getLangOpts().CPlusPlus14
00907                     ? diag::warn_cxx11_compat_constexpr_local_var
00908                     : diag::ext_constexpr_local_var)
00909         << isa<CXXConstructorDecl>(Dcl);
00910       continue;
00911     }
00912 
00913     case Decl::NamespaceAlias:
00914     case Decl::Function:
00915       // These are disallowed in C++11 and permitted in C++1y. Allow them
00916       // everywhere as an extension.
00917       if (!Cxx1yLoc.isValid())
00918         Cxx1yLoc = DS->getLocStart();
00919       continue;
00920 
00921     default:
00922       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
00923         << isa<CXXConstructorDecl>(Dcl);
00924       return false;
00925     }
00926   }
00927 
00928   return true;
00929 }
00930 
00931 /// Check that the given field is initialized within a constexpr constructor.
00932 ///
00933 /// \param Dcl The constexpr constructor being checked.
00934 /// \param Field The field being checked. This may be a member of an anonymous
00935 ///        struct or union nested within the class being checked.
00936 /// \param Inits All declarations, including anonymous struct/union members and
00937 ///        indirect members, for which any initialization was provided.
00938 /// \param Diagnosed Set to true if an error is produced.
00939 static void CheckConstexprCtorInitializer(Sema &SemaRef,
00940                                           const FunctionDecl *Dcl,
00941                                           FieldDecl *Field,
00942                                           llvm::SmallSet<Decl*, 16> &Inits,
00943                                           bool &Diagnosed) {
00944   if (Field->isInvalidDecl())
00945     return;
00946 
00947   if (Field->isUnnamedBitfield())
00948     return;
00949 
00950   // Anonymous unions with no variant members and empty anonymous structs do not
00951   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
00952   // indirect fields don't need initializing.
00953   if (Field->isAnonymousStructOrUnion() &&
00954       (Field->getType()->isUnionType()
00955            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
00956            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
00957     return;
00958 
00959   if (!Inits.count(Field)) {
00960     if (!Diagnosed) {
00961       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
00962       Diagnosed = true;
00963     }
00964     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
00965   } else if (Field->isAnonymousStructOrUnion()) {
00966     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
00967     for (auto *I : RD->fields())
00968       // If an anonymous union contains an anonymous struct of which any member
00969       // is initialized, all members must be initialized.
00970       if (!RD->isUnion() || Inits.count(I))
00971         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
00972   }
00973 }
00974 
00975 /// Check the provided statement is allowed in a constexpr function
00976 /// definition.
00977 static bool
00978 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
00979                            SmallVectorImpl<SourceLocation> &ReturnStmts,
00980                            SourceLocation &Cxx1yLoc) {
00981   // - its function-body shall be [...] a compound-statement that contains only
00982   switch (S->getStmtClass()) {
00983   case Stmt::NullStmtClass:
00984     //   - null statements,
00985     return true;
00986 
00987   case Stmt::DeclStmtClass:
00988     //   - static_assert-declarations
00989     //   - using-declarations,
00990     //   - using-directives,
00991     //   - typedef declarations and alias-declarations that do not define
00992     //     classes or enumerations,
00993     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
00994       return false;
00995     return true;
00996 
00997   case Stmt::ReturnStmtClass:
00998     //   - and exactly one return statement;
00999     if (isa<CXXConstructorDecl>(Dcl)) {
01000       // C++1y allows return statements in constexpr constructors.
01001       if (!Cxx1yLoc.isValid())
01002         Cxx1yLoc = S->getLocStart();
01003       return true;
01004     }
01005 
01006     ReturnStmts.push_back(S->getLocStart());
01007     return true;
01008 
01009   case Stmt::CompoundStmtClass: {
01010     // C++1y allows compound-statements.
01011     if (!Cxx1yLoc.isValid())
01012       Cxx1yLoc = S->getLocStart();
01013 
01014     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
01015     for (auto *BodyIt : CompStmt->body()) {
01016       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
01017                                       Cxx1yLoc))
01018         return false;
01019     }
01020     return true;
01021   }
01022 
01023   case Stmt::AttributedStmtClass:
01024     if (!Cxx1yLoc.isValid())
01025       Cxx1yLoc = S->getLocStart();
01026     return true;
01027 
01028   case Stmt::IfStmtClass: {
01029     // C++1y allows if-statements.
01030     if (!Cxx1yLoc.isValid())
01031       Cxx1yLoc = S->getLocStart();
01032 
01033     IfStmt *If = cast<IfStmt>(S);
01034     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
01035                                     Cxx1yLoc))
01036       return false;
01037     if (If->getElse() &&
01038         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
01039                                     Cxx1yLoc))
01040       return false;
01041     return true;
01042   }
01043 
01044   case Stmt::WhileStmtClass:
01045   case Stmt::DoStmtClass:
01046   case Stmt::ForStmtClass:
01047   case Stmt::CXXForRangeStmtClass:
01048   case Stmt::ContinueStmtClass:
01049     // C++1y allows all of these. We don't allow them as extensions in C++11,
01050     // because they don't make sense without variable mutation.
01051     if (!SemaRef.getLangOpts().CPlusPlus14)
01052       break;
01053     if (!Cxx1yLoc.isValid())
01054       Cxx1yLoc = S->getLocStart();
01055     for (Stmt::child_range Children = S->children(); Children; ++Children)
01056       if (*Children &&
01057           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
01058                                       Cxx1yLoc))
01059         return false;
01060     return true;
01061 
01062   case Stmt::SwitchStmtClass:
01063   case Stmt::CaseStmtClass:
01064   case Stmt::DefaultStmtClass:
01065   case Stmt::BreakStmtClass:
01066     // C++1y allows switch-statements, and since they don't need variable
01067     // mutation, we can reasonably allow them in C++11 as an extension.
01068     if (!Cxx1yLoc.isValid())
01069       Cxx1yLoc = S->getLocStart();
01070     for (Stmt::child_range Children = S->children(); Children; ++Children)
01071       if (*Children &&
01072           !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
01073                                       Cxx1yLoc))
01074         return false;
01075     return true;
01076 
01077   default:
01078     if (!isa<Expr>(S))
01079       break;
01080 
01081     // C++1y allows expression-statements.
01082     if (!Cxx1yLoc.isValid())
01083       Cxx1yLoc = S->getLocStart();
01084     return true;
01085   }
01086 
01087   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
01088     << isa<CXXConstructorDecl>(Dcl);
01089   return false;
01090 }
01091 
01092 /// Check the body for the given constexpr function declaration only contains
01093 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
01094 ///
01095 /// \return true if the body is OK, false if we have diagnosed a problem.
01096 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
01097   if (isa<CXXTryStmt>(Body)) {
01098     // C++11 [dcl.constexpr]p3:
01099     //  The definition of a constexpr function shall satisfy the following
01100     //  constraints: [...]
01101     // - its function-body shall be = delete, = default, or a
01102     //   compound-statement
01103     //
01104     // C++11 [dcl.constexpr]p4:
01105     //  In the definition of a constexpr constructor, [...]
01106     // - its function-body shall not be a function-try-block;
01107     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
01108       << isa<CXXConstructorDecl>(Dcl);
01109     return false;
01110   }
01111 
01112   SmallVector<SourceLocation, 4> ReturnStmts;
01113 
01114   // - its function-body shall be [...] a compound-statement that contains only
01115   //   [... list of cases ...]
01116   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
01117   SourceLocation Cxx1yLoc;
01118   for (auto *BodyIt : CompBody->body()) {
01119     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
01120       return false;
01121   }
01122 
01123   if (Cxx1yLoc.isValid())
01124     Diag(Cxx1yLoc,
01125          getLangOpts().CPlusPlus14
01126            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
01127            : diag::ext_constexpr_body_invalid_stmt)
01128       << isa<CXXConstructorDecl>(Dcl);
01129 
01130   if (const CXXConstructorDecl *Constructor
01131         = dyn_cast<CXXConstructorDecl>(Dcl)) {
01132     const CXXRecordDecl *RD = Constructor->getParent();
01133     // DR1359:
01134     // - every non-variant non-static data member and base class sub-object
01135     //   shall be initialized;
01136     // DR1460:
01137     // - if the class is a union having variant members, exactly one of them
01138     //   shall be initialized;
01139     if (RD->isUnion()) {
01140       if (Constructor->getNumCtorInitializers() == 0 &&
01141           RD->hasVariantMembers()) {
01142         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
01143         return false;
01144       }
01145     } else if (!Constructor->isDependentContext() &&
01146                !Constructor->isDelegatingConstructor()) {
01147       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
01148 
01149       // Skip detailed checking if we have enough initializers, and we would
01150       // allow at most one initializer per member.
01151       bool AnyAnonStructUnionMembers = false;
01152       unsigned Fields = 0;
01153       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
01154            E = RD->field_end(); I != E; ++I, ++Fields) {
01155         if (I->isAnonymousStructOrUnion()) {
01156           AnyAnonStructUnionMembers = true;
01157           break;
01158         }
01159       }
01160       // DR1460:
01161       // - if the class is a union-like class, but is not a union, for each of
01162       //   its anonymous union members having variant members, exactly one of
01163       //   them shall be initialized;
01164       if (AnyAnonStructUnionMembers ||
01165           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
01166         // Check initialization of non-static data members. Base classes are
01167         // always initialized so do not need to be checked. Dependent bases
01168         // might not have initializers in the member initializer list.
01169         llvm::SmallSet<Decl*, 16> Inits;
01170         for (const auto *I: Constructor->inits()) {
01171           if (FieldDecl *FD = I->getMember())
01172             Inits.insert(FD);
01173           else if (IndirectFieldDecl *ID = I->getIndirectMember())
01174             Inits.insert(ID->chain_begin(), ID->chain_end());
01175         }
01176 
01177         bool Diagnosed = false;
01178         for (auto *I : RD->fields())
01179           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
01180         if (Diagnosed)
01181           return false;
01182       }
01183     }
01184   } else {
01185     if (ReturnStmts.empty()) {
01186       // C++1y doesn't require constexpr functions to contain a 'return'
01187       // statement. We still do, unless the return type might be void, because
01188       // otherwise if there's no return statement, the function cannot
01189       // be used in a core constant expression.
01190       bool OK = getLangOpts().CPlusPlus14 &&
01191                 (Dcl->getReturnType()->isVoidType() ||
01192                  Dcl->getReturnType()->isDependentType());
01193       Diag(Dcl->getLocation(),
01194            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
01195               : diag::err_constexpr_body_no_return);
01196       return OK;
01197     }
01198     if (ReturnStmts.size() > 1) {
01199       Diag(ReturnStmts.back(),
01200            getLangOpts().CPlusPlus14
01201              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
01202              : diag::ext_constexpr_body_multiple_return);
01203       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
01204         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
01205     }
01206   }
01207 
01208   // C++11 [dcl.constexpr]p5:
01209   //   if no function argument values exist such that the function invocation
01210   //   substitution would produce a constant expression, the program is
01211   //   ill-formed; no diagnostic required.
01212   // C++11 [dcl.constexpr]p3:
01213   //   - every constructor call and implicit conversion used in initializing the
01214   //     return value shall be one of those allowed in a constant expression.
01215   // C++11 [dcl.constexpr]p4:
01216   //   - every constructor involved in initializing non-static data members and
01217   //     base class sub-objects shall be a constexpr constructor.
01218   SmallVector<PartialDiagnosticAt, 8> Diags;
01219   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
01220     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
01221       << isa<CXXConstructorDecl>(Dcl);
01222     for (size_t I = 0, N = Diags.size(); I != N; ++I)
01223       Diag(Diags[I].first, Diags[I].second);
01224     // Don't return false here: we allow this for compatibility in
01225     // system headers.
01226   }
01227 
01228   return true;
01229 }
01230 
01231 /// isCurrentClassName - Determine whether the identifier II is the
01232 /// name of the class type currently being defined. In the case of
01233 /// nested classes, this will only return true if II is the name of
01234 /// the innermost class.
01235 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
01236                               const CXXScopeSpec *SS) {
01237   assert(getLangOpts().CPlusPlus && "No class names in C!");
01238 
01239   CXXRecordDecl *CurDecl;
01240   if (SS && SS->isSet() && !SS->isInvalid()) {
01241     DeclContext *DC = computeDeclContext(*SS, true);
01242     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
01243   } else
01244     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
01245 
01246   if (CurDecl && CurDecl->getIdentifier())
01247     return &II == CurDecl->getIdentifier();
01248   return false;
01249 }
01250 
01251 /// \brief Determine whether the identifier II is a typo for the name of
01252 /// the class type currently being defined. If so, update it to the identifier
01253 /// that should have been used.
01254 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
01255   assert(getLangOpts().CPlusPlus && "No class names in C!");
01256 
01257   if (!getLangOpts().SpellChecking)
01258     return false;
01259 
01260   CXXRecordDecl *CurDecl;
01261   if (SS && SS->isSet() && !SS->isInvalid()) {
01262     DeclContext *DC = computeDeclContext(*SS, true);
01263     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
01264   } else
01265     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
01266 
01267   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
01268       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
01269           < II->getLength()) {
01270     II = CurDecl->getIdentifier();
01271     return true;
01272   }
01273 
01274   return false;
01275 }
01276 
01277 /// \brief Determine whether the given class is a base class of the given
01278 /// class, including looking at dependent bases.
01279 static bool findCircularInheritance(const CXXRecordDecl *Class,
01280                                     const CXXRecordDecl *Current) {
01281   SmallVector<const CXXRecordDecl*, 8> Queue;
01282 
01283   Class = Class->getCanonicalDecl();
01284   while (true) {
01285     for (const auto &I : Current->bases()) {
01286       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
01287       if (!Base)
01288         continue;
01289 
01290       Base = Base->getDefinition();
01291       if (!Base)
01292         continue;
01293 
01294       if (Base->getCanonicalDecl() == Class)
01295         return true;
01296 
01297       Queue.push_back(Base);
01298     }
01299 
01300     if (Queue.empty())
01301       return false;
01302 
01303     Current = Queue.pop_back_val();
01304   }
01305 
01306   return false;
01307 }
01308 
01309 /// \brief Perform propagation of DLL attributes from a derived class to a
01310 /// templated base class for MS compatibility.
01311 static void propagateDLLAttrToBaseClassTemplate(
01312     Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
01313     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
01314   if (getDLLAttr(
01315           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
01316     // If the base class template has a DLL attribute, don't try to change it.
01317     return;
01318   }
01319 
01320   if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
01321     // If the base class is not already specialized, we can do the propagation.
01322     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
01323     NewAttr->setInherited(true);
01324     BaseTemplateSpec->addAttr(NewAttr);
01325     return;
01326   }
01327 
01328   bool DifferentAttribute = false;
01329   if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
01330     if (!SpecializationAttr->isInherited()) {
01331       // The template has previously been specialized or instantiated with an
01332       // explicit attribute. We should not try to change it.
01333       return;
01334     }
01335     if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
01336       // The specialization already has the right attribute.
01337       return;
01338     }
01339     DifferentAttribute = true;
01340   }
01341 
01342   // The template was previously instantiated or explicitly specialized without
01343   // a dll attribute, or the template was previously instantiated with a
01344   // different inherited attribute. It's too late for us to change the
01345   // attribute, so warn that this is unsupported.
01346   S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
01347       << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
01348   S.Diag(ClassAttr->getLocation(), diag::note_attribute);
01349   if (BaseTemplateSpec->isExplicitSpecialization()) {
01350     S.Diag(BaseTemplateSpec->getLocation(),
01351            diag::note_template_class_explicit_specialization_was_here)
01352         << BaseTemplateSpec;
01353   } else {
01354     S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
01355            diag::note_template_class_instantiation_was_here)
01356         << BaseTemplateSpec;
01357   }
01358 }
01359 
01360 /// \brief Check the validity of a C++ base class specifier.
01361 ///
01362 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
01363 /// and returns NULL otherwise.
01364 CXXBaseSpecifier *
01365 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
01366                          SourceRange SpecifierRange,
01367                          bool Virtual, AccessSpecifier Access,
01368                          TypeSourceInfo *TInfo,
01369                          SourceLocation EllipsisLoc) {
01370   QualType BaseType = TInfo->getType();
01371 
01372   // C++ [class.union]p1:
01373   //   A union shall not have base classes.
01374   if (Class->isUnion()) {
01375     Diag(Class->getLocation(), diag::err_base_clause_on_union)
01376       << SpecifierRange;
01377     return nullptr;
01378   }
01379 
01380   if (EllipsisLoc.isValid() && 
01381       !TInfo->getType()->containsUnexpandedParameterPack()) {
01382     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
01383       << TInfo->getTypeLoc().getSourceRange();
01384     EllipsisLoc = SourceLocation();
01385   }
01386 
01387   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
01388 
01389   if (BaseType->isDependentType()) {
01390     // Make sure that we don't have circular inheritance among our dependent
01391     // bases. For non-dependent bases, the check for completeness below handles
01392     // this.
01393     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
01394       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
01395           ((BaseDecl = BaseDecl->getDefinition()) &&
01396            findCircularInheritance(Class, BaseDecl))) {
01397         Diag(BaseLoc, diag::err_circular_inheritance)
01398           << BaseType << Context.getTypeDeclType(Class);
01399 
01400         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
01401           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
01402             << BaseType;
01403 
01404         return nullptr;
01405       }
01406     }
01407 
01408     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
01409                                           Class->getTagKind() == TTK_Class,
01410                                           Access, TInfo, EllipsisLoc);
01411   }
01412 
01413   // Base specifiers must be record types.
01414   if (!BaseType->isRecordType()) {
01415     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
01416     return nullptr;
01417   }
01418 
01419   // C++ [class.union]p1:
01420   //   A union shall not be used as a base class.
01421   if (BaseType->isUnionType()) {
01422     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
01423     return nullptr;
01424   }
01425 
01426   // For the MS ABI, propagate DLL attributes to base class templates.
01427   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
01428     if (Attr *ClassAttr = getDLLAttr(Class)) {
01429       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
01430               BaseType->getAsCXXRecordDecl())) {
01431         propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
01432                                             BaseTemplate, BaseLoc);
01433       }
01434     }
01435   }
01436 
01437   // C++ [class.derived]p2:
01438   //   The class-name in a base-specifier shall not be an incompletely
01439   //   defined class.
01440   if (RequireCompleteType(BaseLoc, BaseType,
01441                           diag::err_incomplete_base_class, SpecifierRange)) {
01442     Class->setInvalidDecl();
01443     return nullptr;
01444   }
01445 
01446   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
01447   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
01448   assert(BaseDecl && "Record type has no declaration");
01449   BaseDecl = BaseDecl->getDefinition();
01450   assert(BaseDecl && "Base type is not incomplete, but has no definition");
01451   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
01452   assert(CXXBaseDecl && "Base type is not a C++ type");
01453 
01454   // A class which contains a flexible array member is not suitable for use as a
01455   // base class:
01456   //   - If the layout determines that a base comes before another base,
01457   //     the flexible array member would index into the subsequent base.
01458   //   - If the layout determines that base comes before the derived class,
01459   //     the flexible array member would index into the derived class.
01460   if (CXXBaseDecl->hasFlexibleArrayMember()) {
01461     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
01462       << CXXBaseDecl->getDeclName();
01463     return nullptr;
01464   }
01465 
01466   // C++ [class]p3:
01467   //   If a class is marked final and it appears as a base-type-specifier in
01468   //   base-clause, the program is ill-formed.
01469   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
01470     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
01471       << CXXBaseDecl->getDeclName()
01472       << FA->isSpelledAsSealed();
01473     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
01474         << CXXBaseDecl->getDeclName() << FA->getRange();
01475     return nullptr;
01476   }
01477 
01478   if (BaseDecl->isInvalidDecl())
01479     Class->setInvalidDecl();
01480 
01481   // Create the base specifier.
01482   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
01483                                         Class->getTagKind() == TTK_Class,
01484                                         Access, TInfo, EllipsisLoc);
01485 }
01486 
01487 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
01488 /// one entry in the base class list of a class specifier, for
01489 /// example:
01490 ///    class foo : public bar, virtual private baz {
01491 /// 'public bar' and 'virtual private baz' are each base-specifiers.
01492 BaseResult
01493 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
01494                          ParsedAttributes &Attributes,
01495                          bool Virtual, AccessSpecifier Access,
01496                          ParsedType basetype, SourceLocation BaseLoc,
01497                          SourceLocation EllipsisLoc) {
01498   if (!classdecl)
01499     return true;
01500 
01501   AdjustDeclIfTemplate(classdecl);
01502   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
01503   if (!Class)
01504     return true;
01505 
01506   // We haven't yet attached the base specifiers.
01507   Class->setIsParsingBaseSpecifiers();
01508 
01509   // We do not support any C++11 attributes on base-specifiers yet.
01510   // Diagnose any attributes we see.
01511   if (!Attributes.empty()) {
01512     for (AttributeList *Attr = Attributes.getList(); Attr;
01513          Attr = Attr->getNext()) {
01514       if (Attr->isInvalid() ||
01515           Attr->getKind() == AttributeList::IgnoredAttribute)
01516         continue;
01517       Diag(Attr->getLoc(),
01518            Attr->getKind() == AttributeList::UnknownAttribute
01519              ? diag::warn_unknown_attribute_ignored
01520              : diag::err_base_specifier_attribute)
01521         << Attr->getName();
01522     }
01523   }
01524 
01525   TypeSourceInfo *TInfo = nullptr;
01526   GetTypeFromParser(basetype, &TInfo);
01527 
01528   if (EllipsisLoc.isInvalid() &&
01529       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 
01530                                       UPPC_BaseType))
01531     return true;
01532   
01533   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
01534                                                       Virtual, Access, TInfo,
01535                                                       EllipsisLoc))
01536     return BaseSpec;
01537   else
01538     Class->setInvalidDecl();
01539 
01540   return true;
01541 }
01542 
01543 /// \brief Performs the actual work of attaching the given base class
01544 /// specifiers to a C++ class.
01545 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
01546                                 unsigned NumBases) {
01547  if (NumBases == 0)
01548     return false;
01549 
01550   // Used to keep track of which base types we have already seen, so
01551   // that we can properly diagnose redundant direct base types. Note
01552   // that the key is always the unqualified canonical type of the base
01553   // class.
01554   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
01555 
01556   // Copy non-redundant base specifiers into permanent storage.
01557   unsigned NumGoodBases = 0;
01558   bool Invalid = false;
01559   for (unsigned idx = 0; idx < NumBases; ++idx) {
01560     QualType NewBaseType
01561       = Context.getCanonicalType(Bases[idx]->getType());
01562     NewBaseType = NewBaseType.getLocalUnqualifiedType();
01563 
01564     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
01565     if (KnownBase) {
01566       // C++ [class.mi]p3:
01567       //   A class shall not be specified as a direct base class of a
01568       //   derived class more than once.
01569       Diag(Bases[idx]->getLocStart(),
01570            diag::err_duplicate_base_class)
01571         << KnownBase->getType()
01572         << Bases[idx]->getSourceRange();
01573 
01574       // Delete the duplicate base class specifier; we're going to
01575       // overwrite its pointer later.
01576       Context.Deallocate(Bases[idx]);
01577 
01578       Invalid = true;
01579     } else {
01580       // Okay, add this new base class.
01581       KnownBase = Bases[idx];
01582       Bases[NumGoodBases++] = Bases[idx];
01583       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
01584         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
01585         if (Class->isInterface() &&
01586               (!RD->isInterface() ||
01587                KnownBase->getAccessSpecifier() != AS_public)) {
01588           // The Microsoft extension __interface does not permit bases that
01589           // are not themselves public interfaces.
01590           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
01591             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
01592             << RD->getSourceRange();
01593           Invalid = true;
01594         }
01595         if (RD->hasAttr<WeakAttr>())
01596           Class->addAttr(WeakAttr::CreateImplicit(Context));
01597       }
01598     }
01599   }
01600 
01601   // Attach the remaining base class specifiers to the derived class.
01602   Class->setBases(Bases, NumGoodBases);
01603 
01604   // Delete the remaining (good) base class specifiers, since their
01605   // data has been copied into the CXXRecordDecl.
01606   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
01607     Context.Deallocate(Bases[idx]);
01608 
01609   return Invalid;
01610 }
01611 
01612 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
01613 /// class, after checking whether there are any duplicate base
01614 /// classes.
01615 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
01616                                unsigned NumBases) {
01617   if (!ClassDecl || !Bases || !NumBases)
01618     return;
01619 
01620   AdjustDeclIfTemplate(ClassDecl);
01621   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
01622 }
01623 
01624 /// \brief Determine whether the type \p Derived is a C++ class that is
01625 /// derived from the type \p Base.
01626 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
01627   if (!getLangOpts().CPlusPlus)
01628     return false;
01629   
01630   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
01631   if (!DerivedRD)
01632     return false;
01633   
01634   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
01635   if (!BaseRD)
01636     return false;
01637 
01638   // If either the base or the derived type is invalid, don't try to
01639   // check whether one is derived from the other.
01640   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
01641     return false;
01642 
01643   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
01644   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
01645 }
01646 
01647 /// \brief Determine whether the type \p Derived is a C++ class that is
01648 /// derived from the type \p Base.
01649 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
01650   if (!getLangOpts().CPlusPlus)
01651     return false;
01652   
01653   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
01654   if (!DerivedRD)
01655     return false;
01656   
01657   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
01658   if (!BaseRD)
01659     return false;
01660   
01661   return DerivedRD->isDerivedFrom(BaseRD, Paths);
01662 }
01663 
01664 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 
01665                               CXXCastPath &BasePathArray) {
01666   assert(BasePathArray.empty() && "Base path array must be empty!");
01667   assert(Paths.isRecordingPaths() && "Must record paths!");
01668   
01669   const CXXBasePath &Path = Paths.front();
01670        
01671   // We first go backward and check if we have a virtual base.
01672   // FIXME: It would be better if CXXBasePath had the base specifier for
01673   // the nearest virtual base.
01674   unsigned Start = 0;
01675   for (unsigned I = Path.size(); I != 0; --I) {
01676     if (Path[I - 1].Base->isVirtual()) {
01677       Start = I - 1;
01678       break;
01679     }
01680   }
01681 
01682   // Now add all bases.
01683   for (unsigned I = Start, E = Path.size(); I != E; ++I)
01684     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
01685 }
01686 
01687 /// \brief Determine whether the given base path includes a virtual
01688 /// base class.
01689 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
01690   for (CXXCastPath::const_iterator B = BasePath.begin(), 
01691                                 BEnd = BasePath.end();
01692        B != BEnd; ++B)
01693     if ((*B)->isVirtual())
01694       return true;
01695 
01696   return false;
01697 }
01698 
01699 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
01700 /// conversion (where Derived and Base are class types) is
01701 /// well-formed, meaning that the conversion is unambiguous (and
01702 /// that all of the base classes are accessible). Returns true
01703 /// and emits a diagnostic if the code is ill-formed, returns false
01704 /// otherwise. Loc is the location where this routine should point to
01705 /// if there is an error, and Range is the source range to highlight
01706 /// if there is an error.
01707 bool
01708 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
01709                                    unsigned InaccessibleBaseID,
01710                                    unsigned AmbigiousBaseConvID,
01711                                    SourceLocation Loc, SourceRange Range,
01712                                    DeclarationName Name,
01713                                    CXXCastPath *BasePath) {
01714   // First, determine whether the path from Derived to Base is
01715   // ambiguous. This is slightly more expensive than checking whether
01716   // the Derived to Base conversion exists, because here we need to
01717   // explore multiple paths to determine if there is an ambiguity.
01718   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
01719                      /*DetectVirtual=*/false);
01720   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
01721   assert(DerivationOkay &&
01722          "Can only be used with a derived-to-base conversion");
01723   (void)DerivationOkay;
01724   
01725   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
01726     if (InaccessibleBaseID) {
01727       // Check that the base class can be accessed.
01728       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
01729                                    InaccessibleBaseID)) {
01730         case AR_inaccessible: 
01731           return true;
01732         case AR_accessible: 
01733         case AR_dependent:
01734         case AR_delayed:
01735           break;
01736       }
01737     }
01738     
01739     // Build a base path if necessary.
01740     if (BasePath)
01741       BuildBasePathArray(Paths, *BasePath);
01742     return false;
01743   }
01744   
01745   if (AmbigiousBaseConvID) {
01746     // We know that the derived-to-base conversion is ambiguous, and
01747     // we're going to produce a diagnostic. Perform the derived-to-base
01748     // search just one more time to compute all of the possible paths so
01749     // that we can print them out. This is more expensive than any of
01750     // the previous derived-to-base checks we've done, but at this point
01751     // performance isn't as much of an issue.
01752     Paths.clear();
01753     Paths.setRecordingPaths(true);
01754     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
01755     assert(StillOkay && "Can only be used with a derived-to-base conversion");
01756     (void)StillOkay;
01757 
01758     // Build up a textual representation of the ambiguous paths, e.g.,
01759     // D -> B -> A, that will be used to illustrate the ambiguous
01760     // conversions in the diagnostic. We only print one of the paths
01761     // to each base class subobject.
01762     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
01763 
01764     Diag(Loc, AmbigiousBaseConvID)
01765     << Derived << Base << PathDisplayStr << Range << Name;
01766   }
01767   return true;
01768 }
01769 
01770 bool
01771 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
01772                                    SourceLocation Loc, SourceRange Range,
01773                                    CXXCastPath *BasePath,
01774                                    bool IgnoreAccess) {
01775   return CheckDerivedToBaseConversion(Derived, Base,
01776                                       IgnoreAccess ? 0
01777                                        : diag::err_upcast_to_inaccessible_base,
01778                                       diag::err_ambiguous_derived_to_base_conv,
01779                                       Loc, Range, DeclarationName(), 
01780                                       BasePath);
01781 }
01782 
01783 
01784 /// @brief Builds a string representing ambiguous paths from a
01785 /// specific derived class to different subobjects of the same base
01786 /// class.
01787 ///
01788 /// This function builds a string that can be used in error messages
01789 /// to show the different paths that one can take through the
01790 /// inheritance hierarchy to go from the derived class to different
01791 /// subobjects of a base class. The result looks something like this:
01792 /// @code
01793 /// struct D -> struct B -> struct A
01794 /// struct D -> struct C -> struct A
01795 /// @endcode
01796 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
01797   std::string PathDisplayStr;
01798   std::set<unsigned> DisplayedPaths;
01799   for (CXXBasePaths::paths_iterator Path = Paths.begin();
01800        Path != Paths.end(); ++Path) {
01801     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
01802       // We haven't displayed a path to this particular base
01803       // class subobject yet.
01804       PathDisplayStr += "\n    ";
01805       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
01806       for (CXXBasePath::const_iterator Element = Path->begin();
01807            Element != Path->end(); ++Element)
01808         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
01809     }
01810   }
01811   
01812   return PathDisplayStr;
01813 }
01814 
01815 //===----------------------------------------------------------------------===//
01816 // C++ class member Handling
01817 //===----------------------------------------------------------------------===//
01818 
01819 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
01820 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
01821                                 SourceLocation ASLoc,
01822                                 SourceLocation ColonLoc,
01823                                 AttributeList *Attrs) {
01824   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
01825   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
01826                                                   ASLoc, ColonLoc);
01827   CurContext->addHiddenDecl(ASDecl);
01828   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
01829 }
01830 
01831 /// CheckOverrideControl - Check C++11 override control semantics.
01832 void Sema::CheckOverrideControl(NamedDecl *D) {
01833   if (D->isInvalidDecl())
01834     return;
01835 
01836   // We only care about "override" and "final" declarations.
01837   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
01838     return;
01839 
01840   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
01841 
01842   // We can't check dependent instance methods.
01843   if (MD && MD->isInstance() &&
01844       (MD->getParent()->hasAnyDependentBases() ||
01845        MD->getType()->isDependentType()))
01846     return;
01847 
01848   if (MD && !MD->isVirtual()) {
01849     // If we have a non-virtual method, check if if hides a virtual method.
01850     // (In that case, it's most likely the method has the wrong type.)
01851     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
01852     FindHiddenVirtualMethods(MD, OverloadedMethods);
01853 
01854     if (!OverloadedMethods.empty()) {
01855       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
01856         Diag(OA->getLocation(),
01857              diag::override_keyword_hides_virtual_member_function)
01858           << "override" << (OverloadedMethods.size() > 1);
01859       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
01860         Diag(FA->getLocation(),
01861              diag::override_keyword_hides_virtual_member_function)
01862           << (FA->isSpelledAsSealed() ? "sealed" : "final")
01863           << (OverloadedMethods.size() > 1);
01864       }
01865       NoteHiddenVirtualMethods(MD, OverloadedMethods);
01866       MD->setInvalidDecl();
01867       return;
01868     }
01869     // Fall through into the general case diagnostic.
01870     // FIXME: We might want to attempt typo correction here.
01871   }
01872 
01873   if (!MD || !MD->isVirtual()) {
01874     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
01875       Diag(OA->getLocation(),
01876            diag::override_keyword_only_allowed_on_virtual_member_functions)
01877         << "override" << FixItHint::CreateRemoval(OA->getLocation());
01878       D->dropAttr<OverrideAttr>();
01879     }
01880     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
01881       Diag(FA->getLocation(),
01882            diag::override_keyword_only_allowed_on_virtual_member_functions)
01883         << (FA->isSpelledAsSealed() ? "sealed" : "final")
01884         << FixItHint::CreateRemoval(FA->getLocation());
01885       D->dropAttr<FinalAttr>();
01886     }
01887     return;
01888   }
01889 
01890   // C++11 [class.virtual]p5:
01891   //   If a function is marked with the virt-specifier override and
01892   //   does not override a member function of a base class, the program is
01893   //   ill-formed.
01894   bool HasOverriddenMethods =
01895     MD->begin_overridden_methods() != MD->end_overridden_methods();
01896   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
01897     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
01898       << MD->getDeclName();
01899 }
01900 
01901 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
01902   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
01903     return;
01904   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
01905   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
01906       isa<CXXDestructorDecl>(MD))
01907     return;
01908 
01909   SourceLocation Loc = MD->getLocation();
01910   SourceLocation SpellingLoc = Loc;
01911   if (getSourceManager().isMacroArgExpansion(Loc))
01912     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
01913   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
01914   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
01915       return;
01916     
01917   if (MD->size_overridden_methods() > 0) {
01918     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
01919       << MD->getDeclName();
01920     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
01921     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
01922   }
01923 }
01924 
01925 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
01926 /// function overrides a virtual member function marked 'final', according to
01927 /// C++11 [class.virtual]p4.
01928 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
01929                                                   const CXXMethodDecl *Old) {
01930   FinalAttr *FA = Old->getAttr<FinalAttr>();
01931   if (!FA)
01932     return false;
01933 
01934   Diag(New->getLocation(), diag::err_final_function_overridden)
01935     << New->getDeclName()
01936     << FA->isSpelledAsSealed();
01937   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
01938   return true;
01939 }
01940 
01941 static bool InitializationHasSideEffects(const FieldDecl &FD) {
01942   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
01943   // FIXME: Destruction of ObjC lifetime types has side-effects.
01944   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
01945     return !RD->isCompleteDefinition() ||
01946            !RD->hasTrivialDefaultConstructor() ||
01947            !RD->hasTrivialDestructor();
01948   return false;
01949 }
01950 
01951 static AttributeList *getMSPropertyAttr(AttributeList *list) {
01952   for (AttributeList *it = list; it != nullptr; it = it->getNext())
01953     if (it->isDeclspecPropertyAttribute())
01954       return it;
01955   return nullptr;
01956 }
01957 
01958 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
01959 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
01960 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
01961 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
01962 /// present (but parsing it has been deferred).
01963 NamedDecl *
01964 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
01965                                MultiTemplateParamsArg TemplateParameterLists,
01966                                Expr *BW, const VirtSpecifiers &VS,
01967                                InClassInitStyle InitStyle) {
01968   const DeclSpec &DS = D.getDeclSpec();
01969   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
01970   DeclarationName Name = NameInfo.getName();
01971   SourceLocation Loc = NameInfo.getLoc();
01972 
01973   // For anonymous bitfields, the location should point to the type.
01974   if (Loc.isInvalid())
01975     Loc = D.getLocStart();
01976 
01977   Expr *BitWidth = static_cast<Expr*>(BW);
01978 
01979   assert(isa<CXXRecordDecl>(CurContext));
01980   assert(!DS.isFriendSpecified());
01981 
01982   bool isFunc = D.isDeclarationOfFunction();
01983 
01984   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
01985     // The Microsoft extension __interface only permits public member functions
01986     // and prohibits constructors, destructors, operators, non-public member
01987     // functions, static methods and data members.
01988     unsigned InvalidDecl;
01989     bool ShowDeclName = true;
01990     if (!isFunc)
01991       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
01992     else if (AS != AS_public)
01993       InvalidDecl = 2;
01994     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
01995       InvalidDecl = 3;
01996     else switch (Name.getNameKind()) {
01997       case DeclarationName::CXXConstructorName:
01998         InvalidDecl = 4;
01999         ShowDeclName = false;
02000         break;
02001 
02002       case DeclarationName::CXXDestructorName:
02003         InvalidDecl = 5;
02004         ShowDeclName = false;
02005         break;
02006 
02007       case DeclarationName::CXXOperatorName:
02008       case DeclarationName::CXXConversionFunctionName:
02009         InvalidDecl = 6;
02010         break;
02011 
02012       default:
02013         InvalidDecl = 0;
02014         break;
02015     }
02016 
02017     if (InvalidDecl) {
02018       if (ShowDeclName)
02019         Diag(Loc, diag::err_invalid_member_in_interface)
02020           << (InvalidDecl-1) << Name;
02021       else
02022         Diag(Loc, diag::err_invalid_member_in_interface)
02023           << (InvalidDecl-1) << "";
02024       return nullptr;
02025     }
02026   }
02027 
02028   // C++ 9.2p6: A member shall not be declared to have automatic storage
02029   // duration (auto, register) or with the extern storage-class-specifier.
02030   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
02031   // data members and cannot be applied to names declared const or static,
02032   // and cannot be applied to reference members.
02033   switch (DS.getStorageClassSpec()) {
02034   case DeclSpec::SCS_unspecified:
02035   case DeclSpec::SCS_typedef:
02036   case DeclSpec::SCS_static:
02037     break;
02038   case DeclSpec::SCS_mutable:
02039     if (isFunc) {
02040       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
02041 
02042       // FIXME: It would be nicer if the keyword was ignored only for this
02043       // declarator. Otherwise we could get follow-up errors.
02044       D.getMutableDeclSpec().ClearStorageClassSpecs();
02045     }
02046     break;
02047   default:
02048     Diag(DS.getStorageClassSpecLoc(),
02049          diag::err_storageclass_invalid_for_member);
02050     D.getMutableDeclSpec().ClearStorageClassSpecs();
02051     break;
02052   }
02053 
02054   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
02055                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
02056                       !isFunc);
02057 
02058   if (DS.isConstexprSpecified() && isInstField) {
02059     SemaDiagnosticBuilder B =
02060         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
02061     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
02062     if (InitStyle == ICIS_NoInit) {
02063       B << 0 << 0;
02064       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
02065         B << FixItHint::CreateRemoval(ConstexprLoc);
02066       else {
02067         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
02068         D.getMutableDeclSpec().ClearConstexprSpec();
02069         const char *PrevSpec;
02070         unsigned DiagID;
02071         bool Failed = D.getMutableDeclSpec().SetTypeQual(
02072             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
02073         (void)Failed;
02074         assert(!Failed && "Making a constexpr member const shouldn't fail");
02075       }
02076     } else {
02077       B << 1;
02078       const char *PrevSpec;
02079       unsigned DiagID;
02080       if (D.getMutableDeclSpec().SetStorageClassSpec(
02081           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
02082           Context.getPrintingPolicy())) {
02083         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
02084                "This is the only DeclSpec that should fail to be applied");
02085         B << 1;
02086       } else {
02087         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
02088         isInstField = false;
02089       }
02090     }
02091   }
02092 
02093   NamedDecl *Member;
02094   if (isInstField) {
02095     CXXScopeSpec &SS = D.getCXXScopeSpec();
02096 
02097     // Data members must have identifiers for names.
02098     if (!Name.isIdentifier()) {
02099       Diag(Loc, diag::err_bad_variable_name)
02100         << Name;
02101       return nullptr;
02102     }
02103 
02104     IdentifierInfo *II = Name.getAsIdentifierInfo();
02105 
02106     // Member field could not be with "template" keyword.
02107     // So TemplateParameterLists should be empty in this case.
02108     if (TemplateParameterLists.size()) {
02109       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
02110       if (TemplateParams->size()) {
02111         // There is no such thing as a member field template.
02112         Diag(D.getIdentifierLoc(), diag::err_template_member)
02113             << II
02114             << SourceRange(TemplateParams->getTemplateLoc(),
02115                 TemplateParams->getRAngleLoc());
02116       } else {
02117         // There is an extraneous 'template<>' for this member.
02118         Diag(TemplateParams->getTemplateLoc(),
02119             diag::err_template_member_noparams)
02120             << II
02121             << SourceRange(TemplateParams->getTemplateLoc(),
02122                 TemplateParams->getRAngleLoc());
02123       }
02124       return nullptr;
02125     }
02126 
02127     if (SS.isSet() && !SS.isInvalid()) {
02128       // The user provided a superfluous scope specifier inside a class
02129       // definition:
02130       //
02131       // class X {
02132       //   int X::member;
02133       // };
02134       if (DeclContext *DC = computeDeclContext(SS, false))
02135         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
02136       else
02137         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
02138           << Name << SS.getRange();
02139       
02140       SS.clear();
02141     }
02142 
02143     AttributeList *MSPropertyAttr =
02144       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
02145     if (MSPropertyAttr) {
02146       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
02147                                 BitWidth, InitStyle, AS, MSPropertyAttr);
02148       if (!Member)
02149         return nullptr;
02150       isInstField = false;
02151     } else {
02152       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
02153                                 BitWidth, InitStyle, AS);
02154       assert(Member && "HandleField never returns null");
02155     }
02156   } else {
02157     assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
02158 
02159     Member = HandleDeclarator(S, D, TemplateParameterLists);
02160     if (!Member)
02161       return nullptr;
02162 
02163     // Non-instance-fields can't have a bitfield.
02164     if (BitWidth) {
02165       if (Member->isInvalidDecl()) {
02166         // don't emit another diagnostic.
02167       } else if (isa<VarDecl>(Member)) {
02168         // C++ 9.6p3: A bit-field shall not be a static member.
02169         // "static member 'A' cannot be a bit-field"
02170         Diag(Loc, diag::err_static_not_bitfield)
02171           << Name << BitWidth->getSourceRange();
02172       } else if (isa<TypedefDecl>(Member)) {
02173         // "typedef member 'x' cannot be a bit-field"
02174         Diag(Loc, diag::err_typedef_not_bitfield)
02175           << Name << BitWidth->getSourceRange();
02176       } else {
02177         // A function typedef ("typedef int f(); f a;").
02178         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
02179         Diag(Loc, diag::err_not_integral_type_bitfield)
02180           << Name << cast<ValueDecl>(Member)->getType()
02181           << BitWidth->getSourceRange();
02182       }
02183 
02184       BitWidth = nullptr;
02185       Member->setInvalidDecl();
02186     }
02187 
02188     Member->setAccess(AS);
02189 
02190     // If we have declared a member function template or static data member
02191     // template, set the access of the templated declaration as well.
02192     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
02193       FunTmpl->getTemplatedDecl()->setAccess(AS);
02194     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
02195       VarTmpl->getTemplatedDecl()->setAccess(AS);
02196   }
02197 
02198   if (VS.isOverrideSpecified())
02199     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
02200   if (VS.isFinalSpecified())
02201     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
02202                                             VS.isFinalSpelledSealed()));
02203 
02204   if (VS.getLastLocation().isValid()) {
02205     // Update the end location of a method that has a virt-specifiers.
02206     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
02207       MD->setRangeEnd(VS.getLastLocation());
02208   }
02209 
02210   CheckOverrideControl(Member);
02211 
02212   assert((Name || isInstField) && "No identifier for non-field ?");
02213 
02214   if (isInstField) {
02215     FieldDecl *FD = cast<FieldDecl>(Member);
02216     FieldCollector->Add(FD);
02217 
02218     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
02219       // Remember all explicit private FieldDecls that have a name, no side
02220       // effects and are not part of a dependent type declaration.
02221       if (!FD->isImplicit() && FD->getDeclName() &&
02222           FD->getAccess() == AS_private &&
02223           !FD->hasAttr<UnusedAttr>() &&
02224           !FD->getParent()->isDependentContext() &&
02225           !InitializationHasSideEffects(*FD))
02226         UnusedPrivateFields.insert(FD);
02227     }
02228   }
02229 
02230   return Member;
02231 }
02232 
02233 namespace {
02234   class UninitializedFieldVisitor
02235       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
02236     Sema &S;
02237     // List of Decls to generate a warning on.  Also remove Decls that become
02238     // initialized.
02239     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
02240     // Vector of decls to be removed from the Decl set prior to visiting the
02241     // nodes.  These Decls may have been initialized in the prior initializer.
02242     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
02243     // If non-null, add a note to the warning pointing back to the constructor.
02244     const CXXConstructorDecl *Constructor;
02245     // Variables to hold state when processing an initializer list.  When
02246     // InitList is true, special case initialization of FieldDecls matching
02247     // InitListFieldDecl.
02248     bool InitList;
02249     FieldDecl *InitListFieldDecl;
02250     llvm::SmallVector<unsigned, 4> InitFieldIndex;
02251 
02252   public:
02253     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
02254     UninitializedFieldVisitor(Sema &S,
02255                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
02256       : Inherited(S.Context), S(S), Decls(Decls), Constructor(nullptr),
02257         InitList(false), InitListFieldDecl(nullptr) {}
02258 
02259     // Returns true if the use of ME is not an uninitialized use.
02260     bool IsInitListMemberExprInitialized(MemberExpr *ME,
02261                                          bool CheckReferenceOnly) {
02262       llvm::SmallVector<FieldDecl*, 4> Fields;
02263       bool ReferenceField = false;
02264       while (ME) {
02265         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
02266         if (!FD)
02267           return false;
02268         Fields.push_back(FD);
02269         if (FD->getType()->isReferenceType())
02270           ReferenceField = true;
02271         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
02272       }
02273 
02274       // Binding a reference to an unintialized field is not an
02275       // uninitialized use.
02276       if (CheckReferenceOnly && !ReferenceField)
02277         return true;
02278 
02279       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
02280       // Discard the first field since it is the field decl that is being
02281       // initialized.
02282       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
02283         UsedFieldIndex.push_back((*I)->getFieldIndex());
02284       }
02285 
02286       for (auto UsedIter = UsedFieldIndex.begin(),
02287                 UsedEnd = UsedFieldIndex.end(),
02288                 OrigIter = InitFieldIndex.begin(),
02289                 OrigEnd = InitFieldIndex.end();
02290            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
02291         if (*UsedIter < *OrigIter)
02292           return true;
02293         if (*UsedIter > *OrigIter)
02294           break;
02295       }
02296 
02297       return false;
02298     }
02299 
02300     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
02301                           bool AddressOf) {
02302       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
02303         return;
02304 
02305       // FieldME is the inner-most MemberExpr that is not an anonymous struct
02306       // or union.
02307       MemberExpr *FieldME = ME;
02308 
02309       bool AllPODFields = FieldME->getType().isPODType(S.Context);
02310 
02311       Expr *Base = ME;
02312       while (MemberExpr *SubME = dyn_cast<MemberExpr>(Base)) {
02313 
02314         if (isa<VarDecl>(SubME->getMemberDecl()))
02315           return;
02316 
02317         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
02318           if (!FD->isAnonymousStructOrUnion())
02319             FieldME = SubME;
02320 
02321         if (!FieldME->getType().isPODType(S.Context))
02322           AllPODFields = false;
02323 
02324         Base = SubME->getBase()->IgnoreParenImpCasts();
02325       }
02326 
02327       if (!isa<CXXThisExpr>(Base))
02328         return;
02329 
02330       if (AddressOf && AllPODFields)
02331         return;
02332 
02333       ValueDecl* FoundVD = FieldME->getMemberDecl();
02334 
02335       if (!Decls.count(FoundVD))
02336         return;
02337 
02338       const bool IsReference = FoundVD->getType()->isReferenceType();
02339 
02340       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
02341         // Special checking for initializer lists.
02342         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
02343           return;
02344         }
02345       } else {
02346         // Prevent double warnings on use of unbounded references.
02347         if (CheckReferenceOnly && !IsReference)
02348           return;
02349       }
02350 
02351       unsigned diag = IsReference
02352           ? diag::warn_reference_field_is_uninit
02353           : diag::warn_field_is_uninit;
02354       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
02355       if (Constructor)
02356         S.Diag(Constructor->getLocation(),
02357                diag::note_uninit_in_this_constructor)
02358           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
02359 
02360     }
02361 
02362     void HandleValue(Expr *E, bool AddressOf) {
02363       E = E->IgnoreParens();
02364 
02365       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
02366         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
02367                          AddressOf /*AddressOf*/);
02368         return;
02369       }
02370 
02371       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
02372         Visit(CO->getCond());
02373         HandleValue(CO->getTrueExpr(), AddressOf);
02374         HandleValue(CO->getFalseExpr(), AddressOf);
02375         return;
02376       }
02377 
02378       if (BinaryConditionalOperator *BCO =
02379               dyn_cast<BinaryConditionalOperator>(E)) {
02380         Visit(BCO->getCond());
02381         HandleValue(BCO->getFalseExpr(), AddressOf);
02382         return;
02383       }
02384 
02385       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
02386         HandleValue(OVE->getSourceExpr(), AddressOf);
02387         return;
02388       }
02389 
02390       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
02391         switch (BO->getOpcode()) {
02392         default:
02393           break;
02394         case(BO_PtrMemD):
02395         case(BO_PtrMemI):
02396           HandleValue(BO->getLHS(), AddressOf);
02397           Visit(BO->getRHS());
02398           return;
02399         case(BO_Comma):
02400           Visit(BO->getLHS());
02401           HandleValue(BO->getRHS(), AddressOf);
02402           return;
02403         }
02404       }
02405 
02406       Visit(E);
02407     }
02408 
02409     void CheckInitListExpr(InitListExpr *ILE) {
02410       InitFieldIndex.push_back(0);
02411       for (auto Child : ILE->children()) {
02412         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
02413           CheckInitListExpr(SubList);
02414         } else {
02415           Visit(Child);
02416         }
02417         ++InitFieldIndex.back();
02418       }
02419       InitFieldIndex.pop_back();
02420     }
02421 
02422     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
02423                           FieldDecl *Field) {
02424       // Remove Decls that may have been initialized in the previous
02425       // initializer.
02426       for (ValueDecl* VD : DeclsToRemove)
02427         Decls.erase(VD);
02428       DeclsToRemove.clear();
02429 
02430       Constructor = FieldConstructor;
02431       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
02432 
02433       if (ILE && Field) {
02434         InitList = true;
02435         InitListFieldDecl = Field;
02436         InitFieldIndex.clear();
02437         CheckInitListExpr(ILE);
02438       } else {
02439         InitList = false;
02440         Visit(E);
02441       }
02442 
02443       if (Field)
02444         Decls.erase(Field);
02445     }
02446 
02447     void VisitMemberExpr(MemberExpr *ME) {
02448       // All uses of unbounded reference fields will warn.
02449       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
02450     }
02451 
02452     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
02453       if (E->getCastKind() == CK_LValueToRValue) {
02454         HandleValue(E->getSubExpr(), false /*AddressOf*/);
02455         return;
02456       }
02457 
02458       Inherited::VisitImplicitCastExpr(E);
02459     }
02460 
02461     void VisitCXXConstructExpr(CXXConstructExpr *E) {
02462       if (E->getConstructor()->isCopyConstructor()) {
02463         Expr *ArgExpr = E->getArg(0);
02464         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
02465           if (ILE->getNumInits() == 1)
02466             ArgExpr = ILE->getInit(0);
02467         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
02468           if (ICE->getCastKind() == CK_NoOp)
02469             ArgExpr = ICE->getSubExpr();
02470         HandleValue(ArgExpr, false /*AddressOf*/);
02471         return;
02472       }
02473       Inherited::VisitCXXConstructExpr(E);
02474     }
02475 
02476     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
02477       Expr *Callee = E->getCallee();
02478       if (isa<MemberExpr>(Callee)) {
02479         HandleValue(Callee, false /*AddressOf*/);
02480         for (auto Arg : E->arguments())
02481           Visit(Arg);
02482         return;
02483       }
02484 
02485       Inherited::VisitCXXMemberCallExpr(E);
02486     }
02487 
02488     void VisitCallExpr(CallExpr *E) {
02489       // Treat std::move as a use.
02490       if (E->getNumArgs() == 1) {
02491         if (FunctionDecl *FD = E->getDirectCallee()) {
02492           if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
02493             HandleValue(E->getArg(0), false /*AddressOf*/);
02494             return;
02495           }
02496         }
02497       }
02498 
02499       Inherited::VisitCallExpr(E);
02500     }
02501 
02502     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
02503       Expr *Callee = E->getCallee();
02504 
02505       if (isa<UnresolvedLookupExpr>(Callee))
02506         return Inherited::VisitCXXOperatorCallExpr(E);
02507 
02508       Visit(Callee);
02509       for (auto Arg : E->arguments())
02510         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
02511     }
02512 
02513     void VisitBinaryOperator(BinaryOperator *E) {
02514       // If a field assignment is detected, remove the field from the
02515       // uninitiailized field set.
02516       if (E->getOpcode() == BO_Assign)
02517         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
02518           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
02519             if (!FD->getType()->isReferenceType())
02520               DeclsToRemove.push_back(FD);
02521 
02522       if (E->isCompoundAssignmentOp()) {
02523         HandleValue(E->getLHS(), false /*AddressOf*/);
02524         Visit(E->getRHS());
02525         return;
02526       }
02527 
02528       Inherited::VisitBinaryOperator(E);
02529     }
02530 
02531     void VisitUnaryOperator(UnaryOperator *E) {
02532       if (E->isIncrementDecrementOp()) {
02533         HandleValue(E->getSubExpr(), false /*AddressOf*/);
02534         return;
02535       }
02536       if (E->getOpcode() == UO_AddrOf) {
02537         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
02538           HandleValue(ME->getBase(), true /*AddressOf*/);
02539           return;
02540         }
02541       }
02542 
02543       Inherited::VisitUnaryOperator(E);
02544     }
02545   };
02546 
02547   // Diagnose value-uses of fields to initialize themselves, e.g.
02548   //   foo(foo)
02549   // where foo is not also a parameter to the constructor.
02550   // Also diagnose across field uninitialized use such as
02551   //   x(y), y(x)
02552   // TODO: implement -Wuninitialized and fold this into that framework.
02553   static void DiagnoseUninitializedFields(
02554       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
02555 
02556     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
02557                                            Constructor->getLocation())) {
02558       return;
02559     }
02560 
02561     if (Constructor->isInvalidDecl())
02562       return;
02563 
02564     const CXXRecordDecl *RD = Constructor->getParent();
02565 
02566     if (RD->getDescribedClassTemplate())
02567       return;
02568 
02569     // Holds fields that are uninitialized.
02570     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
02571 
02572     // At the beginning, all fields are uninitialized.
02573     for (auto *I : RD->decls()) {
02574       if (auto *FD = dyn_cast<FieldDecl>(I)) {
02575         UninitializedFields.insert(FD);
02576       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
02577         UninitializedFields.insert(IFD->getAnonField());
02578       }
02579     }
02580 
02581     if (UninitializedFields.empty())
02582       return;
02583 
02584     UninitializedFieldVisitor UninitializedChecker(SemaRef,
02585                                                    UninitializedFields);
02586 
02587     for (const auto *FieldInit : Constructor->inits()) {
02588       if (UninitializedFields.empty())
02589         break;
02590 
02591       Expr *InitExpr = FieldInit->getInit();
02592       if (!InitExpr)
02593         continue;
02594 
02595       if (CXXDefaultInitExpr *Default =
02596               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
02597         InitExpr = Default->getExpr();
02598         if (!InitExpr)
02599           continue;
02600         // In class initializers will point to the constructor.
02601         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
02602                                               FieldInit->getAnyMember());
02603       } else {
02604         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
02605                                               FieldInit->getAnyMember());
02606       }
02607     }
02608   }
02609 } // namespace
02610 
02611 /// \brief Enter a new C++ default initializer scope. After calling this, the
02612 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
02613 /// parsing or instantiating the initializer failed.
02614 void Sema::ActOnStartCXXInClassMemberInitializer() {
02615   // Create a synthetic function scope to represent the call to the constructor
02616   // that notionally surrounds a use of this initializer.
02617   PushFunctionScope();
02618 }
02619 
02620 /// \brief This is invoked after parsing an in-class initializer for a
02621 /// non-static C++ class member, and after instantiating an in-class initializer
02622 /// in a class template. Such actions are deferred until the class is complete.
02623 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
02624                                                   SourceLocation InitLoc,
02625                                                   Expr *InitExpr) {
02626   // Pop the notional constructor scope we created earlier.
02627   PopFunctionScopeInfo(nullptr, D);
02628 
02629   FieldDecl *FD = cast<FieldDecl>(D);
02630   assert(FD->getInClassInitStyle() != ICIS_NoInit &&
02631          "must set init style when field is created");
02632 
02633   if (!InitExpr) {
02634     FD->setInvalidDecl();
02635     FD->removeInClassInitializer();
02636     return;
02637   }
02638 
02639   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
02640     FD->setInvalidDecl();
02641     FD->removeInClassInitializer();
02642     return;
02643   }
02644 
02645   ExprResult Init = InitExpr;
02646   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
02647     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
02648     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
02649         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
02650         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
02651     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
02652     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
02653     if (Init.isInvalid()) {
02654       FD->setInvalidDecl();
02655       return;
02656     }
02657   }
02658 
02659   // C++11 [class.base.init]p7:
02660   //   The initialization of each base and member constitutes a
02661   //   full-expression.
02662   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
02663   if (Init.isInvalid()) {
02664     FD->setInvalidDecl();
02665     return;
02666   }
02667 
02668   InitExpr = Init.get();
02669 
02670   FD->setInClassInitializer(InitExpr);
02671 }
02672 
02673 /// \brief Find the direct and/or virtual base specifiers that
02674 /// correspond to the given base type, for use in base initialization
02675 /// within a constructor.
02676 static bool FindBaseInitializer(Sema &SemaRef, 
02677                                 CXXRecordDecl *ClassDecl,
02678                                 QualType BaseType,
02679                                 const CXXBaseSpecifier *&DirectBaseSpec,
02680                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
02681   // First, check for a direct base class.
02682   DirectBaseSpec = nullptr;
02683   for (const auto &Base : ClassDecl->bases()) {
02684     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
02685       // We found a direct base of this type. That's what we're
02686       // initializing.
02687       DirectBaseSpec = &Base;
02688       break;
02689     }
02690   }
02691 
02692   // Check for a virtual base class.
02693   // FIXME: We might be able to short-circuit this if we know in advance that
02694   // there are no virtual bases.
02695   VirtualBaseSpec = nullptr;
02696   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
02697     // We haven't found a base yet; search the class hierarchy for a
02698     // virtual base class.
02699     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
02700                        /*DetectVirtual=*/false);
02701     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl), 
02702                               BaseType, Paths)) {
02703       for (CXXBasePaths::paths_iterator Path = Paths.begin();
02704            Path != Paths.end(); ++Path) {
02705         if (Path->back().Base->isVirtual()) {
02706           VirtualBaseSpec = Path->back().Base;
02707           break;
02708         }
02709       }
02710     }
02711   }
02712 
02713   return DirectBaseSpec || VirtualBaseSpec;
02714 }
02715 
02716 /// \brief Handle a C++ member initializer using braced-init-list syntax.
02717 MemInitResult
02718 Sema::ActOnMemInitializer(Decl *ConstructorD,
02719                           Scope *S,
02720                           CXXScopeSpec &SS,
02721                           IdentifierInfo *MemberOrBase,
02722                           ParsedType TemplateTypeTy,
02723                           const DeclSpec &DS,
02724                           SourceLocation IdLoc,
02725                           Expr *InitList,
02726                           SourceLocation EllipsisLoc) {
02727   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
02728                              DS, IdLoc, InitList,
02729                              EllipsisLoc);
02730 }
02731 
02732 /// \brief Handle a C++ member initializer using parentheses syntax.
02733 MemInitResult
02734 Sema::ActOnMemInitializer(Decl *ConstructorD,
02735                           Scope *S,
02736                           CXXScopeSpec &SS,
02737                           IdentifierInfo *MemberOrBase,
02738                           ParsedType TemplateTypeTy,
02739                           const DeclSpec &DS,
02740                           SourceLocation IdLoc,
02741                           SourceLocation LParenLoc,
02742                           ArrayRef<Expr *> Args,
02743                           SourceLocation RParenLoc,
02744                           SourceLocation EllipsisLoc) {
02745   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
02746                                            Args, RParenLoc);
02747   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
02748                              DS, IdLoc, List, EllipsisLoc);
02749 }
02750 
02751 namespace {
02752 
02753 // Callback to only accept typo corrections that can be a valid C++ member
02754 // intializer: either a non-static field member or a base class.
02755 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
02756 public:
02757   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
02758       : ClassDecl(ClassDecl) {}
02759 
02760   bool ValidateCandidate(const TypoCorrection &candidate) override {
02761     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
02762       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
02763         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
02764       return isa<TypeDecl>(ND);
02765     }
02766     return false;
02767   }
02768 
02769 private:
02770   CXXRecordDecl *ClassDecl;
02771 };
02772 
02773 }
02774 
02775 /// \brief Handle a C++ member initializer.
02776 MemInitResult
02777 Sema::BuildMemInitializer(Decl *ConstructorD,
02778                           Scope *S,
02779                           CXXScopeSpec &SS,
02780                           IdentifierInfo *MemberOrBase,
02781                           ParsedType TemplateTypeTy,
02782                           const DeclSpec &DS,
02783                           SourceLocation IdLoc,
02784                           Expr *Init,
02785                           SourceLocation EllipsisLoc) {
02786   if (!ConstructorD)
02787     return true;
02788 
02789   AdjustDeclIfTemplate(ConstructorD);
02790 
02791   CXXConstructorDecl *Constructor
02792     = dyn_cast<CXXConstructorDecl>(ConstructorD);
02793   if (!Constructor) {
02794     // The user wrote a constructor initializer on a function that is
02795     // not a C++ constructor. Ignore the error for now, because we may
02796     // have more member initializers coming; we'll diagnose it just
02797     // once in ActOnMemInitializers.
02798     return true;
02799   }
02800 
02801   CXXRecordDecl *ClassDecl = Constructor->getParent();
02802 
02803   // C++ [class.base.init]p2:
02804   //   Names in a mem-initializer-id are looked up in the scope of the
02805   //   constructor's class and, if not found in that scope, are looked
02806   //   up in the scope containing the constructor's definition.
02807   //   [Note: if the constructor's class contains a member with the
02808   //   same name as a direct or virtual base class of the class, a
02809   //   mem-initializer-id naming the member or base class and composed
02810   //   of a single identifier refers to the class member. A
02811   //   mem-initializer-id for the hidden base class may be specified
02812   //   using a qualified name. ]
02813   if (!SS.getScopeRep() && !TemplateTypeTy) {
02814     // Look for a member, first.
02815     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
02816     if (!Result.empty()) {
02817       ValueDecl *Member;
02818       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
02819           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
02820         if (EllipsisLoc.isValid())
02821           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
02822             << MemberOrBase
02823             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
02824 
02825         return BuildMemberInitializer(Member, Init, IdLoc);
02826       }
02827     }
02828   }
02829   // It didn't name a member, so see if it names a class.
02830   QualType BaseType;
02831   TypeSourceInfo *TInfo = nullptr;
02832 
02833   if (TemplateTypeTy) {
02834     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
02835   } else if (DS.getTypeSpecType() == TST_decltype) {
02836     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
02837   } else {
02838     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
02839     LookupParsedName(R, S, &SS);
02840 
02841     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
02842     if (!TyD) {
02843       if (R.isAmbiguous()) return true;
02844 
02845       // We don't want access-control diagnostics here.
02846       R.suppressDiagnostics();
02847 
02848       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
02849         bool NotUnknownSpecialization = false;
02850         DeclContext *DC = computeDeclContext(SS, false);
02851         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 
02852           NotUnknownSpecialization = !Record->hasAnyDependentBases();
02853 
02854         if (!NotUnknownSpecialization) {
02855           // When the scope specifier can refer to a member of an unknown
02856           // specialization, we take it as a type name.
02857           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
02858                                        SS.getWithLocInContext(Context),
02859                                        *MemberOrBase, IdLoc);
02860           if (BaseType.isNull())
02861             return true;
02862 
02863           R.clear();
02864           R.setLookupName(MemberOrBase);
02865         }
02866       }
02867 
02868       // If no results were found, try to correct typos.
02869       TypoCorrection Corr;
02870       if (R.empty() && BaseType.isNull() &&
02871           (Corr = CorrectTypo(
02872                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
02873                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
02874                CTK_ErrorRecovery, ClassDecl))) {
02875         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
02876           // We have found a non-static data member with a similar
02877           // name to what was typed; complain and initialize that
02878           // member.
02879           diagnoseTypo(Corr,
02880                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
02881                          << MemberOrBase << true);
02882           return BuildMemberInitializer(Member, Init, IdLoc);
02883         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
02884           const CXXBaseSpecifier *DirectBaseSpec;
02885           const CXXBaseSpecifier *VirtualBaseSpec;
02886           if (FindBaseInitializer(*this, ClassDecl, 
02887                                   Context.getTypeDeclType(Type),
02888                                   DirectBaseSpec, VirtualBaseSpec)) {
02889             // We have found a direct or virtual base class with a
02890             // similar name to what was typed; complain and initialize
02891             // that base class.
02892             diagnoseTypo(Corr,
02893                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
02894                            << MemberOrBase << false,
02895                          PDiag() /*Suppress note, we provide our own.*/);
02896 
02897             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
02898                                                               : VirtualBaseSpec;
02899             Diag(BaseSpec->getLocStart(),
02900                  diag::note_base_class_specified_here)
02901               << BaseSpec->getType()
02902               << BaseSpec->getSourceRange();
02903 
02904             TyD = Type;
02905           }
02906         }
02907       }
02908 
02909       if (!TyD && BaseType.isNull()) {
02910         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
02911           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
02912         return true;
02913       }
02914     }
02915 
02916     if (BaseType.isNull()) {
02917       BaseType = Context.getTypeDeclType(TyD);
02918       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
02919       if (SS.isSet())
02920         // FIXME: preserve source range information
02921         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
02922                                              BaseType);
02923     }
02924   }
02925 
02926   if (!TInfo)
02927     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
02928 
02929   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
02930 }
02931 
02932 /// Checks a member initializer expression for cases where reference (or
02933 /// pointer) members are bound to by-value parameters (or their addresses).
02934 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
02935                                                Expr *Init,
02936                                                SourceLocation IdLoc) {
02937   QualType MemberTy = Member->getType();
02938 
02939   // We only handle pointers and references currently.
02940   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
02941   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
02942     return;
02943 
02944   const bool IsPointer = MemberTy->isPointerType();
02945   if (IsPointer) {
02946     if (const UnaryOperator *Op
02947           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
02948       // The only case we're worried about with pointers requires taking the
02949       // address.
02950       if (Op->getOpcode() != UO_AddrOf)
02951         return;
02952 
02953       Init = Op->getSubExpr();
02954     } else {
02955       // We only handle address-of expression initializers for pointers.
02956       return;
02957     }
02958   }
02959 
02960   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
02961     // We only warn when referring to a non-reference parameter declaration.
02962     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
02963     if (!Parameter || Parameter->getType()->isReferenceType())
02964       return;
02965 
02966     S.Diag(Init->getExprLoc(),
02967            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
02968                      : diag::warn_bind_ref_member_to_parameter)
02969       << Member << Parameter << Init->getSourceRange();
02970   } else {
02971     // Other initializers are fine.
02972     return;
02973   }
02974 
02975   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
02976     << (unsigned)IsPointer;
02977 }
02978 
02979 MemInitResult
02980 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
02981                              SourceLocation IdLoc) {
02982   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
02983   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
02984   assert((DirectMember || IndirectMember) &&
02985          "Member must be a FieldDecl or IndirectFieldDecl");
02986 
02987   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
02988     return true;
02989 
02990   if (Member->isInvalidDecl())
02991     return true;
02992 
02993   MultiExprArg Args;
02994   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
02995     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
02996   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
02997     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
02998   } else {
02999     // Template instantiation doesn't reconstruct ParenListExprs for us.
03000     Args = Init;
03001   }
03002 
03003   SourceRange InitRange = Init->getSourceRange();
03004 
03005   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
03006     // Can't check initialization for a member of dependent type or when
03007     // any of the arguments are type-dependent expressions.
03008     DiscardCleanupsInEvaluationContext();
03009   } else {
03010     bool InitList = false;
03011     if (isa<InitListExpr>(Init)) {
03012       InitList = true;
03013       Args = Init;
03014     }
03015 
03016     // Initialize the member.
03017     InitializedEntity MemberEntity =
03018       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
03019                    : InitializedEntity::InitializeMember(IndirectMember,
03020                                                          nullptr);
03021     InitializationKind Kind =
03022       InitList ? InitializationKind::CreateDirectList(IdLoc)
03023                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
03024                                                   InitRange.getEnd());
03025 
03026     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
03027     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
03028                                             nullptr);
03029     if (MemberInit.isInvalid())
03030       return true;
03031 
03032     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
03033 
03034     // C++11 [class.base.init]p7:
03035     //   The initialization of each base and member constitutes a
03036     //   full-expression.
03037     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
03038     if (MemberInit.isInvalid())
03039       return true;
03040 
03041     Init = MemberInit.get();
03042   }
03043 
03044   if (DirectMember) {
03045     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
03046                                             InitRange.getBegin(), Init,
03047                                             InitRange.getEnd());
03048   } else {
03049     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
03050                                             InitRange.getBegin(), Init,
03051                                             InitRange.getEnd());
03052   }
03053 }
03054 
03055 MemInitResult
03056 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
03057                                  CXXRecordDecl *ClassDecl) {
03058   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
03059   if (!LangOpts.CPlusPlus11)
03060     return Diag(NameLoc, diag::err_delegating_ctor)
03061       << TInfo->getTypeLoc().getLocalSourceRange();
03062   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
03063 
03064   bool InitList = true;
03065   MultiExprArg Args = Init;
03066   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
03067     InitList = false;
03068     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
03069   }
03070 
03071   SourceRange InitRange = Init->getSourceRange();
03072   // Initialize the object.
03073   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
03074                                      QualType(ClassDecl->getTypeForDecl(), 0));
03075   InitializationKind Kind =
03076     InitList ? InitializationKind::CreateDirectList(NameLoc)
03077              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
03078                                                 InitRange.getEnd());
03079   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
03080   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
03081                                               Args, nullptr);
03082   if (DelegationInit.isInvalid())
03083     return true;
03084 
03085   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
03086          "Delegating constructor with no target?");
03087 
03088   // C++11 [class.base.init]p7:
03089   //   The initialization of each base and member constitutes a
03090   //   full-expression.
03091   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
03092                                        InitRange.getBegin());
03093   if (DelegationInit.isInvalid())
03094     return true;
03095 
03096   // If we are in a dependent context, template instantiation will
03097   // perform this type-checking again. Just save the arguments that we
03098   // received in a ParenListExpr.
03099   // FIXME: This isn't quite ideal, since our ASTs don't capture all
03100   // of the information that we have about the base
03101   // initializer. However, deconstructing the ASTs is a dicey process,
03102   // and this approach is far more likely to get the corner cases right.
03103   if (CurContext->isDependentContext())
03104     DelegationInit = Init;
03105 
03106   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 
03107                                           DelegationInit.getAs<Expr>(),
03108                                           InitRange.getEnd());
03109 }
03110 
03111 MemInitResult
03112 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
03113                            Expr *Init, CXXRecordDecl *ClassDecl,
03114                            SourceLocation EllipsisLoc) {
03115   SourceLocation BaseLoc
03116     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
03117 
03118   if (!BaseType->isDependentType() && !BaseType->isRecordType())
03119     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
03120              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
03121 
03122   // C++ [class.base.init]p2:
03123   //   [...] Unless the mem-initializer-id names a nonstatic data
03124   //   member of the constructor's class or a direct or virtual base
03125   //   of that class, the mem-initializer is ill-formed. A
03126   //   mem-initializer-list can initialize a base class using any
03127   //   name that denotes that base class type.
03128   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
03129 
03130   SourceRange InitRange = Init->getSourceRange();
03131   if (EllipsisLoc.isValid()) {
03132     // This is a pack expansion.
03133     if (!BaseType->containsUnexpandedParameterPack())  {
03134       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
03135         << SourceRange(BaseLoc, InitRange.getEnd());
03136 
03137       EllipsisLoc = SourceLocation();
03138     }
03139   } else {
03140     // Check for any unexpanded parameter packs.
03141     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
03142       return true;
03143 
03144     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
03145       return true;
03146   }
03147 
03148   // Check for direct and virtual base classes.
03149   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
03150   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
03151   if (!Dependent) { 
03152     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
03153                                        BaseType))
03154       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
03155 
03156     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 
03157                         VirtualBaseSpec);
03158 
03159     // C++ [base.class.init]p2:
03160     // Unless the mem-initializer-id names a nonstatic data member of the
03161     // constructor's class or a direct or virtual base of that class, the
03162     // mem-initializer is ill-formed.
03163     if (!DirectBaseSpec && !VirtualBaseSpec) {
03164       // If the class has any dependent bases, then it's possible that
03165       // one of those types will resolve to the same type as
03166       // BaseType. Therefore, just treat this as a dependent base
03167       // class initialization.  FIXME: Should we try to check the
03168       // initialization anyway? It seems odd.
03169       if (ClassDecl->hasAnyDependentBases())
03170         Dependent = true;
03171       else
03172         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
03173           << BaseType << Context.getTypeDeclType(ClassDecl)
03174           << BaseTInfo->getTypeLoc().getLocalSourceRange();
03175     }
03176   }
03177 
03178   if (Dependent) {
03179     DiscardCleanupsInEvaluationContext();
03180 
03181     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
03182                                             /*IsVirtual=*/false,
03183                                             InitRange.getBegin(), Init,
03184                                             InitRange.getEnd(), EllipsisLoc);
03185   }
03186 
03187   // C++ [base.class.init]p2:
03188   //   If a mem-initializer-id is ambiguous because it designates both
03189   //   a direct non-virtual base class and an inherited virtual base
03190   //   class, the mem-initializer is ill-formed.
03191   if (DirectBaseSpec && VirtualBaseSpec)
03192     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
03193       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
03194 
03195   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
03196   if (!BaseSpec)
03197     BaseSpec = VirtualBaseSpec;
03198 
03199   // Initialize the base.
03200   bool InitList = true;
03201   MultiExprArg Args = Init;
03202   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
03203     InitList = false;
03204     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
03205   }
03206 
03207   InitializedEntity BaseEntity =
03208     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
03209   InitializationKind Kind =
03210     InitList ? InitializationKind::CreateDirectList(BaseLoc)
03211              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
03212                                                 InitRange.getEnd());
03213   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
03214   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
03215   if (BaseInit.isInvalid())
03216     return true;
03217 
03218   // C++11 [class.base.init]p7:
03219   //   The initialization of each base and member constitutes a
03220   //   full-expression.
03221   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
03222   if (BaseInit.isInvalid())
03223     return true;
03224 
03225   // If we are in a dependent context, template instantiation will
03226   // perform this type-checking again. Just save the arguments that we
03227   // received in a ParenListExpr.
03228   // FIXME: This isn't quite ideal, since our ASTs don't capture all
03229   // of the information that we have about the base
03230   // initializer. However, deconstructing the ASTs is a dicey process,
03231   // and this approach is far more likely to get the corner cases right.
03232   if (CurContext->isDependentContext())
03233     BaseInit = Init;
03234 
03235   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
03236                                           BaseSpec->isVirtual(),
03237                                           InitRange.getBegin(),
03238                                           BaseInit.getAs<Expr>(),
03239                                           InitRange.getEnd(), EllipsisLoc);
03240 }
03241 
03242 // Create a static_cast<T&&>(expr).
03243 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
03244   if (T.isNull()) T = E->getType();
03245   QualType TargetType = SemaRef.BuildReferenceType(
03246       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
03247   SourceLocation ExprLoc = E->getLocStart();
03248   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
03249       TargetType, ExprLoc);
03250 
03251   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
03252                                    SourceRange(ExprLoc, ExprLoc),
03253                                    E->getSourceRange()).get();
03254 }
03255 
03256 /// ImplicitInitializerKind - How an implicit base or member initializer should
03257 /// initialize its base or member.
03258 enum ImplicitInitializerKind {
03259   IIK_Default,
03260   IIK_Copy,
03261   IIK_Move,
03262   IIK_Inherit
03263 };
03264 
03265 static bool
03266 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
03267                              ImplicitInitializerKind ImplicitInitKind,
03268                              CXXBaseSpecifier *BaseSpec,
03269                              bool IsInheritedVirtualBase,
03270                              CXXCtorInitializer *&CXXBaseInit) {
03271   InitializedEntity InitEntity
03272     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
03273                                         IsInheritedVirtualBase);
03274 
03275   ExprResult BaseInit;
03276   
03277   switch (ImplicitInitKind) {
03278   case IIK_Inherit: {
03279     const CXXRecordDecl *Inherited =
03280         Constructor->getInheritedConstructor()->getParent();
03281     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
03282     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
03283       // C++11 [class.inhctor]p8:
03284       //   Each expression in the expression-list is of the form
03285       //   static_cast<T&&>(p), where p is the name of the corresponding
03286       //   constructor parameter and T is the declared type of p.
03287       SmallVector<Expr*, 16> Args;
03288       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
03289         ParmVarDecl *PD = Constructor->getParamDecl(I);
03290         ExprResult ArgExpr =
03291             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
03292                                      VK_LValue, SourceLocation());
03293         if (ArgExpr.isInvalid())
03294           return true;
03295         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
03296       }
03297 
03298       InitializationKind InitKind = InitializationKind::CreateDirect(
03299           Constructor->getLocation(), SourceLocation(), SourceLocation());
03300       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
03301       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
03302       break;
03303     }
03304   }
03305   // Fall through.
03306   case IIK_Default: {
03307     InitializationKind InitKind
03308       = InitializationKind::CreateDefault(Constructor->getLocation());
03309     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
03310     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
03311     break;
03312   }
03313 
03314   case IIK_Move:
03315   case IIK_Copy: {
03316     bool Moving = ImplicitInitKind == IIK_Move;
03317     ParmVarDecl *Param = Constructor->getParamDecl(0);
03318     QualType ParamType = Param->getType().getNonReferenceType();
03319 
03320     Expr *CopyCtorArg = 
03321       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
03322                           SourceLocation(), Param, false,
03323                           Constructor->getLocation(), ParamType,
03324                           VK_LValue, nullptr);
03325 
03326     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
03327 
03328     // Cast to the base class to avoid ambiguities.
03329     QualType ArgTy = 
03330       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 
03331                                        ParamType.getQualifiers());
03332 
03333     if (Moving) {
03334       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
03335     }
03336 
03337     CXXCastPath BasePath;
03338     BasePath.push_back(BaseSpec);
03339     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
03340                                             CK_UncheckedDerivedToBase,
03341                                             Moving ? VK_XValue : VK_LValue,
03342                                             &BasePath).get();
03343 
03344     InitializationKind InitKind
03345       = InitializationKind::CreateDirect(Constructor->getLocation(),
03346                                          SourceLocation(), SourceLocation());
03347     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
03348     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
03349     break;
03350   }
03351   }
03352 
03353   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
03354   if (BaseInit.isInvalid())
03355     return true;
03356         
03357   CXXBaseInit =
03358     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
03359                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 
03360                                                         SourceLocation()),
03361                                              BaseSpec->isVirtual(),
03362                                              SourceLocation(),
03363                                              BaseInit.getAs<Expr>(),
03364                                              SourceLocation(),
03365                                              SourceLocation());
03366 
03367   return false;
03368 }
03369 
03370 static bool RefersToRValueRef(Expr *MemRef) {
03371   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
03372   return Referenced->getType()->isRValueReferenceType();
03373 }
03374 
03375 static bool
03376 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
03377                                ImplicitInitializerKind ImplicitInitKind,
03378                                FieldDecl *Field, IndirectFieldDecl *Indirect,
03379                                CXXCtorInitializer *&CXXMemberInit) {
03380   if (Field->isInvalidDecl())
03381     return true;
03382 
03383   SourceLocation Loc = Constructor->getLocation();
03384 
03385   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
03386     bool Moving = ImplicitInitKind == IIK_Move;
03387     ParmVarDecl *Param = Constructor->getParamDecl(0);
03388     QualType ParamType = Param->getType().getNonReferenceType();
03389 
03390     // Suppress copying zero-width bitfields.
03391     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
03392       return false;
03393         
03394     Expr *MemberExprBase = 
03395       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
03396                           SourceLocation(), Param, false,
03397                           Loc, ParamType, VK_LValue, nullptr);
03398 
03399     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
03400 
03401     if (Moving) {
03402       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
03403     }
03404 
03405     // Build a reference to this field within the parameter.
03406     CXXScopeSpec SS;
03407     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
03408                               Sema::LookupMemberName);
03409     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
03410                                   : cast<ValueDecl>(Field), AS_public);
03411     MemberLookup.resolveKind();
03412     ExprResult CtorArg 
03413       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
03414                                          ParamType, Loc,
03415                                          /*IsArrow=*/false,
03416                                          SS,
03417                                          /*TemplateKWLoc=*/SourceLocation(),
03418                                          /*FirstQualifierInScope=*/nullptr,
03419                                          MemberLookup,
03420                                          /*TemplateArgs=*/nullptr);
03421     if (CtorArg.isInvalid())
03422       return true;
03423 
03424     // C++11 [class.copy]p15:
03425     //   - if a member m has rvalue reference type T&&, it is direct-initialized
03426     //     with static_cast<T&&>(x.m);
03427     if (RefersToRValueRef(CtorArg.get())) {
03428       CtorArg = CastForMoving(SemaRef, CtorArg.get());
03429     }
03430 
03431     // When the field we are copying is an array, create index variables for 
03432     // each dimension of the array. We use these index variables to subscript
03433     // the source array, and other clients (e.g., CodeGen) will perform the
03434     // necessary iteration with these index variables.
03435     SmallVector<VarDecl *, 4> IndexVariables;
03436     QualType BaseType = Field->getType();
03437     QualType SizeType = SemaRef.Context.getSizeType();
03438     bool InitializingArray = false;
03439     while (const ConstantArrayType *Array
03440                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
03441       InitializingArray = true;
03442       // Create the iteration variable for this array index.
03443       IdentifierInfo *IterationVarName = nullptr;
03444       {
03445         SmallString<8> Str;
03446         llvm::raw_svector_ostream OS(Str);
03447         OS << "__i" << IndexVariables.size();
03448         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
03449       }
03450       VarDecl *IterationVar
03451         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
03452                           IterationVarName, SizeType,
03453                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
03454                           SC_None);
03455       IndexVariables.push_back(IterationVar);
03456       
03457       // Create a reference to the iteration variable.
03458       ExprResult IterationVarRef
03459         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
03460       assert(!IterationVarRef.isInvalid() &&
03461              "Reference to invented variable cannot fail!");
03462       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
03463       assert(!IterationVarRef.isInvalid() &&
03464              "Conversion of invented variable cannot fail!");
03465 
03466       // Subscript the array with this iteration variable.
03467       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
03468                                                         IterationVarRef.get(),
03469                                                         Loc);
03470       if (CtorArg.isInvalid())
03471         return true;
03472 
03473       BaseType = Array->getElementType();
03474     }
03475 
03476     // The array subscript expression is an lvalue, which is wrong for moving.
03477     if (Moving && InitializingArray)
03478       CtorArg = CastForMoving(SemaRef, CtorArg.get());
03479 
03480     // Construct the entity that we will be initializing. For an array, this
03481     // will be first element in the array, which may require several levels
03482     // of array-subscript entities. 
03483     SmallVector<InitializedEntity, 4> Entities;
03484     Entities.reserve(1 + IndexVariables.size());
03485     if (Indirect)
03486       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
03487     else
03488       Entities.push_back(InitializedEntity::InitializeMember(Field));
03489     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
03490       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
03491                                                               0,
03492                                                               Entities.back()));
03493     
03494     // Direct-initialize to use the copy constructor.
03495     InitializationKind InitKind =
03496       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
03497     
03498     Expr *CtorArgE = CtorArg.getAs<Expr>();
03499     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
03500     
03501     ExprResult MemberInit
03502       = InitSeq.Perform(SemaRef, Entities.back(), InitKind, 
03503                         MultiExprArg(&CtorArgE, 1));
03504     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
03505     if (MemberInit.isInvalid())
03506       return true;
03507 
03508     if (Indirect) {
03509       assert(IndexVariables.size() == 0 && 
03510              "Indirect field improperly initialized");
03511       CXXMemberInit
03512         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect, 
03513                                                    Loc, Loc, 
03514                                                    MemberInit.getAs<Expr>(), 
03515                                                    Loc);
03516     } else
03517       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, 
03518                                                  Loc, MemberInit.getAs<Expr>(), 
03519                                                  Loc,
03520                                                  IndexVariables.data(),
03521                                                  IndexVariables.size());
03522     return false;
03523   }
03524 
03525   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
03526          "Unhandled implicit init kind!");
03527 
03528   QualType FieldBaseElementType = 
03529     SemaRef.Context.getBaseElementType(Field->getType());
03530   
03531   if (FieldBaseElementType->isRecordType()) {
03532     InitializedEntity InitEntity 
03533       = Indirect? InitializedEntity::InitializeMember(Indirect)
03534                 : InitializedEntity::InitializeMember(Field);
03535     InitializationKind InitKind = 
03536       InitializationKind::CreateDefault(Loc);
03537 
03538     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
03539     ExprResult MemberInit =
03540       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
03541 
03542     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
03543     if (MemberInit.isInvalid())
03544       return true;
03545     
03546     if (Indirect)
03547       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
03548                                                                Indirect, Loc, 
03549                                                                Loc,
03550                                                                MemberInit.get(),
03551                                                                Loc);
03552     else
03553       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
03554                                                                Field, Loc, Loc,
03555                                                                MemberInit.get(),
03556                                                                Loc);
03557     return false;
03558   }
03559 
03560   if (!Field->getParent()->isUnion()) {
03561     if (FieldBaseElementType->isReferenceType()) {
03562       SemaRef.Diag(Constructor->getLocation(), 
03563                    diag::err_uninitialized_member_in_ctor)
03564       << (int)Constructor->isImplicit() 
03565       << SemaRef.Context.getTagDeclType(Constructor->getParent())
03566       << 0 << Field->getDeclName();
03567       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
03568       return true;
03569     }
03570 
03571     if (FieldBaseElementType.isConstQualified()) {
03572       SemaRef.Diag(Constructor->getLocation(), 
03573                    diag::err_uninitialized_member_in_ctor)
03574       << (int)Constructor->isImplicit() 
03575       << SemaRef.Context.getTagDeclType(Constructor->getParent())
03576       << 1 << Field->getDeclName();
03577       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
03578       return true;
03579     }
03580   }
03581   
03582   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
03583       FieldBaseElementType->isObjCRetainableType() &&
03584       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
03585       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
03586     // ARC:
03587     //   Default-initialize Objective-C pointers to NULL.
03588     CXXMemberInit
03589       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 
03590                                                  Loc, Loc, 
03591                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 
03592                                                  Loc);
03593     return false;
03594   }
03595       
03596   // Nothing to initialize.
03597   CXXMemberInit = nullptr;
03598   return false;
03599 }
03600 
03601 namespace {
03602 struct BaseAndFieldInfo {
03603   Sema &S;
03604   CXXConstructorDecl *Ctor;
03605   bool AnyErrorsInInits;
03606   ImplicitInitializerKind IIK;
03607   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
03608   SmallVector<CXXCtorInitializer*, 8> AllToInit;
03609   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
03610 
03611   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
03612     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
03613     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
03614     if (Generated && Ctor->isCopyConstructor())
03615       IIK = IIK_Copy;
03616     else if (Generated && Ctor->isMoveConstructor())
03617       IIK = IIK_Move;
03618     else if (Ctor->getInheritedConstructor())
03619       IIK = IIK_Inherit;
03620     else
03621       IIK = IIK_Default;
03622   }
03623   
03624   bool isImplicitCopyOrMove() const {
03625     switch (IIK) {
03626     case IIK_Copy:
03627     case IIK_Move:
03628       return true;
03629       
03630     case IIK_Default:
03631     case IIK_Inherit:
03632       return false;
03633     }
03634 
03635     llvm_unreachable("Invalid ImplicitInitializerKind!");
03636   }
03637 
03638   bool addFieldInitializer(CXXCtorInitializer *Init) {
03639     AllToInit.push_back(Init);
03640 
03641     // Check whether this initializer makes the field "used".
03642     if (Init->getInit()->HasSideEffects(S.Context))
03643       S.UnusedPrivateFields.remove(Init->getAnyMember());
03644 
03645     return false;
03646   }
03647 
03648   bool isInactiveUnionMember(FieldDecl *Field) {
03649     RecordDecl *Record = Field->getParent();
03650     if (!Record->isUnion())
03651       return false;
03652 
03653     if (FieldDecl *Active =
03654             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
03655       return Active != Field->getCanonicalDecl();
03656 
03657     // In an implicit copy or move constructor, ignore any in-class initializer.
03658     if (isImplicitCopyOrMove())
03659       return true;
03660 
03661     // If there's no explicit initialization, the field is active only if it
03662     // has an in-class initializer...
03663     if (Field->hasInClassInitializer())
03664       return false;
03665     // ... or it's an anonymous struct or union whose class has an in-class
03666     // initializer.
03667     if (!Field->isAnonymousStructOrUnion())
03668       return true;
03669     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
03670     return !FieldRD->hasInClassInitializer();
03671   }
03672 
03673   /// \brief Determine whether the given field is, or is within, a union member
03674   /// that is inactive (because there was an initializer given for a different
03675   /// member of the union, or because the union was not initialized at all).
03676   bool isWithinInactiveUnionMember(FieldDecl *Field,
03677                                    IndirectFieldDecl *Indirect) {
03678     if (!Indirect)
03679       return isInactiveUnionMember(Field);
03680 
03681     for (auto *C : Indirect->chain()) {
03682       FieldDecl *Field = dyn_cast<FieldDecl>(C);
03683       if (Field && isInactiveUnionMember(Field))
03684         return true;
03685     }
03686     return false;
03687   }
03688 };
03689 }
03690 
03691 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
03692 /// array type.
03693 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
03694   if (T->isIncompleteArrayType())
03695     return true;
03696   
03697   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
03698     if (!ArrayT->getSize())
03699       return true;
03700     
03701     T = ArrayT->getElementType();
03702   }
03703   
03704   return false;
03705 }
03706 
03707 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
03708                                     FieldDecl *Field, 
03709                                     IndirectFieldDecl *Indirect = nullptr) {
03710   if (Field->isInvalidDecl())
03711     return false;
03712 
03713   // Overwhelmingly common case: we have a direct initializer for this field.
03714   if (CXXCtorInitializer *Init =
03715           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
03716     return Info.addFieldInitializer(Init);
03717 
03718   // C++11 [class.base.init]p8:
03719   //   if the entity is a non-static data member that has a
03720   //   brace-or-equal-initializer and either
03721   //   -- the constructor's class is a union and no other variant member of that
03722   //      union is designated by a mem-initializer-id or
03723   //   -- the constructor's class is not a union, and, if the entity is a member
03724   //      of an anonymous union, no other member of that union is designated by
03725   //      a mem-initializer-id,
03726   //   the entity is initialized as specified in [dcl.init].
03727   //
03728   // We also apply the same rules to handle anonymous structs within anonymous
03729   // unions.
03730   if (Info.isWithinInactiveUnionMember(Field, Indirect))
03731     return false;
03732 
03733   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
03734     ExprResult DIE =
03735         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
03736     if (DIE.isInvalid())
03737       return true;
03738     CXXCtorInitializer *Init;
03739     if (Indirect)
03740       Init = new (SemaRef.Context)
03741           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
03742                              SourceLocation(), DIE.get(), SourceLocation());
03743     else
03744       Init = new (SemaRef.Context)
03745           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
03746                              SourceLocation(), DIE.get(), SourceLocation());
03747     return Info.addFieldInitializer(Init);
03748   }
03749 
03750   // Don't initialize incomplete or zero-length arrays.
03751   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
03752     return false;
03753 
03754   // Don't try to build an implicit initializer if there were semantic
03755   // errors in any of the initializers (and therefore we might be
03756   // missing some that the user actually wrote).
03757   if (Info.AnyErrorsInInits)
03758     return false;
03759 
03760   CXXCtorInitializer *Init = nullptr;
03761   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
03762                                      Indirect, Init))
03763     return true;
03764 
03765   if (!Init)
03766     return false;
03767 
03768   return Info.addFieldInitializer(Init);
03769 }
03770 
03771 bool
03772 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
03773                                CXXCtorInitializer *Initializer) {
03774   assert(Initializer->isDelegatingInitializer());
03775   Constructor->setNumCtorInitializers(1);
03776   CXXCtorInitializer **initializer =
03777     new (Context) CXXCtorInitializer*[1];
03778   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
03779   Constructor->setCtorInitializers(initializer);
03780 
03781   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
03782     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
03783     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
03784   }
03785 
03786   DelegatingCtorDecls.push_back(Constructor);
03787 
03788   DiagnoseUninitializedFields(*this, Constructor);
03789 
03790   return false;
03791 }
03792 
03793 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
03794                                ArrayRef<CXXCtorInitializer *> Initializers) {
03795   if (Constructor->isDependentContext()) {
03796     // Just store the initializers as written, they will be checked during
03797     // instantiation.
03798     if (!Initializers.empty()) {
03799       Constructor->setNumCtorInitializers(Initializers.size());
03800       CXXCtorInitializer **baseOrMemberInitializers =
03801         new (Context) CXXCtorInitializer*[Initializers.size()];
03802       memcpy(baseOrMemberInitializers, Initializers.data(),
03803              Initializers.size() * sizeof(CXXCtorInitializer*));
03804       Constructor->setCtorInitializers(baseOrMemberInitializers);
03805     }
03806 
03807     // Let template instantiation know whether we had errors.
03808     if (AnyErrors)
03809       Constructor->setInvalidDecl();
03810 
03811     return false;
03812   }
03813 
03814   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
03815 
03816   // We need to build the initializer AST according to order of construction
03817   // and not what user specified in the Initializers list.
03818   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
03819   if (!ClassDecl)
03820     return true;
03821   
03822   bool HadError = false;
03823 
03824   for (unsigned i = 0; i < Initializers.size(); i++) {
03825     CXXCtorInitializer *Member = Initializers[i];
03826 
03827     if (Member->isBaseInitializer())
03828       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
03829     else {
03830       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
03831 
03832       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
03833         for (auto *C : F->chain()) {
03834           FieldDecl *FD = dyn_cast<FieldDecl>(C);
03835           if (FD && FD->getParent()->isUnion())
03836             Info.ActiveUnionMember.insert(std::make_pair(
03837                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
03838         }
03839       } else if (FieldDecl *FD = Member->getMember()) {
03840         if (FD->getParent()->isUnion())
03841           Info.ActiveUnionMember.insert(std::make_pair(
03842               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
03843       }
03844     }
03845   }
03846 
03847   // Keep track of the direct virtual bases.
03848   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
03849   for (auto &I : ClassDecl->bases()) {
03850     if (I.isVirtual())
03851       DirectVBases.insert(&I);
03852   }
03853 
03854   // Push virtual bases before others.
03855   for (auto &VBase : ClassDecl->vbases()) {
03856     if (CXXCtorInitializer *Value
03857         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
03858       // [class.base.init]p7, per DR257:
03859       //   A mem-initializer where the mem-initializer-id names a virtual base
03860       //   class is ignored during execution of a constructor of any class that
03861       //   is not the most derived class.
03862       if (ClassDecl->isAbstract()) {
03863         // FIXME: Provide a fixit to remove the base specifier. This requires
03864         // tracking the location of the associated comma for a base specifier.
03865         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
03866           << VBase.getType() << ClassDecl;
03867         DiagnoseAbstractType(ClassDecl);
03868       }
03869 
03870       Info.AllToInit.push_back(Value);
03871     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
03872       // [class.base.init]p8, per DR257:
03873       //   If a given [...] base class is not named by a mem-initializer-id
03874       //   [...] and the entity is not a virtual base class of an abstract
03875       //   class, then [...] the entity is default-initialized.
03876       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
03877       CXXCtorInitializer *CXXBaseInit;
03878       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
03879                                        &VBase, IsInheritedVirtualBase,
03880                                        CXXBaseInit)) {
03881         HadError = true;
03882         continue;
03883       }
03884 
03885       Info.AllToInit.push_back(CXXBaseInit);
03886     }
03887   }
03888 
03889   // Non-virtual bases.
03890   for (auto &Base : ClassDecl->bases()) {
03891     // Virtuals are in the virtual base list and already constructed.
03892     if (Base.isVirtual())
03893       continue;
03894 
03895     if (CXXCtorInitializer *Value
03896           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
03897       Info.AllToInit.push_back(Value);
03898     } else if (!AnyErrors) {
03899       CXXCtorInitializer *CXXBaseInit;
03900       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
03901                                        &Base, /*IsInheritedVirtualBase=*/false,
03902                                        CXXBaseInit)) {
03903         HadError = true;
03904         continue;
03905       }
03906 
03907       Info.AllToInit.push_back(CXXBaseInit);
03908     }
03909   }
03910 
03911   // Fields.
03912   for (auto *Mem : ClassDecl->decls()) {
03913     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
03914       // C++ [class.bit]p2:
03915       //   A declaration for a bit-field that omits the identifier declares an
03916       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
03917       //   initialized.
03918       if (F->isUnnamedBitfield())
03919         continue;
03920             
03921       // If we're not generating the implicit copy/move constructor, then we'll
03922       // handle anonymous struct/union fields based on their individual
03923       // indirect fields.
03924       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
03925         continue;
03926           
03927       if (CollectFieldInitializer(*this, Info, F))
03928         HadError = true;
03929       continue;
03930     }
03931     
03932     // Beyond this point, we only consider default initialization.
03933     if (Info.isImplicitCopyOrMove())
03934       continue;
03935     
03936     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
03937       if (F->getType()->isIncompleteArrayType()) {
03938         assert(ClassDecl->hasFlexibleArrayMember() &&
03939                "Incomplete array type is not valid");
03940         continue;
03941       }
03942       
03943       // Initialize each field of an anonymous struct individually.
03944       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
03945         HadError = true;
03946       
03947       continue;        
03948     }
03949   }
03950 
03951   unsigned NumInitializers = Info.AllToInit.size();
03952   if (NumInitializers > 0) {
03953     Constructor->setNumCtorInitializers(NumInitializers);
03954     CXXCtorInitializer **baseOrMemberInitializers =
03955       new (Context) CXXCtorInitializer*[NumInitializers];
03956     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
03957            NumInitializers * sizeof(CXXCtorInitializer*));
03958     Constructor->setCtorInitializers(baseOrMemberInitializers);
03959 
03960     // Constructors implicitly reference the base and member
03961     // destructors.
03962     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
03963                                            Constructor->getParent());
03964   }
03965 
03966   return HadError;
03967 }
03968 
03969 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
03970   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
03971     const RecordDecl *RD = RT->getDecl();
03972     if (RD->isAnonymousStructOrUnion()) {
03973       for (auto *Field : RD->fields())
03974         PopulateKeysForFields(Field, IdealInits);
03975       return;
03976     }
03977   }
03978   IdealInits.push_back(Field->getCanonicalDecl());
03979 }
03980 
03981 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
03982   return Context.getCanonicalType(BaseType).getTypePtr();
03983 }
03984 
03985 static const void *GetKeyForMember(ASTContext &Context,
03986                                    CXXCtorInitializer *Member) {
03987   if (!Member->isAnyMemberInitializer())
03988     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
03989     
03990   return Member->getAnyMember()->getCanonicalDecl();
03991 }
03992 
03993 static void DiagnoseBaseOrMemInitializerOrder(
03994     Sema &SemaRef, const CXXConstructorDecl *Constructor,
03995     ArrayRef<CXXCtorInitializer *> Inits) {
03996   if (Constructor->getDeclContext()->isDependentContext())
03997     return;
03998 
03999   // Don't check initializers order unless the warning is enabled at the
04000   // location of at least one initializer. 
04001   bool ShouldCheckOrder = false;
04002   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
04003     CXXCtorInitializer *Init = Inits[InitIndex];
04004     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
04005                                  Init->getSourceLocation())) {
04006       ShouldCheckOrder = true;
04007       break;
04008     }
04009   }
04010   if (!ShouldCheckOrder)
04011     return;
04012   
04013   // Build the list of bases and members in the order that they'll
04014   // actually be initialized.  The explicit initializers should be in
04015   // this same order but may be missing things.
04016   SmallVector<const void*, 32> IdealInitKeys;
04017 
04018   const CXXRecordDecl *ClassDecl = Constructor->getParent();
04019 
04020   // 1. Virtual bases.
04021   for (const auto &VBase : ClassDecl->vbases())
04022     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
04023 
04024   // 2. Non-virtual bases.
04025   for (const auto &Base : ClassDecl->bases()) {
04026     if (Base.isVirtual())
04027       continue;
04028     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
04029   }
04030 
04031   // 3. Direct fields.
04032   for (auto *Field : ClassDecl->fields()) {
04033     if (Field->isUnnamedBitfield())
04034       continue;
04035     
04036     PopulateKeysForFields(Field, IdealInitKeys);
04037   }
04038   
04039   unsigned NumIdealInits = IdealInitKeys.size();
04040   unsigned IdealIndex = 0;
04041 
04042   CXXCtorInitializer *PrevInit = nullptr;
04043   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
04044     CXXCtorInitializer *Init = Inits[InitIndex];
04045     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
04046 
04047     // Scan forward to try to find this initializer in the idealized
04048     // initializers list.
04049     for (; IdealIndex != NumIdealInits; ++IdealIndex)
04050       if (InitKey == IdealInitKeys[IdealIndex])
04051         break;
04052 
04053     // If we didn't find this initializer, it must be because we
04054     // scanned past it on a previous iteration.  That can only
04055     // happen if we're out of order;  emit a warning.
04056     if (IdealIndex == NumIdealInits && PrevInit) {
04057       Sema::SemaDiagnosticBuilder D =
04058         SemaRef.Diag(PrevInit->getSourceLocation(),
04059                      diag::warn_initializer_out_of_order);
04060 
04061       if (PrevInit->isAnyMemberInitializer())
04062         D << 0 << PrevInit->getAnyMember()->getDeclName();
04063       else
04064         D << 1 << PrevInit->getTypeSourceInfo()->getType();
04065       
04066       if (Init->isAnyMemberInitializer())
04067         D << 0 << Init->getAnyMember()->getDeclName();
04068       else
04069         D << 1 << Init->getTypeSourceInfo()->getType();
04070 
04071       // Move back to the initializer's location in the ideal list.
04072       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
04073         if (InitKey == IdealInitKeys[IdealIndex])
04074           break;
04075 
04076       assert(IdealIndex != NumIdealInits &&
04077              "initializer not found in initializer list");
04078     }
04079 
04080     PrevInit = Init;
04081   }
04082 }
04083 
04084 namespace {
04085 bool CheckRedundantInit(Sema &S,
04086                         CXXCtorInitializer *Init,
04087                         CXXCtorInitializer *&PrevInit) {
04088   if (!PrevInit) {
04089     PrevInit = Init;
04090     return false;
04091   }
04092 
04093   if (FieldDecl *Field = Init->getAnyMember())
04094     S.Diag(Init->getSourceLocation(),
04095            diag::err_multiple_mem_initialization)
04096       << Field->getDeclName()
04097       << Init->getSourceRange();
04098   else {
04099     const Type *BaseClass = Init->getBaseClass();
04100     assert(BaseClass && "neither field nor base");
04101     S.Diag(Init->getSourceLocation(),
04102            diag::err_multiple_base_initialization)
04103       << QualType(BaseClass, 0)
04104       << Init->getSourceRange();
04105   }
04106   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
04107     << 0 << PrevInit->getSourceRange();
04108 
04109   return true;
04110 }
04111 
04112 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
04113 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
04114 
04115 bool CheckRedundantUnionInit(Sema &S,
04116                              CXXCtorInitializer *Init,
04117                              RedundantUnionMap &Unions) {
04118   FieldDecl *Field = Init->getAnyMember();
04119   RecordDecl *Parent = Field->getParent();
04120   NamedDecl *Child = Field;
04121 
04122   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
04123     if (Parent->isUnion()) {
04124       UnionEntry &En = Unions[Parent];
04125       if (En.first && En.first != Child) {
04126         S.Diag(Init->getSourceLocation(),
04127                diag::err_multiple_mem_union_initialization)
04128           << Field->getDeclName()
04129           << Init->getSourceRange();
04130         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
04131           << 0 << En.second->getSourceRange();
04132         return true;
04133       } 
04134       if (!En.first) {
04135         En.first = Child;
04136         En.second = Init;
04137       }
04138       if (!Parent->isAnonymousStructOrUnion())
04139         return false;
04140     }
04141 
04142     Child = Parent;
04143     Parent = cast<RecordDecl>(Parent->getDeclContext());
04144   }
04145 
04146   return false;
04147 }
04148 }
04149 
04150 /// ActOnMemInitializers - Handle the member initializers for a constructor.
04151 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
04152                                 SourceLocation ColonLoc,
04153                                 ArrayRef<CXXCtorInitializer*> MemInits,
04154                                 bool AnyErrors) {
04155   if (!ConstructorDecl)
04156     return;
04157 
04158   AdjustDeclIfTemplate(ConstructorDecl);
04159 
04160   CXXConstructorDecl *Constructor
04161     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
04162 
04163   if (!Constructor) {
04164     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
04165     return;
04166   }
04167   
04168   // Mapping for the duplicate initializers check.
04169   // For member initializers, this is keyed with a FieldDecl*.
04170   // For base initializers, this is keyed with a Type*.
04171   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
04172 
04173   // Mapping for the inconsistent anonymous-union initializers check.
04174   RedundantUnionMap MemberUnions;
04175 
04176   bool HadError = false;
04177   for (unsigned i = 0; i < MemInits.size(); i++) {
04178     CXXCtorInitializer *Init = MemInits[i];
04179 
04180     // Set the source order index.
04181     Init->setSourceOrder(i);
04182 
04183     if (Init->isAnyMemberInitializer()) {
04184       const void *Key = GetKeyForMember(Context, Init);
04185       if (CheckRedundantInit(*this, Init, Members[Key]) ||
04186           CheckRedundantUnionInit(*this, Init, MemberUnions))
04187         HadError = true;
04188     } else if (Init->isBaseInitializer()) {
04189       const void *Key = GetKeyForMember(Context, Init);
04190       if (CheckRedundantInit(*this, Init, Members[Key]))
04191         HadError = true;
04192     } else {
04193       assert(Init->isDelegatingInitializer());
04194       // This must be the only initializer
04195       if (MemInits.size() != 1) {
04196         Diag(Init->getSourceLocation(),
04197              diag::err_delegating_initializer_alone)
04198           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
04199         // We will treat this as being the only initializer.
04200       }
04201       SetDelegatingInitializer(Constructor, MemInits[i]);
04202       // Return immediately as the initializer is set.
04203       return;
04204     }
04205   }
04206 
04207   if (HadError)
04208     return;
04209 
04210   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
04211 
04212   SetCtorInitializers(Constructor, AnyErrors, MemInits);
04213 
04214   DiagnoseUninitializedFields(*this, Constructor);
04215 }
04216 
04217 void
04218 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
04219                                              CXXRecordDecl *ClassDecl) {
04220   // Ignore dependent contexts. Also ignore unions, since their members never
04221   // have destructors implicitly called.
04222   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
04223     return;
04224 
04225   // FIXME: all the access-control diagnostics are positioned on the
04226   // field/base declaration.  That's probably good; that said, the
04227   // user might reasonably want to know why the destructor is being
04228   // emitted, and we currently don't say.
04229   
04230   // Non-static data members.
04231   for (auto *Field : ClassDecl->fields()) {
04232     if (Field->isInvalidDecl())
04233       continue;
04234     
04235     // Don't destroy incomplete or zero-length arrays.
04236     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
04237       continue;
04238 
04239     QualType FieldType = Context.getBaseElementType(Field->getType());
04240     
04241     const RecordType* RT = FieldType->getAs<RecordType>();
04242     if (!RT)
04243       continue;
04244     
04245     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
04246     if (FieldClassDecl->isInvalidDecl())
04247       continue;
04248     if (FieldClassDecl->hasIrrelevantDestructor())
04249       continue;
04250     // The destructor for an implicit anonymous union member is never invoked.
04251     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
04252       continue;
04253 
04254     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
04255     assert(Dtor && "No dtor found for FieldClassDecl!");
04256     CheckDestructorAccess(Field->getLocation(), Dtor,
04257                           PDiag(diag::err_access_dtor_field)
04258                             << Field->getDeclName()
04259                             << FieldType);
04260 
04261     MarkFunctionReferenced(Location, Dtor);
04262     DiagnoseUseOfDecl(Dtor, Location);
04263   }
04264 
04265   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
04266 
04267   // Bases.
04268   for (const auto &Base : ClassDecl->bases()) {
04269     // Bases are always records in a well-formed non-dependent class.
04270     const RecordType *RT = Base.getType()->getAs<RecordType>();
04271 
04272     // Remember direct virtual bases.
04273     if (Base.isVirtual())
04274       DirectVirtualBases.insert(RT);
04275 
04276     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
04277     // If our base class is invalid, we probably can't get its dtor anyway.
04278     if (BaseClassDecl->isInvalidDecl())
04279       continue;
04280     if (BaseClassDecl->hasIrrelevantDestructor())
04281       continue;
04282 
04283     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
04284     assert(Dtor && "No dtor found for BaseClassDecl!");
04285 
04286     // FIXME: caret should be on the start of the class name
04287     CheckDestructorAccess(Base.getLocStart(), Dtor,
04288                           PDiag(diag::err_access_dtor_base)
04289                             << Base.getType()
04290                             << Base.getSourceRange(),
04291                           Context.getTypeDeclType(ClassDecl));
04292     
04293     MarkFunctionReferenced(Location, Dtor);
04294     DiagnoseUseOfDecl(Dtor, Location);
04295   }
04296   
04297   // Virtual bases.
04298   for (const auto &VBase : ClassDecl->vbases()) {
04299     // Bases are always records in a well-formed non-dependent class.
04300     const RecordType *RT = VBase.getType()->castAs<RecordType>();
04301 
04302     // Ignore direct virtual bases.
04303     if (DirectVirtualBases.count(RT))
04304       continue;
04305 
04306     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
04307     // If our base class is invalid, we probably can't get its dtor anyway.
04308     if (BaseClassDecl->isInvalidDecl())
04309       continue;
04310     if (BaseClassDecl->hasIrrelevantDestructor())
04311       continue;
04312 
04313     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
04314     assert(Dtor && "No dtor found for BaseClassDecl!");
04315     if (CheckDestructorAccess(
04316             ClassDecl->getLocation(), Dtor,
04317             PDiag(diag::err_access_dtor_vbase)
04318                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
04319             Context.getTypeDeclType(ClassDecl)) ==
04320         AR_accessible) {
04321       CheckDerivedToBaseConversion(
04322           Context.getTypeDeclType(ClassDecl), VBase.getType(),
04323           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
04324           SourceRange(), DeclarationName(), nullptr);
04325     }
04326 
04327     MarkFunctionReferenced(Location, Dtor);
04328     DiagnoseUseOfDecl(Dtor, Location);
04329   }
04330 }
04331 
04332 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
04333   if (!CDtorDecl)
04334     return;
04335 
04336   if (CXXConstructorDecl *Constructor
04337       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
04338     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
04339     DiagnoseUninitializedFields(*this, Constructor);
04340   }
04341 }
04342 
04343 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
04344                                   unsigned DiagID, AbstractDiagSelID SelID) {
04345   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
04346     unsigned DiagID;
04347     AbstractDiagSelID SelID;
04348     
04349   public:
04350     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
04351       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
04352 
04353     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
04354       if (Suppressed) return;
04355       if (SelID == -1)
04356         S.Diag(Loc, DiagID) << T;
04357       else
04358         S.Diag(Loc, DiagID) << SelID << T;
04359     }
04360   } Diagnoser(DiagID, SelID);
04361   
04362   return RequireNonAbstractType(Loc, T, Diagnoser);
04363 }
04364 
04365 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
04366                                   TypeDiagnoser &Diagnoser) {
04367   if (!getLangOpts().CPlusPlus)
04368     return false;
04369 
04370   if (const ArrayType *AT = Context.getAsArrayType(T))
04371     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
04372 
04373   if (const PointerType *PT = T->getAs<PointerType>()) {
04374     // Find the innermost pointer type.
04375     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
04376       PT = T;
04377 
04378     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
04379       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
04380   }
04381 
04382   const RecordType *RT = T->getAs<RecordType>();
04383   if (!RT)
04384     return false;
04385 
04386   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
04387 
04388   // We can't answer whether something is abstract until it has a
04389   // definition.  If it's currently being defined, we'll walk back
04390   // over all the declarations when we have a full definition.
04391   const CXXRecordDecl *Def = RD->getDefinition();
04392   if (!Def || Def->isBeingDefined())
04393     return false;
04394 
04395   if (!RD->isAbstract())
04396     return false;
04397 
04398   Diagnoser.diagnose(*this, Loc, T);
04399   DiagnoseAbstractType(RD);
04400 
04401   return true;
04402 }
04403 
04404 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
04405   // Check if we've already emitted the list of pure virtual functions
04406   // for this class.
04407   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
04408     return;
04409 
04410   // If the diagnostic is suppressed, don't emit the notes. We're only
04411   // going to emit them once, so try to attach them to a diagnostic we're
04412   // actually going to show.
04413   if (Diags.isLastDiagnosticIgnored())
04414     return;
04415 
04416   CXXFinalOverriderMap FinalOverriders;
04417   RD->getFinalOverriders(FinalOverriders);
04418 
04419   // Keep a set of seen pure methods so we won't diagnose the same method
04420   // more than once.
04421   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
04422   
04423   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 
04424                                    MEnd = FinalOverriders.end();
04425        M != MEnd; 
04426        ++M) {
04427     for (OverridingMethods::iterator SO = M->second.begin(), 
04428                                   SOEnd = M->second.end();
04429          SO != SOEnd; ++SO) {
04430       // C++ [class.abstract]p4:
04431       //   A class is abstract if it contains or inherits at least one
04432       //   pure virtual function for which the final overrider is pure
04433       //   virtual.
04434 
04435       // 
04436       if (SO->second.size() != 1)
04437         continue;
04438 
04439       if (!SO->second.front().Method->isPure())
04440         continue;
04441 
04442       if (!SeenPureMethods.insert(SO->second.front().Method))
04443         continue;
04444 
04445       Diag(SO->second.front().Method->getLocation(), 
04446            diag::note_pure_virtual_function) 
04447         << SO->second.front().Method->getDeclName() << RD->getDeclName();
04448     }
04449   }
04450 
04451   if (!PureVirtualClassDiagSet)
04452     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
04453   PureVirtualClassDiagSet->insert(RD);
04454 }
04455 
04456 namespace {
04457 struct AbstractUsageInfo {
04458   Sema &S;
04459   CXXRecordDecl *Record;
04460   CanQualType AbstractType;
04461   bool Invalid;
04462 
04463   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
04464     : S(S), Record(Record),
04465       AbstractType(S.Context.getCanonicalType(
04466                    S.Context.getTypeDeclType(Record))),
04467       Invalid(false) {}
04468 
04469   void DiagnoseAbstractType() {
04470     if (Invalid) return;
04471     S.DiagnoseAbstractType(Record);
04472     Invalid = true;
04473   }
04474 
04475   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
04476 };
04477 
04478 struct CheckAbstractUsage {
04479   AbstractUsageInfo &Info;
04480   const NamedDecl *Ctx;
04481 
04482   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
04483     : Info(Info), Ctx(Ctx) {}
04484 
04485   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
04486     switch (TL.getTypeLocClass()) {
04487 #define ABSTRACT_TYPELOC(CLASS, PARENT)
04488 #define TYPELOC(CLASS, PARENT) \
04489     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
04490 #include "clang/AST/TypeLocNodes.def"
04491     }
04492   }
04493 
04494   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
04495     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
04496     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
04497       if (!TL.getParam(I))
04498         continue;
04499 
04500       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
04501       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
04502     }
04503   }
04504 
04505   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
04506     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
04507   }
04508 
04509   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
04510     // Visit the type parameters from a permissive context.
04511     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
04512       TemplateArgumentLoc TAL = TL.getArgLoc(I);
04513       if (TAL.getArgument().getKind() == TemplateArgument::Type)
04514         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
04515           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
04516       // TODO: other template argument types?
04517     }
04518   }
04519 
04520   // Visit pointee types from a permissive context.
04521 #define CheckPolymorphic(Type) \
04522   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
04523     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
04524   }
04525   CheckPolymorphic(PointerTypeLoc)
04526   CheckPolymorphic(ReferenceTypeLoc)
04527   CheckPolymorphic(MemberPointerTypeLoc)
04528   CheckPolymorphic(BlockPointerTypeLoc)
04529   CheckPolymorphic(AtomicTypeLoc)
04530 
04531   /// Handle all the types we haven't given a more specific
04532   /// implementation for above.
04533   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
04534     // Every other kind of type that we haven't called out already
04535     // that has an inner type is either (1) sugar or (2) contains that
04536     // inner type in some way as a subobject.
04537     if (TypeLoc Next = TL.getNextTypeLoc())
04538       return Visit(Next, Sel);
04539 
04540     // If there's no inner type and we're in a permissive context,
04541     // don't diagnose.
04542     if (Sel == Sema::AbstractNone) return;
04543 
04544     // Check whether the type matches the abstract type.
04545     QualType T = TL.getType();
04546     if (T->isArrayType()) {
04547       Sel = Sema::AbstractArrayType;
04548       T = Info.S.Context.getBaseElementType(T);
04549     }
04550     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
04551     if (CT != Info.AbstractType) return;
04552 
04553     // It matched; do some magic.
04554     if (Sel == Sema::AbstractArrayType) {
04555       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
04556         << T << TL.getSourceRange();
04557     } else {
04558       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
04559         << Sel << T << TL.getSourceRange();
04560     }
04561     Info.DiagnoseAbstractType();
04562   }
04563 };
04564 
04565 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
04566                                   Sema::AbstractDiagSelID Sel) {
04567   CheckAbstractUsage(*this, D).Visit(TL, Sel);
04568 }
04569 
04570 }
04571 
04572 /// Check for invalid uses of an abstract type in a method declaration.
04573 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
04574                                     CXXMethodDecl *MD) {
04575   // No need to do the check on definitions, which require that
04576   // the return/param types be complete.
04577   if (MD->doesThisDeclarationHaveABody())
04578     return;
04579 
04580   // For safety's sake, just ignore it if we don't have type source
04581   // information.  This should never happen for non-implicit methods,
04582   // but...
04583   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
04584     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
04585 }
04586 
04587 /// Check for invalid uses of an abstract type within a class definition.
04588 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
04589                                     CXXRecordDecl *RD) {
04590   for (auto *D : RD->decls()) {
04591     if (D->isImplicit()) continue;
04592 
04593     // Methods and method templates.
04594     if (isa<CXXMethodDecl>(D)) {
04595       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
04596     } else if (isa<FunctionTemplateDecl>(D)) {
04597       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
04598       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
04599 
04600     // Fields and static variables.
04601     } else if (isa<FieldDecl>(D)) {
04602       FieldDecl *FD = cast<FieldDecl>(D);
04603       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
04604         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
04605     } else if (isa<VarDecl>(D)) {
04606       VarDecl *VD = cast<VarDecl>(D);
04607       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
04608         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
04609 
04610     // Nested classes and class templates.
04611     } else if (isa<CXXRecordDecl>(D)) {
04612       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
04613     } else if (isa<ClassTemplateDecl>(D)) {
04614       CheckAbstractClassUsage(Info,
04615                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
04616     }
04617   }
04618 }
04619 
04620 /// \brief Check class-level dllimport/dllexport attribute.
04621 static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
04622   Attr *ClassAttr = getDLLAttr(Class);
04623 
04624   // MSVC inherits DLL attributes to partial class template specializations.
04625   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
04626     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
04627       if (Attr *TemplateAttr =
04628               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
04629         auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
04630         A->setInherited(true);
04631         ClassAttr = A;
04632       }
04633     }
04634   }
04635 
04636   if (!ClassAttr)
04637     return;
04638 
04639   if (!Class->isExternallyVisible()) {
04640     S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
04641         << Class << ClassAttr;
04642     return;
04643   }
04644 
04645   if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
04646       !ClassAttr->isInherited()) {
04647     // Diagnose dll attributes on members of class with dll attribute.
04648     for (Decl *Member : Class->decls()) {
04649       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
04650         continue;
04651       InheritableAttr *MemberAttr = getDLLAttr(Member);
04652       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
04653         continue;
04654 
04655       S.Diag(MemberAttr->getLocation(),
04656              diag::err_attribute_dll_member_of_dll_class)
04657           << MemberAttr << ClassAttr;
04658       S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
04659       Member->setInvalidDecl();
04660     }
04661   }
04662 
04663   if (Class->getDescribedClassTemplate())
04664     // Don't inherit dll attribute until the template is instantiated.
04665     return;
04666 
04667   // The class is either imported or exported.
04668   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
04669   const bool ClassImported = !ClassExported;
04670 
04671   // Force declaration of implicit members so they can inherit the attribute.
04672   S.ForceDeclarationOfImplicitMembers(Class);
04673 
04674   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
04675   // seem to be true in practice?
04676 
04677   TemplateSpecializationKind TSK =
04678     Class->getTemplateSpecializationKind();
04679 
04680   for (Decl *Member : Class->decls()) {
04681     VarDecl *VD = dyn_cast<VarDecl>(Member);
04682     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
04683 
04684     // Only methods and static fields inherit the attributes.
04685     if (!VD && !MD)
04686       continue;
04687 
04688     if (MD) {
04689       // Don't process deleted methods.
04690       if (MD->isDeleted())
04691         continue;
04692 
04693       if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
04694         // Current MSVC versions don't export the move assignment operators, so
04695         // don't attempt to import them if we have a definition.
04696         continue;
04697       }
04698 
04699       if (MD->isInlined() && ClassImported &&
04700           !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
04701         // MinGW does not import inline functions.
04702         continue;
04703       }
04704     }
04705 
04706     if (!getDLLAttr(Member)) {
04707       auto *NewAttr =
04708           cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
04709       NewAttr->setInherited(true);
04710       Member->addAttr(NewAttr);
04711     }
04712 
04713     if (MD && ClassExported) {
04714       if (MD->isUserProvided()) {
04715         // Instantiate non-default methods..
04716 
04717         // .. except for certain kinds of template specializations.
04718         if (TSK == TSK_ExplicitInstantiationDeclaration)
04719           continue;
04720         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
04721           continue;
04722 
04723         S.MarkFunctionReferenced(Class->getLocation(), MD);
04724       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
04725                  MD->isCopyAssignmentOperator() ||
04726                  MD->isMoveAssignmentOperator()) {
04727         // Instantiate non-trivial or explicitly defaulted methods, and the
04728         // copy assignment / move assignment operators.
04729         S.MarkFunctionReferenced(Class->getLocation(), MD);
04730         // Resolve its exception specification; CodeGen needs it.
04731         auto *FPT = MD->getType()->getAs<FunctionProtoType>();
04732         S.ResolveExceptionSpec(Class->getLocation(), FPT);
04733         S.ActOnFinishInlineMethodDef(MD);
04734       }
04735     }
04736   }
04737 }
04738 
04739 /// \brief Perform semantic checks on a class definition that has been
04740 /// completing, introducing implicitly-declared members, checking for
04741 /// abstract types, etc.
04742 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
04743   if (!Record)
04744     return;
04745 
04746   if (Record->isAbstract() && !Record->isInvalidDecl()) {
04747     AbstractUsageInfo Info(*this, Record);
04748     CheckAbstractClassUsage(Info, Record);
04749   }
04750   
04751   // If this is not an aggregate type and has no user-declared constructor,
04752   // complain about any non-static data members of reference or const scalar
04753   // type, since they will never get initializers.
04754   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
04755       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
04756       !Record->isLambda()) {
04757     bool Complained = false;
04758     for (const auto *F : Record->fields()) {
04759       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
04760         continue;
04761 
04762       if (F->getType()->isReferenceType() ||
04763           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
04764         if (!Complained) {
04765           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
04766             << Record->getTagKind() << Record;
04767           Complained = true;
04768         }
04769         
04770         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
04771           << F->getType()->isReferenceType()
04772           << F->getDeclName();
04773       }
04774     }
04775   }
04776 
04777   if (Record->isDynamicClass() && !Record->isDependentType())
04778     DynamicClasses.push_back(Record);
04779 
04780   if (Record->getIdentifier()) {
04781     // C++ [class.mem]p13:
04782     //   If T is the name of a class, then each of the following shall have a 
04783     //   name different from T:
04784     //     - every member of every anonymous union that is a member of class T.
04785     //
04786     // C++ [class.mem]p14:
04787     //   In addition, if class T has a user-declared constructor (12.1), every 
04788     //   non-static data member of class T shall have a name different from T.
04789     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
04790     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
04791          ++I) {
04792       NamedDecl *D = *I;
04793       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
04794           isa<IndirectFieldDecl>(D)) {
04795         Diag(D->getLocation(), diag::err_member_name_of_class)
04796           << D->getDeclName();
04797         break;
04798       }
04799     }
04800   }
04801 
04802   // Warn if the class has virtual methods but non-virtual public destructor.
04803   if (Record->isPolymorphic() && !Record->isDependentType()) {
04804     CXXDestructorDecl *dtor = Record->getDestructor();
04805     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
04806         !Record->hasAttr<FinalAttr>())
04807       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
04808            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
04809   }
04810 
04811   if (Record->isAbstract()) {
04812     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
04813       Diag(Record->getLocation(), diag::warn_abstract_final_class)
04814         << FA->isSpelledAsSealed();
04815       DiagnoseAbstractType(Record);
04816     }
04817   }
04818 
04819   bool HasMethodWithOverrideControl = false,
04820        HasOverridingMethodWithoutOverrideControl = false;
04821   if (!Record->isDependentType()) {
04822     for (auto *M : Record->methods()) {
04823       // See if a method overloads virtual methods in a base
04824       // class without overriding any.
04825       if (!M->isStatic())
04826         DiagnoseHiddenVirtualMethods(M);
04827       if (M->hasAttr<OverrideAttr>())
04828         HasMethodWithOverrideControl = true;
04829       else if (M->size_overridden_methods() > 0)
04830         HasOverridingMethodWithoutOverrideControl = true;
04831       // Check whether the explicitly-defaulted special members are valid.
04832       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
04833         CheckExplicitlyDefaultedSpecialMember(M);
04834 
04835       // For an explicitly defaulted or deleted special member, we defer
04836       // determining triviality until the class is complete. That time is now!
04837       if (!M->isImplicit() && !M->isUserProvided()) {
04838         CXXSpecialMember CSM = getSpecialMember(M);
04839         if (CSM != CXXInvalid) {
04840           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
04841 
04842           // Inform the class that we've finished declaring this member.
04843           Record->finishedDefaultedOrDeletedMember(M);
04844         }
04845       }
04846     }
04847   }
04848 
04849   if (HasMethodWithOverrideControl &&
04850       HasOverridingMethodWithoutOverrideControl) {
04851     // At least one method has the 'override' control declared.
04852     // Diagnose all other overridden methods which do not have 'override' specified on them.
04853     for (auto *M : Record->methods())
04854       DiagnoseAbsenceOfOverrideControl(M);
04855   }
04856   // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
04857   // function that is not a constructor declares that member function to be
04858   // const. [...] The class of which that function is a member shall be
04859   // a literal type.
04860   //
04861   // If the class has virtual bases, any constexpr members will already have
04862   // been diagnosed by the checks performed on the member declaration, so
04863   // suppress this (less useful) diagnostic.
04864   //
04865   // We delay this until we know whether an explicitly-defaulted (or deleted)
04866   // destructor for the class is trivial.
04867   if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
04868       !Record->isLiteral() && !Record->getNumVBases()) {
04869     for (const auto *M : Record->methods()) {
04870       if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
04871         switch (Record->getTemplateSpecializationKind()) {
04872         case TSK_ImplicitInstantiation:
04873         case TSK_ExplicitInstantiationDeclaration:
04874         case TSK_ExplicitInstantiationDefinition:
04875           // If a template instantiates to a non-literal type, but its members
04876           // instantiate to constexpr functions, the template is technically
04877           // ill-formed, but we allow it for sanity.
04878           continue;
04879 
04880         case TSK_Undeclared:
04881         case TSK_ExplicitSpecialization:
04882           RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
04883                              diag::err_constexpr_method_non_literal);
04884           break;
04885         }
04886 
04887         // Only produce one error per class.
04888         break;
04889       }
04890     }
04891   }
04892 
04893   // ms_struct is a request to use the same ABI rules as MSVC.  Check
04894   // whether this class uses any C++ features that are implemented
04895   // completely differently in MSVC, and if so, emit a diagnostic.
04896   // That diagnostic defaults to an error, but we allow projects to
04897   // map it down to a warning (or ignore it).  It's a fairly common
04898   // practice among users of the ms_struct pragma to mass-annotate
04899   // headers, sweeping up a bunch of types that the project doesn't
04900   // really rely on MSVC-compatible layout for.  We must therefore
04901   // support "ms_struct except for C++ stuff" as a secondary ABI.
04902   if (Record->isMsStruct(Context) &&
04903       (Record->isPolymorphic() || Record->getNumBases())) {
04904     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
04905   }
04906 
04907   // Declare inheriting constructors. We do this eagerly here because:
04908   // - The standard requires an eager diagnostic for conflicting inheriting
04909   //   constructors from different classes.
04910   // - The lazy declaration of the other implicit constructors is so as to not
04911   //   waste space and performance on classes that are not meant to be
04912   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
04913   //   have inheriting constructors.
04914   DeclareInheritingConstructors(Record);
04915 
04916   checkDLLAttribute(*this, Record);
04917 }
04918 
04919 /// Look up the special member function that would be called by a special
04920 /// member function for a subobject of class type.
04921 ///
04922 /// \param Class The class type of the subobject.
04923 /// \param CSM The kind of special member function.
04924 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
04925 /// \param ConstRHS True if this is a copy operation with a const object
04926 ///        on its RHS, that is, if the argument to the outer special member
04927 ///        function is 'const' and this is not a field marked 'mutable'.
04928 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
04929     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
04930     unsigned FieldQuals, bool ConstRHS) {
04931   unsigned LHSQuals = 0;
04932   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
04933     LHSQuals = FieldQuals;
04934 
04935   unsigned RHSQuals = FieldQuals;
04936   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
04937     RHSQuals = 0;
04938   else if (ConstRHS)
04939     RHSQuals |= Qualifiers::Const;
04940 
04941   return S.LookupSpecialMember(Class, CSM,
04942                                RHSQuals & Qualifiers::Const,
04943                                RHSQuals & Qualifiers::Volatile,
04944                                false,
04945                                LHSQuals & Qualifiers::Const,
04946                                LHSQuals & Qualifiers::Volatile);
04947 }
04948 
04949 /// Is the special member function which would be selected to perform the
04950 /// specified operation on the specified class type a constexpr constructor?
04951 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
04952                                      Sema::CXXSpecialMember CSM,
04953                                      unsigned Quals, bool ConstRHS) {
04954   Sema::SpecialMemberOverloadResult *SMOR =
04955       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
04956   if (!SMOR || !SMOR->getMethod())
04957     // A constructor we wouldn't select can't be "involved in initializing"
04958     // anything.
04959     return true;
04960   return SMOR->getMethod()->isConstexpr();
04961 }
04962 
04963 /// Determine whether the specified special member function would be constexpr
04964 /// if it were implicitly defined.
04965 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
04966                                               Sema::CXXSpecialMember CSM,
04967                                               bool ConstArg) {
04968   if (!S.getLangOpts().CPlusPlus11)
04969     return false;
04970 
04971   // C++11 [dcl.constexpr]p4:
04972   // In the definition of a constexpr constructor [...]
04973   bool Ctor = true;
04974   switch (CSM) {
04975   case Sema::CXXDefaultConstructor:
04976     // Since default constructor lookup is essentially trivial (and cannot
04977     // involve, for instance, template instantiation), we compute whether a
04978     // defaulted default constructor is constexpr directly within CXXRecordDecl.
04979     //
04980     // This is important for performance; we need to know whether the default
04981     // constructor is constexpr to determine whether the type is a literal type.
04982     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
04983 
04984   case Sema::CXXCopyConstructor:
04985   case Sema::CXXMoveConstructor:
04986     // For copy or move constructors, we need to perform overload resolution.
04987     break;
04988 
04989   case Sema::CXXCopyAssignment:
04990   case Sema::CXXMoveAssignment:
04991     if (!S.getLangOpts().CPlusPlus14)
04992       return false;
04993     // In C++1y, we need to perform overload resolution.
04994     Ctor = false;
04995     break;
04996 
04997   case Sema::CXXDestructor:
04998   case Sema::CXXInvalid:
04999     return false;
05000   }
05001 
05002   //   -- if the class is a non-empty union, or for each non-empty anonymous
05003   //      union member of a non-union class, exactly one non-static data member
05004   //      shall be initialized; [DR1359]
05005   //
05006   // If we squint, this is guaranteed, since exactly one non-static data member
05007   // will be initialized (if the constructor isn't deleted), we just don't know
05008   // which one.
05009   if (Ctor && ClassDecl->isUnion())
05010     return true;
05011 
05012   //   -- the class shall not have any virtual base classes;
05013   if (Ctor && ClassDecl->getNumVBases())
05014     return false;
05015 
05016   // C++1y [class.copy]p26:
05017   //   -- [the class] is a literal type, and
05018   if (!Ctor && !ClassDecl->isLiteral())
05019     return false;
05020 
05021   //   -- every constructor involved in initializing [...] base class
05022   //      sub-objects shall be a constexpr constructor;
05023   //   -- the assignment operator selected to copy/move each direct base
05024   //      class is a constexpr function, and
05025   for (const auto &B : ClassDecl->bases()) {
05026     const RecordType *BaseType = B.getType()->getAs<RecordType>();
05027     if (!BaseType) continue;
05028 
05029     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
05030     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
05031       return false;
05032   }
05033 
05034   //   -- every constructor involved in initializing non-static data members
05035   //      [...] shall be a constexpr constructor;
05036   //   -- every non-static data member and base class sub-object shall be
05037   //      initialized
05038   //   -- for each non-static data member of X that is of class type (or array
05039   //      thereof), the assignment operator selected to copy/move that member is
05040   //      a constexpr function
05041   for (const auto *F : ClassDecl->fields()) {
05042     if (F->isInvalidDecl())
05043       continue;
05044     QualType BaseType = S.Context.getBaseElementType(F->getType());
05045     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
05046       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
05047       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
05048                                     BaseType.getCVRQualifiers(),
05049                                     ConstArg && !F->isMutable()))
05050         return false;
05051     }
05052   }
05053 
05054   // All OK, it's constexpr!
05055   return true;
05056 }
05057 
05058 static Sema::ImplicitExceptionSpecification
05059 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
05060   switch (S.getSpecialMember(MD)) {
05061   case Sema::CXXDefaultConstructor:
05062     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
05063   case Sema::CXXCopyConstructor:
05064     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
05065   case Sema::CXXCopyAssignment:
05066     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
05067   case Sema::CXXMoveConstructor:
05068     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
05069   case Sema::CXXMoveAssignment:
05070     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
05071   case Sema::CXXDestructor:
05072     return S.ComputeDefaultedDtorExceptionSpec(MD);
05073   case Sema::CXXInvalid:
05074     break;
05075   }
05076   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
05077          "only special members have implicit exception specs");
05078   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
05079 }
05080 
05081 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
05082                                                             CXXMethodDecl *MD) {
05083   FunctionProtoType::ExtProtoInfo EPI;
05084 
05085   // Build an exception specification pointing back at this member.
05086   EPI.ExceptionSpec.Type = EST_Unevaluated;
05087   EPI.ExceptionSpec.SourceDecl = MD;
05088 
05089   // Set the calling convention to the default for C++ instance methods.
05090   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
05091       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
05092                                             /*IsCXXMethod=*/true));
05093   return EPI;
05094 }
05095 
05096 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
05097   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
05098   if (FPT->getExceptionSpecType() != EST_Unevaluated)
05099     return;
05100 
05101   // Evaluate the exception specification.
05102   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
05103 
05104   // Update the type of the special member to use it.
05105   UpdateExceptionSpec(MD, ESI);
05106 
05107   // A user-provided destructor can be defined outside the class. When that
05108   // happens, be sure to update the exception specification on both
05109   // declarations.
05110   const FunctionProtoType *CanonicalFPT =
05111     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
05112   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
05113     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
05114 }
05115 
05116 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
05117   CXXRecordDecl *RD = MD->getParent();
05118   CXXSpecialMember CSM = getSpecialMember(MD);
05119 
05120   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
05121          "not an explicitly-defaulted special member");
05122 
05123   // Whether this was the first-declared instance of the constructor.
05124   // This affects whether we implicitly add an exception spec and constexpr.
05125   bool First = MD == MD->getCanonicalDecl();
05126 
05127   bool HadError = false;
05128 
05129   // C++11 [dcl.fct.def.default]p1:
05130   //   A function that is explicitly defaulted shall
05131   //     -- be a special member function (checked elsewhere),
05132   //     -- have the same type (except for ref-qualifiers, and except that a
05133   //        copy operation can take a non-const reference) as an implicit
05134   //        declaration, and
05135   //     -- not have default arguments.
05136   unsigned ExpectedParams = 1;
05137   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
05138     ExpectedParams = 0;
05139   if (MD->getNumParams() != ExpectedParams) {
05140     // This also checks for default arguments: a copy or move constructor with a
05141     // default argument is classified as a default constructor, and assignment
05142     // operations and destructors can't have default arguments.
05143     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
05144       << CSM << MD->getSourceRange();
05145     HadError = true;
05146   } else if (MD->isVariadic()) {
05147     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
05148       << CSM << MD->getSourceRange();
05149     HadError = true;
05150   }
05151 
05152   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
05153 
05154   bool CanHaveConstParam = false;
05155   if (CSM == CXXCopyConstructor)
05156     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
05157   else if (CSM == CXXCopyAssignment)
05158     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
05159 
05160   QualType ReturnType = Context.VoidTy;
05161   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
05162     // Check for return type matching.
05163     ReturnType = Type->getReturnType();
05164     QualType ExpectedReturnType =
05165         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
05166     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
05167       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
05168         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
05169       HadError = true;
05170     }
05171 
05172     // A defaulted special member cannot have cv-qualifiers.
05173     if (Type->getTypeQuals()) {
05174       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
05175         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
05176       HadError = true;
05177     }
05178   }
05179 
05180   // Check for parameter type matching.
05181   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
05182   bool HasConstParam = false;
05183   if (ExpectedParams && ArgType->isReferenceType()) {
05184     // Argument must be reference to possibly-const T.
05185     QualType ReferentType = ArgType->getPointeeType();
05186     HasConstParam = ReferentType.isConstQualified();
05187 
05188     if (ReferentType.isVolatileQualified()) {
05189       Diag(MD->getLocation(),
05190            diag::err_defaulted_special_member_volatile_param) << CSM;
05191       HadError = true;
05192     }
05193 
05194     if (HasConstParam && !CanHaveConstParam) {
05195       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
05196         Diag(MD->getLocation(),
05197              diag::err_defaulted_special_member_copy_const_param)
05198           << (CSM == CXXCopyAssignment);
05199         // FIXME: Explain why this special member can't be const.
05200       } else {
05201         Diag(MD->getLocation(),
05202              diag::err_defaulted_special_member_move_const_param)
05203           << (CSM == CXXMoveAssignment);
05204       }
05205       HadError = true;
05206     }
05207   } else if (ExpectedParams) {
05208     // A copy assignment operator can take its argument by value, but a
05209     // defaulted one cannot.
05210     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
05211     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
05212     HadError = true;
05213   }
05214 
05215   // C++11 [dcl.fct.def.default]p2:
05216   //   An explicitly-defaulted function may be declared constexpr only if it
05217   //   would have been implicitly declared as constexpr,
05218   // Do not apply this rule to members of class templates, since core issue 1358
05219   // makes such functions always instantiate to constexpr functions. For
05220   // functions which cannot be constexpr (for non-constructors in C++11 and for
05221   // destructors in C++1y), this is checked elsewhere.
05222   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
05223                                                      HasConstParam);
05224   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
05225                                  : isa<CXXConstructorDecl>(MD)) &&
05226       MD->isConstexpr() && !Constexpr &&
05227       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
05228     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
05229     // FIXME: Explain why the special member can't be constexpr.
05230     HadError = true;
05231   }
05232 
05233   //   and may have an explicit exception-specification only if it is compatible
05234   //   with the exception-specification on the implicit declaration.
05235   if (Type->hasExceptionSpec()) {
05236     // Delay the check if this is the first declaration of the special member,
05237     // since we may not have parsed some necessary in-class initializers yet.
05238     if (First) {
05239       // If the exception specification needs to be instantiated, do so now,
05240       // before we clobber it with an EST_Unevaluated specification below.
05241       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
05242         InstantiateExceptionSpec(MD->getLocStart(), MD);
05243         Type = MD->getType()->getAs<FunctionProtoType>();
05244       }
05245       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
05246     } else
05247       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
05248   }
05249 
05250   //   If a function is explicitly defaulted on its first declaration,
05251   if (First) {
05252     //  -- it is implicitly considered to be constexpr if the implicit
05253     //     definition would be,
05254     MD->setConstexpr(Constexpr);
05255 
05256     //  -- it is implicitly considered to have the same exception-specification
05257     //     as if it had been implicitly declared,
05258     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
05259     EPI.ExceptionSpec.Type = EST_Unevaluated;
05260     EPI.ExceptionSpec.SourceDecl = MD;
05261     MD->setType(Context.getFunctionType(ReturnType,
05262                                         llvm::makeArrayRef(&ArgType,
05263                                                            ExpectedParams),
05264                                         EPI));
05265   }
05266 
05267   if (ShouldDeleteSpecialMember(MD, CSM)) {
05268     if (First) {
05269       SetDeclDeleted(MD, MD->getLocation());
05270     } else {
05271       // C++11 [dcl.fct.def.default]p4:
05272       //   [For a] user-provided explicitly-defaulted function [...] if such a
05273       //   function is implicitly defined as deleted, the program is ill-formed.
05274       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
05275       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
05276       HadError = true;
05277     }
05278   }
05279 
05280   if (HadError)
05281     MD->setInvalidDecl();
05282 }
05283 
05284 /// Check whether the exception specification provided for an
05285 /// explicitly-defaulted special member matches the exception specification
05286 /// that would have been generated for an implicit special member, per
05287 /// C++11 [dcl.fct.def.default]p2.
05288 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
05289     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
05290   // If the exception specification was explicitly specified but hadn't been
05291   // parsed when the method was defaulted, grab it now.
05292   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
05293     SpecifiedType =
05294         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
05295 
05296   // Compute the implicit exception specification.
05297   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
05298                                                        /*IsCXXMethod=*/true);
05299   FunctionProtoType::ExtProtoInfo EPI(CC);
05300   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
05301                           .getExceptionSpec();
05302   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
05303     Context.getFunctionType(Context.VoidTy, None, EPI));
05304 
05305   // Ensure that it matches.
05306   CheckEquivalentExceptionSpec(
05307     PDiag(diag::err_incorrect_defaulted_exception_spec)
05308       << getSpecialMember(MD), PDiag(),
05309     ImplicitType, SourceLocation(),
05310     SpecifiedType, MD->getLocation());
05311 }
05312 
05313 void Sema::CheckDelayedMemberExceptionSpecs() {
05314   SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
05315               2> Checks;
05316   SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
05317 
05318   std::swap(Checks, DelayedDestructorExceptionSpecChecks);
05319   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
05320 
05321   // Perform any deferred checking of exception specifications for virtual
05322   // destructors.
05323   for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
05324     const CXXDestructorDecl *Dtor = Checks[i].first;
05325     assert(!Dtor->getParent()->isDependentType() &&
05326            "Should not ever add destructors of templates into the list.");
05327     CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
05328   }
05329 
05330   // Check that any explicitly-defaulted methods have exception specifications
05331   // compatible with their implicit exception specifications.
05332   for (unsigned I = 0, N = Specs.size(); I != N; ++I)
05333     CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
05334                                                 Specs[I].second);
05335 }
05336 
05337 namespace {
05338 struct SpecialMemberDeletionInfo {
05339   Sema &S;
05340   CXXMethodDecl *MD;
05341   Sema::CXXSpecialMember CSM;
05342   bool Diagnose;
05343 
05344   // Properties of the special member, computed for convenience.
05345   bool IsConstructor, IsAssignment, IsMove, ConstArg;
05346   SourceLocation Loc;
05347 
05348   bool AllFieldsAreConst;
05349 
05350   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
05351                             Sema::CXXSpecialMember CSM, bool Diagnose)
05352     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
05353       IsConstructor(false), IsAssignment(false), IsMove(false),
05354       ConstArg(false), Loc(MD->getLocation()),
05355       AllFieldsAreConst(true) {
05356     switch (CSM) {
05357       case Sema::CXXDefaultConstructor:
05358       case Sema::CXXCopyConstructor:
05359         IsConstructor = true;
05360         break;
05361       case Sema::CXXMoveConstructor:
05362         IsConstructor = true;
05363         IsMove = true;
05364         break;
05365       case Sema::CXXCopyAssignment:
05366         IsAssignment = true;
05367         break;
05368       case Sema::CXXMoveAssignment:
05369         IsAssignment = true;
05370         IsMove = true;
05371         break;
05372       case Sema::CXXDestructor:
05373         break;
05374       case Sema::CXXInvalid:
05375         llvm_unreachable("invalid special member kind");
05376     }
05377 
05378     if (MD->getNumParams()) {
05379       if (const ReferenceType *RT =
05380               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
05381         ConstArg = RT->getPointeeType().isConstQualified();
05382     }
05383   }
05384 
05385   bool inUnion() const { return MD->getParent()->isUnion(); }
05386 
05387   /// Look up the corresponding special member in the given class.
05388   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
05389                                               unsigned Quals, bool IsMutable) {
05390     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
05391                                        ConstArg && !IsMutable);
05392   }
05393 
05394   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
05395 
05396   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
05397   bool shouldDeleteForField(FieldDecl *FD);
05398   bool shouldDeleteForAllConstMembers();
05399 
05400   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
05401                                      unsigned Quals);
05402   bool shouldDeleteForSubobjectCall(Subobject Subobj,
05403                                     Sema::SpecialMemberOverloadResult *SMOR,
05404                                     bool IsDtorCallInCtor);
05405 
05406   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
05407 };
05408 }
05409 
05410 /// Is the given special member inaccessible when used on the given
05411 /// sub-object.
05412 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
05413                                              CXXMethodDecl *target) {
05414   /// If we're operating on a base class, the object type is the
05415   /// type of this special member.
05416   QualType objectTy;
05417   AccessSpecifier access = target->getAccess();
05418   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
05419     objectTy = S.Context.getTypeDeclType(MD->getParent());
05420     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
05421 
05422   // If we're operating on a field, the object type is the type of the field.
05423   } else {
05424     objectTy = S.Context.getTypeDeclType(target->getParent());
05425   }
05426 
05427   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
05428 }
05429 
05430 /// Check whether we should delete a special member due to the implicit
05431 /// definition containing a call to a special member of a subobject.
05432 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
05433     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
05434     bool IsDtorCallInCtor) {
05435   CXXMethodDecl *Decl = SMOR->getMethod();
05436   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
05437 
05438   int DiagKind = -1;
05439 
05440   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
05441     DiagKind = !Decl ? 0 : 1;
05442   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
05443     DiagKind = 2;
05444   else if (!isAccessible(Subobj, Decl))
05445     DiagKind = 3;
05446   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
05447            !Decl->isTrivial()) {
05448     // A member of a union must have a trivial corresponding special member.
05449     // As a weird special case, a destructor call from a union's constructor
05450     // must be accessible and non-deleted, but need not be trivial. Such a
05451     // destructor is never actually called, but is semantically checked as
05452     // if it were.
05453     DiagKind = 4;
05454   }
05455 
05456   if (DiagKind == -1)
05457     return false;
05458 
05459   if (Diagnose) {
05460     if (Field) {
05461       S.Diag(Field->getLocation(),
05462              diag::note_deleted_special_member_class_subobject)
05463         << CSM << MD->getParent() << /*IsField*/true
05464         << Field << DiagKind << IsDtorCallInCtor;
05465     } else {
05466       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
05467       S.Diag(Base->getLocStart(),
05468              diag::note_deleted_special_member_class_subobject)
05469         << CSM << MD->getParent() << /*IsField*/false
05470         << Base->getType() << DiagKind << IsDtorCallInCtor;
05471     }
05472 
05473     if (DiagKind == 1)
05474       S.NoteDeletedFunction(Decl);
05475     // FIXME: Explain inaccessibility if DiagKind == 3.
05476   }
05477 
05478   return true;
05479 }
05480 
05481 /// Check whether we should delete a special member function due to having a
05482 /// direct or virtual base class or non-static data member of class type M.
05483 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
05484     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
05485   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
05486   bool IsMutable = Field && Field->isMutable();
05487 
05488   // C++11 [class.ctor]p5:
05489   // -- any direct or virtual base class, or non-static data member with no
05490   //    brace-or-equal-initializer, has class type M (or array thereof) and
05491   //    either M has no default constructor or overload resolution as applied
05492   //    to M's default constructor results in an ambiguity or in a function
05493   //    that is deleted or inaccessible
05494   // C++11 [class.copy]p11, C++11 [class.copy]p23:
05495   // -- a direct or virtual base class B that cannot be copied/moved because
05496   //    overload resolution, as applied to B's corresponding special member,
05497   //    results in an ambiguity or a function that is deleted or inaccessible
05498   //    from the defaulted special member
05499   // C++11 [class.dtor]p5:
05500   // -- any direct or virtual base class [...] has a type with a destructor
05501   //    that is deleted or inaccessible
05502   if (!(CSM == Sema::CXXDefaultConstructor &&
05503         Field && Field->hasInClassInitializer()) &&
05504       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
05505                                    false))
05506     return true;
05507 
05508   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
05509   // -- any direct or virtual base class or non-static data member has a
05510   //    type with a destructor that is deleted or inaccessible
05511   if (IsConstructor) {
05512     Sema::SpecialMemberOverloadResult *SMOR =
05513         S.LookupSpecialMember(Class, Sema::CXXDestructor,
05514                               false, false, false, false, false);
05515     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
05516       return true;
05517   }
05518 
05519   return false;
05520 }
05521 
05522 /// Check whether we should delete a special member function due to the class
05523 /// having a particular direct or virtual base class.
05524 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
05525   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
05526   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
05527 }
05528 
05529 /// Check whether we should delete a special member function due to the class
05530 /// having a particular non-static data member.
05531 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
05532   QualType FieldType = S.Context.getBaseElementType(FD->getType());
05533   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
05534 
05535   if (CSM == Sema::CXXDefaultConstructor) {
05536     // For a default constructor, all references must be initialized in-class
05537     // and, if a union, it must have a non-const member.
05538     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
05539       if (Diagnose)
05540         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
05541           << MD->getParent() << FD << FieldType << /*Reference*/0;
05542       return true;
05543     }
05544     // C++11 [class.ctor]p5: any non-variant non-static data member of
05545     // const-qualified type (or array thereof) with no
05546     // brace-or-equal-initializer does not have a user-provided default
05547     // constructor.
05548     if (!inUnion() && FieldType.isConstQualified() &&
05549         !FD->hasInClassInitializer() &&
05550         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
05551       if (Diagnose)
05552         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
05553           << MD->getParent() << FD << FD->getType() << /*Const*/1;
05554       return true;
05555     }
05556 
05557     if (inUnion() && !FieldType.isConstQualified())
05558       AllFieldsAreConst = false;
05559   } else if (CSM == Sema::CXXCopyConstructor) {
05560     // For a copy constructor, data members must not be of rvalue reference
05561     // type.
05562     if (FieldType->isRValueReferenceType()) {
05563       if (Diagnose)
05564         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
05565           << MD->getParent() << FD << FieldType;
05566       return true;
05567     }
05568   } else if (IsAssignment) {
05569     // For an assignment operator, data members must not be of reference type.
05570     if (FieldType->isReferenceType()) {
05571       if (Diagnose)
05572         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
05573           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
05574       return true;
05575     }
05576     if (!FieldRecord && FieldType.isConstQualified()) {
05577       // C++11 [class.copy]p23:
05578       // -- a non-static data member of const non-class type (or array thereof)
05579       if (Diagnose)
05580         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
05581           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
05582       return true;
05583     }
05584   }
05585 
05586   if (FieldRecord) {
05587     // Some additional restrictions exist on the variant members.
05588     if (!inUnion() && FieldRecord->isUnion() &&
05589         FieldRecord->isAnonymousStructOrUnion()) {
05590       bool AllVariantFieldsAreConst = true;
05591 
05592       // FIXME: Handle anonymous unions declared within anonymous unions.
05593       for (auto *UI : FieldRecord->fields()) {
05594         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
05595 
05596         if (!UnionFieldType.isConstQualified())
05597           AllVariantFieldsAreConst = false;
05598 
05599         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
05600         if (UnionFieldRecord &&
05601             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
05602                                           UnionFieldType.getCVRQualifiers()))
05603           return true;
05604       }
05605 
05606       // At least one member in each anonymous union must be non-const
05607       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
05608           !FieldRecord->field_empty()) {
05609         if (Diagnose)
05610           S.Diag(FieldRecord->getLocation(),
05611                  diag::note_deleted_default_ctor_all_const)
05612             << MD->getParent() << /*anonymous union*/1;
05613         return true;
05614       }
05615 
05616       // Don't check the implicit member of the anonymous union type.
05617       // This is technically non-conformant, but sanity demands it.
05618       return false;
05619     }
05620 
05621     if (shouldDeleteForClassSubobject(FieldRecord, FD,
05622                                       FieldType.getCVRQualifiers()))
05623       return true;
05624   }
05625 
05626   return false;
05627 }
05628 
05629 /// C++11 [class.ctor] p5:
05630 ///   A defaulted default constructor for a class X is defined as deleted if
05631 /// X is a union and all of its variant members are of const-qualified type.
05632 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
05633   // This is a silly definition, because it gives an empty union a deleted
05634   // default constructor. Don't do that.
05635   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
05636       !MD->getParent()->field_empty()) {
05637     if (Diagnose)
05638       S.Diag(MD->getParent()->getLocation(),
05639              diag::note_deleted_default_ctor_all_const)
05640         << MD->getParent() << /*not anonymous union*/0;
05641     return true;
05642   }
05643   return false;
05644 }
05645 
05646 /// Determine whether a defaulted special member function should be defined as
05647 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
05648 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
05649 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
05650                                      bool Diagnose) {
05651   if (MD->isInvalidDecl())
05652     return false;
05653   CXXRecordDecl *RD = MD->getParent();
05654   assert(!RD->isDependentType() && "do deletion after instantiation");
05655   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
05656     return false;
05657 
05658   // C++11 [expr.lambda.prim]p19:
05659   //   The closure type associated with a lambda-expression has a
05660   //   deleted (8.4.3) default constructor and a deleted copy
05661   //   assignment operator.
05662   if (RD->isLambda() &&
05663       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
05664     if (Diagnose)
05665       Diag(RD->getLocation(), diag::note_lambda_decl);
05666     return true;
05667   }
05668 
05669   // For an anonymous struct or union, the copy and assignment special members
05670   // will never be used, so skip the check. For an anonymous union declared at
05671   // namespace scope, the constructor and destructor are used.
05672   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
05673       RD->isAnonymousStructOrUnion())
05674     return false;
05675 
05676   // C++11 [class.copy]p7, p18:
05677   //   If the class definition declares a move constructor or move assignment
05678   //   operator, an implicitly declared copy constructor or copy assignment
05679   //   operator is defined as deleted.
05680   if (MD->isImplicit() &&
05681       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
05682     CXXMethodDecl *UserDeclaredMove = nullptr;
05683 
05684     // In Microsoft mode, a user-declared move only causes the deletion of the
05685     // corresponding copy operation, not both copy operations.
05686     if (RD->hasUserDeclaredMoveConstructor() &&
05687         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
05688       if (!Diagnose) return true;
05689 
05690       // Find any user-declared move constructor.
05691       for (auto *I : RD->ctors()) {
05692         if (I->isMoveConstructor()) {
05693           UserDeclaredMove = I;
05694           break;
05695         }
05696       }
05697       assert(UserDeclaredMove);
05698     } else if (RD->hasUserDeclaredMoveAssignment() &&
05699                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
05700       if (!Diagnose) return true;
05701 
05702       // Find any user-declared move assignment operator.
05703       for (auto *I : RD->methods()) {
05704         if (I->isMoveAssignmentOperator()) {
05705           UserDeclaredMove = I;
05706           break;
05707         }
05708       }
05709       assert(UserDeclaredMove);
05710     }
05711 
05712     if (UserDeclaredMove) {
05713       Diag(UserDeclaredMove->getLocation(),
05714            diag::note_deleted_copy_user_declared_move)
05715         << (CSM == CXXCopyAssignment) << RD
05716         << UserDeclaredMove->isMoveAssignmentOperator();
05717       return true;
05718     }
05719   }
05720 
05721   // Do access control from the special member function
05722   ContextRAII MethodContext(*this, MD);
05723 
05724   // C++11 [class.dtor]p5:
05725   // -- for a virtual destructor, lookup of the non-array deallocation function
05726   //    results in an ambiguity or in a function that is deleted or inaccessible
05727   if (CSM == CXXDestructor && MD->isVirtual()) {
05728     FunctionDecl *OperatorDelete = nullptr;
05729     DeclarationName Name =
05730       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
05731     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
05732                                  OperatorDelete, false)) {
05733       if (Diagnose)
05734         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
05735       return true;
05736     }
05737   }
05738 
05739   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
05740 
05741   for (auto &BI : RD->bases())
05742     if (!BI.isVirtual() &&
05743         SMI.shouldDeleteForBase(&BI))
05744       return true;
05745 
05746   // Per DR1611, do not consider virtual bases of constructors of abstract
05747   // classes, since we are not going to construct them.
05748   if (!RD->isAbstract() || !SMI.IsConstructor) {
05749     for (auto &BI : RD->vbases())
05750       if (SMI.shouldDeleteForBase(&BI))
05751         return true;
05752   }
05753 
05754   for (auto *FI : RD->fields())
05755     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
05756         SMI.shouldDeleteForField(FI))
05757       return true;
05758 
05759   if (SMI.shouldDeleteForAllConstMembers())
05760     return true;
05761 
05762   if (getLangOpts().CUDA) {
05763     // We should delete the special member in CUDA mode if target inference
05764     // failed.
05765     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
05766                                                    Diagnose);
05767   }
05768 
05769   return false;
05770 }
05771 
05772 /// Perform lookup for a special member of the specified kind, and determine
05773 /// whether it is trivial. If the triviality can be determined without the
05774 /// lookup, skip it. This is intended for use when determining whether a
05775 /// special member of a containing object is trivial, and thus does not ever
05776 /// perform overload resolution for default constructors.
05777 ///
05778 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
05779 /// member that was most likely to be intended to be trivial, if any.
05780 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
05781                                      Sema::CXXSpecialMember CSM, unsigned Quals,
05782                                      bool ConstRHS, CXXMethodDecl **Selected) {
05783   if (Selected)
05784     *Selected = nullptr;
05785 
05786   switch (CSM) {
05787   case Sema::CXXInvalid:
05788     llvm_unreachable("not a special member");
05789 
05790   case Sema::CXXDefaultConstructor:
05791     // C++11 [class.ctor]p5:
05792     //   A default constructor is trivial if:
05793     //    - all the [direct subobjects] have trivial default constructors
05794     //
05795     // Note, no overload resolution is performed in this case.
05796     if (RD->hasTrivialDefaultConstructor())
05797       return true;
05798 
05799     if (Selected) {
05800       // If there's a default constructor which could have been trivial, dig it
05801       // out. Otherwise, if there's any user-provided default constructor, point
05802       // to that as an example of why there's not a trivial one.
05803       CXXConstructorDecl *DefCtor = nullptr;
05804       if (RD->needsImplicitDefaultConstructor())
05805         S.DeclareImplicitDefaultConstructor(RD);
05806       for (auto *CI : RD->ctors()) {
05807         if (!CI->isDefaultConstructor())
05808           continue;
05809         DefCtor = CI;
05810         if (!DefCtor->isUserProvided())
05811           break;
05812       }
05813 
05814       *Selected = DefCtor;
05815     }
05816 
05817     return false;
05818 
05819   case Sema::CXXDestructor:
05820     // C++11 [class.dtor]p5:
05821     //   A destructor is trivial if:
05822     //    - all the direct [subobjects] have trivial destructors
05823     if (RD->hasTrivialDestructor())
05824       return true;
05825 
05826     if (Selected) {
05827       if (RD->needsImplicitDestructor())
05828         S.DeclareImplicitDestructor(RD);
05829       *Selected = RD->getDestructor();
05830     }
05831 
05832     return false;
05833 
05834   case Sema::CXXCopyConstructor:
05835     // C++11 [class.copy]p12:
05836     //   A copy constructor is trivial if:
05837     //    - the constructor selected to copy each direct [subobject] is trivial
05838     if (RD->hasTrivialCopyConstructor()) {
05839       if (Quals == Qualifiers::Const)
05840         // We must either select the trivial copy constructor or reach an
05841         // ambiguity; no need to actually perform overload resolution.
05842         return true;
05843     } else if (!Selected) {
05844       return false;
05845     }
05846     // In C++98, we are not supposed to perform overload resolution here, but we
05847     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
05848     // cases like B as having a non-trivial copy constructor:
05849     //   struct A { template<typename T> A(T&); };
05850     //   struct B { mutable A a; };
05851     goto NeedOverloadResolution;
05852 
05853   case Sema::CXXCopyAssignment:
05854     // C++11 [class.copy]p25:
05855     //   A copy assignment operator is trivial if:
05856     //    - the assignment operator selected to copy each direct [subobject] is
05857     //      trivial
05858     if (RD->hasTrivialCopyAssignment()) {
05859       if (Quals == Qualifiers::Const)
05860         return true;
05861     } else if (!Selected) {
05862       return false;
05863     }
05864     // In C++98, we are not supposed to perform overload resolution here, but we
05865     // treat that as a language defect.
05866     goto NeedOverloadResolution;
05867 
05868   case Sema::CXXMoveConstructor:
05869   case Sema::CXXMoveAssignment:
05870   NeedOverloadResolution:
05871     Sema::SpecialMemberOverloadResult *SMOR =
05872         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
05873 
05874     // The standard doesn't describe how to behave if the lookup is ambiguous.
05875     // We treat it as not making the member non-trivial, just like the standard
05876     // mandates for the default constructor. This should rarely matter, because
05877     // the member will also be deleted.
05878     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
05879       return true;
05880 
05881     if (!SMOR->getMethod()) {
05882       assert(SMOR->getKind() ==
05883              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
05884       return false;
05885     }
05886 
05887     // We deliberately don't check if we found a deleted special member. We're
05888     // not supposed to!
05889     if (Selected)
05890       *Selected = SMOR->getMethod();
05891     return SMOR->getMethod()->isTrivial();
05892   }
05893 
05894   llvm_unreachable("unknown special method kind");
05895 }
05896 
05897 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
05898   for (auto *CI : RD->ctors())
05899     if (!CI->isImplicit())
05900       return CI;
05901 
05902   // Look for constructor templates.
05903   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
05904   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
05905     if (CXXConstructorDecl *CD =
05906           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
05907       return CD;
05908   }
05909 
05910   return nullptr;
05911 }
05912 
05913 /// The kind of subobject we are checking for triviality. The values of this
05914 /// enumeration are used in diagnostics.
05915 enum TrivialSubobjectKind {
05916   /// The subobject is a base class.
05917   TSK_BaseClass,
05918   /// The subobject is a non-static data member.
05919   TSK_Field,
05920   /// The object is actually the complete object.
05921   TSK_CompleteObject
05922 };
05923 
05924 /// Check whether the special member selected for a given type would be trivial.
05925 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
05926                                       QualType SubType, bool ConstRHS,
05927                                       Sema::CXXSpecialMember CSM,
05928                                       TrivialSubobjectKind Kind,
05929                                       bool Diagnose) {
05930   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
05931   if (!SubRD)
05932     return true;
05933 
05934   CXXMethodDecl *Selected;
05935   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
05936                                ConstRHS, Diagnose ? &Selected : nullptr))
05937     return true;
05938 
05939   if (Diagnose) {
05940     if (ConstRHS)
05941       SubType.addConst();
05942 
05943     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
05944       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
05945         << Kind << SubType.getUnqualifiedType();
05946       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
05947         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
05948     } else if (!Selected)
05949       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
05950         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
05951     else if (Selected->isUserProvided()) {
05952       if (Kind == TSK_CompleteObject)
05953         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
05954           << Kind << SubType.getUnqualifiedType() << CSM;
05955       else {
05956         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
05957           << Kind << SubType.getUnqualifiedType() << CSM;
05958         S.Diag(Selected->getLocation(), diag::note_declared_at);
05959       }
05960     } else {
05961       if (Kind != TSK_CompleteObject)
05962         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
05963           << Kind << SubType.getUnqualifiedType() << CSM;
05964 
05965       // Explain why the defaulted or deleted special member isn't trivial.
05966       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
05967     }
05968   }
05969 
05970   return false;
05971 }
05972 
05973 /// Check whether the members of a class type allow a special member to be
05974 /// trivial.
05975 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
05976                                      Sema::CXXSpecialMember CSM,
05977                                      bool ConstArg, bool Diagnose) {
05978   for (const auto *FI : RD->fields()) {
05979     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
05980       continue;
05981 
05982     QualType FieldType = S.Context.getBaseElementType(FI->getType());
05983 
05984     // Pretend anonymous struct or union members are members of this class.
05985     if (FI->isAnonymousStructOrUnion()) {
05986       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
05987                                     CSM, ConstArg, Diagnose))
05988         return false;
05989       continue;
05990     }
05991 
05992     // C++11 [class.ctor]p5:
05993     //   A default constructor is trivial if [...]
05994     //    -- no non-static data member of its class has a
05995     //       brace-or-equal-initializer
05996     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
05997       if (Diagnose)
05998         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
05999       return false;
06000     }
06001 
06002     // Objective C ARC 4.3.5:
06003     //   [...] nontrivally ownership-qualified types are [...] not trivially
06004     //   default constructible, copy constructible, move constructible, copy
06005     //   assignable, move assignable, or destructible [...]
06006     if (S.getLangOpts().ObjCAutoRefCount &&
06007         FieldType.hasNonTrivialObjCLifetime()) {
06008       if (Diagnose)
06009         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
06010           << RD << FieldType.getObjCLifetime();
06011       return false;
06012     }
06013 
06014     bool ConstRHS = ConstArg && !FI->isMutable();
06015     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
06016                                    CSM, TSK_Field, Diagnose))
06017       return false;
06018   }
06019 
06020   return true;
06021 }
06022 
06023 /// Diagnose why the specified class does not have a trivial special member of
06024 /// the given kind.
06025 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
06026   QualType Ty = Context.getRecordType(RD);
06027 
06028   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
06029   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
06030                             TSK_CompleteObject, /*Diagnose*/true);
06031 }
06032 
06033 /// Determine whether a defaulted or deleted special member function is trivial,
06034 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
06035 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
06036 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
06037                                   bool Diagnose) {
06038   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
06039 
06040   CXXRecordDecl *RD = MD->getParent();
06041 
06042   bool ConstArg = false;
06043 
06044   // C++11 [class.copy]p12, p25: [DR1593]
06045   //   A [special member] is trivial if [...] its parameter-type-list is
06046   //   equivalent to the parameter-type-list of an implicit declaration [...]
06047   switch (CSM) {
06048   case CXXDefaultConstructor:
06049   case CXXDestructor:
06050     // Trivial default constructors and destructors cannot have parameters.
06051     break;
06052 
06053   case CXXCopyConstructor:
06054   case CXXCopyAssignment: {
06055     // Trivial copy operations always have const, non-volatile parameter types.
06056     ConstArg = true;
06057     const ParmVarDecl *Param0 = MD->getParamDecl(0);
06058     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
06059     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
06060       if (Diagnose)
06061         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
06062           << Param0->getSourceRange() << Param0->getType()
06063           << Context.getLValueReferenceType(
06064                Context.getRecordType(RD).withConst());
06065       return false;
06066     }
06067     break;
06068   }
06069 
06070   case CXXMoveConstructor:
06071   case CXXMoveAssignment: {
06072     // Trivial move operations always have non-cv-qualified parameters.
06073     const ParmVarDecl *Param0 = MD->getParamDecl(0);
06074     const RValueReferenceType *RT =
06075       Param0->getType()->getAs<RValueReferenceType>();
06076     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
06077       if (Diagnose)
06078         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
06079           << Param0->getSourceRange() << Param0->getType()
06080           << Context.getRValueReferenceType(Context.getRecordType(RD));
06081       return false;
06082     }
06083     break;
06084   }
06085 
06086   case CXXInvalid:
06087     llvm_unreachable("not a special member");
06088   }
06089 
06090   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
06091     if (Diagnose)
06092       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
06093            diag::note_nontrivial_default_arg)
06094         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
06095     return false;
06096   }
06097   if (MD->isVariadic()) {
06098     if (Diagnose)
06099       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
06100     return false;
06101   }
06102 
06103   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
06104   //   A copy/move [constructor or assignment operator] is trivial if
06105   //    -- the [member] selected to copy/move each direct base class subobject
06106   //       is trivial
06107   //
06108   // C++11 [class.copy]p12, C++11 [class.copy]p25:
06109   //   A [default constructor or destructor] is trivial if
06110   //    -- all the direct base classes have trivial [default constructors or
06111   //       destructors]
06112   for (const auto &BI : RD->bases())
06113     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
06114                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
06115       return false;
06116 
06117   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
06118   //   A copy/move [constructor or assignment operator] for a class X is
06119   //   trivial if
06120   //    -- for each non-static data member of X that is of class type (or array
06121   //       thereof), the constructor selected to copy/move that member is
06122   //       trivial
06123   //
06124   // C++11 [class.copy]p12, C++11 [class.copy]p25:
06125   //   A [default constructor or destructor] is trivial if
06126   //    -- for all of the non-static data members of its class that are of class
06127   //       type (or array thereof), each such class has a trivial [default
06128   //       constructor or destructor]
06129   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
06130     return false;
06131 
06132   // C++11 [class.dtor]p5:
06133   //   A destructor is trivial if [...]
06134   //    -- the destructor is not virtual
06135   if (CSM == CXXDestructor && MD->isVirtual()) {
06136     if (Diagnose)
06137       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
06138     return false;
06139   }
06140 
06141   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
06142   //   A [special member] for class X is trivial if [...]
06143   //    -- class X has no virtual functions and no virtual base classes
06144   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
06145     if (!Diagnose)
06146       return false;
06147 
06148     if (RD->getNumVBases()) {
06149       // Check for virtual bases. We already know that the corresponding
06150       // member in all bases is trivial, so vbases must all be direct.
06151       CXXBaseSpecifier &BS = *RD->vbases_begin();
06152       assert(BS.isVirtual());
06153       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
06154       return false;
06155     }
06156 
06157     // Must have a virtual method.
06158     for (const auto *MI : RD->methods()) {
06159       if (MI->isVirtual()) {
06160         SourceLocation MLoc = MI->getLocStart();
06161         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
06162         return false;
06163       }
06164     }
06165 
06166     llvm_unreachable("dynamic class with no vbases and no virtual functions");
06167   }
06168 
06169   // Looks like it's trivial!
06170   return true;
06171 }
06172 
06173 /// \brief Data used with FindHiddenVirtualMethod
06174 namespace {
06175   struct FindHiddenVirtualMethodData {
06176     Sema *S;
06177     CXXMethodDecl *Method;
06178     llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
06179     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
06180   };
06181 }
06182 
06183 /// \brief Check whether any most overriden method from MD in Methods
06184 static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
06185                   const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
06186   if (MD->size_overridden_methods() == 0)
06187     return Methods.count(MD->getCanonicalDecl());
06188   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
06189                                       E = MD->end_overridden_methods();
06190        I != E; ++I)
06191     if (CheckMostOverridenMethods(*I, Methods))
06192       return true;
06193   return false;
06194 }
06195 
06196 /// \brief Member lookup function that determines whether a given C++
06197 /// method overloads virtual methods in a base class without overriding any,
06198 /// to be used with CXXRecordDecl::lookupInBases().
06199 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
06200                                     CXXBasePath &Path,
06201                                     void *UserData) {
06202   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
06203 
06204   FindHiddenVirtualMethodData &Data
06205     = *static_cast<FindHiddenVirtualMethodData*>(UserData);
06206 
06207   DeclarationName Name = Data.Method->getDeclName();
06208   assert(Name.getNameKind() == DeclarationName::Identifier);
06209 
06210   bool foundSameNameMethod = false;
06211   SmallVector<CXXMethodDecl *, 8> overloadedMethods;
06212   for (Path.Decls = BaseRecord->lookup(Name);
06213        !Path.Decls.empty();
06214        Path.Decls = Path.Decls.slice(1)) {
06215     NamedDecl *D = Path.Decls.front();
06216     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
06217       MD = MD->getCanonicalDecl();
06218       foundSameNameMethod = true;
06219       // Interested only in hidden virtual methods.
06220       if (!MD->isVirtual())
06221         continue;
06222       // If the method we are checking overrides a method from its base
06223       // don't warn about the other overloaded methods. Clang deviates from GCC
06224       // by only diagnosing overloads of inherited virtual functions that do not
06225       // override any other virtual functions in the base. GCC's
06226       // -Woverloaded-virtual diagnoses any derived function hiding a virtual
06227       // function from a base class. These cases may be better served by a
06228       // warning (not specific to virtual functions) on call sites when the call
06229       // would select a different function from the base class, were it visible.
06230       // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
06231       if (!Data.S->IsOverload(Data.Method, MD, false))
06232         return true;
06233       // Collect the overload only if its hidden.
06234       if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
06235         overloadedMethods.push_back(MD);
06236     }
06237   }
06238 
06239   if (foundSameNameMethod)
06240     Data.OverloadedMethods.append(overloadedMethods.begin(),
06241                                    overloadedMethods.end());
06242   return foundSameNameMethod;
06243 }
06244 
06245 /// \brief Add the most overriden methods from MD to Methods
06246 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
06247                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
06248   if (MD->size_overridden_methods() == 0)
06249     Methods.insert(MD->getCanonicalDecl());
06250   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
06251                                       E = MD->end_overridden_methods();
06252        I != E; ++I)
06253     AddMostOverridenMethods(*I, Methods);
06254 }
06255 
06256 /// \brief Check if a method overloads virtual methods in a base class without
06257 /// overriding any.
06258 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
06259                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
06260   if (!MD->getDeclName().isIdentifier())
06261     return;
06262 
06263   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
06264                      /*bool RecordPaths=*/false,
06265                      /*bool DetectVirtual=*/false);
06266   FindHiddenVirtualMethodData Data;
06267   Data.Method = MD;
06268   Data.S = this;
06269 
06270   // Keep the base methods that were overriden or introduced in the subclass
06271   // by 'using' in a set. A base method not in this set is hidden.
06272   CXXRecordDecl *DC = MD->getParent();
06273   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
06274   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
06275     NamedDecl *ND = *I;
06276     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
06277       ND = shad->getTargetDecl();
06278     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
06279       AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
06280   }
06281 
06282   if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
06283     OverloadedMethods = Data.OverloadedMethods;
06284 }
06285 
06286 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
06287                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
06288   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
06289     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
06290     PartialDiagnostic PD = PDiag(
06291          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
06292     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
06293     Diag(overloadedMD->getLocation(), PD);
06294   }
06295 }
06296 
06297 /// \brief Diagnose methods which overload virtual methods in a base class
06298 /// without overriding any.
06299 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
06300   if (MD->isInvalidDecl())
06301     return;
06302 
06303   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
06304     return;
06305 
06306   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
06307   FindHiddenVirtualMethods(MD, OverloadedMethods);
06308   if (!OverloadedMethods.empty()) {
06309     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
06310       << MD << (OverloadedMethods.size() > 1);
06311 
06312     NoteHiddenVirtualMethods(MD, OverloadedMethods);
06313   }
06314 }
06315 
06316 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
06317                                              Decl *TagDecl,
06318                                              SourceLocation LBrac,
06319                                              SourceLocation RBrac,
06320                                              AttributeList *AttrList) {
06321   if (!TagDecl)
06322     return;
06323 
06324   AdjustDeclIfTemplate(TagDecl);
06325 
06326   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
06327     if (l->getKind() != AttributeList::AT_Visibility)
06328       continue;
06329     l->setInvalid();
06330     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
06331       l->getName();
06332   }
06333 
06334   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
06335               // strict aliasing violation!
06336               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
06337               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
06338 
06339   CheckCompletedCXXClass(
06340                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
06341 }
06342 
06343 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
06344 /// special functions, such as the default constructor, copy
06345 /// constructor, or destructor, to the given C++ class (C++
06346 /// [special]p1).  This routine can only be executed just before the
06347 /// definition of the class is complete.
06348 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
06349   if (!ClassDecl->hasUserDeclaredConstructor())
06350     ++ASTContext::NumImplicitDefaultConstructors;
06351 
06352   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
06353     ++ASTContext::NumImplicitCopyConstructors;
06354 
06355     // If the properties or semantics of the copy constructor couldn't be
06356     // determined while the class was being declared, force a declaration
06357     // of it now.
06358     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
06359       DeclareImplicitCopyConstructor(ClassDecl);
06360   }
06361 
06362   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
06363     ++ASTContext::NumImplicitMoveConstructors;
06364 
06365     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
06366       DeclareImplicitMoveConstructor(ClassDecl);
06367   }
06368 
06369   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
06370     ++ASTContext::NumImplicitCopyAssignmentOperators;
06371 
06372     // If we have a dynamic class, then the copy assignment operator may be
06373     // virtual, so we have to declare it immediately. This ensures that, e.g.,
06374     // it shows up in the right place in the vtable and that we diagnose
06375     // problems with the implicit exception specification.
06376     if (ClassDecl->isDynamicClass() ||
06377         ClassDecl->needsOverloadResolutionForCopyAssignment())
06378       DeclareImplicitCopyAssignment(ClassDecl);
06379   }
06380 
06381   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
06382     ++ASTContext::NumImplicitMoveAssignmentOperators;
06383 
06384     // Likewise for the move assignment operator.
06385     if (ClassDecl->isDynamicClass() ||
06386         ClassDecl->needsOverloadResolutionForMoveAssignment())
06387       DeclareImplicitMoveAssignment(ClassDecl);
06388   }
06389 
06390   if (!ClassDecl->hasUserDeclaredDestructor()) {
06391     ++ASTContext::NumImplicitDestructors;
06392 
06393     // If we have a dynamic class, then the destructor may be virtual, so we
06394     // have to declare the destructor immediately. This ensures that, e.g., it
06395     // shows up in the right place in the vtable and that we diagnose problems
06396     // with the implicit exception specification.
06397     if (ClassDecl->isDynamicClass() ||
06398         ClassDecl->needsOverloadResolutionForDestructor())
06399       DeclareImplicitDestructor(ClassDecl);
06400   }
06401 }
06402 
06403 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
06404   if (!D)
06405     return 0;
06406 
06407   // The order of template parameters is not important here. All names
06408   // get added to the same scope.
06409   SmallVector<TemplateParameterList *, 4> ParameterLists;
06410 
06411   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
06412     D = TD->getTemplatedDecl();
06413 
06414   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
06415     ParameterLists.push_back(PSD->getTemplateParameters());
06416 
06417   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
06418     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
06419       ParameterLists.push_back(DD->getTemplateParameterList(i));
06420 
06421     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
06422       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
06423         ParameterLists.push_back(FTD->getTemplateParameters());
06424     }
06425   }
06426 
06427   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
06428     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
06429       ParameterLists.push_back(TD->getTemplateParameterList(i));
06430 
06431     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
06432       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
06433         ParameterLists.push_back(CTD->getTemplateParameters());
06434     }
06435   }
06436 
06437   unsigned Count = 0;
06438   for (TemplateParameterList *Params : ParameterLists) {
06439     if (Params->size() > 0)
06440       // Ignore explicit specializations; they don't contribute to the template
06441       // depth.
06442       ++Count;
06443     for (NamedDecl *Param : *Params) {
06444       if (Param->getDeclName()) {
06445         S->AddDecl(Param);
06446         IdResolver.AddDecl(Param);
06447       }
06448     }
06449   }
06450 
06451   return Count;
06452 }
06453 
06454 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
06455   if (!RecordD) return;
06456   AdjustDeclIfTemplate(RecordD);
06457   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
06458   PushDeclContext(S, Record);
06459 }
06460 
06461 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
06462   if (!RecordD) return;
06463   PopDeclContext();
06464 }
06465 
06466 /// This is used to implement the constant expression evaluation part of the
06467 /// attribute enable_if extension. There is nothing in standard C++ which would
06468 /// require reentering parameters.
06469 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
06470   if (!Param)
06471     return;
06472 
06473   S->AddDecl(Param);
06474   if (Param->getDeclName())
06475     IdResolver.AddDecl(Param);
06476 }
06477 
06478 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
06479 /// parsing a top-level (non-nested) C++ class, and we are now
06480 /// parsing those parts of the given Method declaration that could
06481 /// not be parsed earlier (C++ [class.mem]p2), such as default
06482 /// arguments. This action should enter the scope of the given
06483 /// Method declaration as if we had just parsed the qualified method
06484 /// name. However, it should not bring the parameters into scope;
06485 /// that will be performed by ActOnDelayedCXXMethodParameter.
06486 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
06487 }
06488 
06489 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
06490 /// C++ method declaration. We're (re-)introducing the given
06491 /// function parameter into scope for use in parsing later parts of
06492 /// the method declaration. For example, we could see an
06493 /// ActOnParamDefaultArgument event for this parameter.
06494 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
06495   if (!ParamD)
06496     return;
06497 
06498   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
06499 
06500   // If this parameter has an unparsed default argument, clear it out
06501   // to make way for the parsed default argument.
06502   if (Param->hasUnparsedDefaultArg())
06503     Param->setDefaultArg(nullptr);
06504 
06505   S->AddDecl(Param);
06506   if (Param->getDeclName())
06507     IdResolver.AddDecl(Param);
06508 }
06509 
06510 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
06511 /// processing the delayed method declaration for Method. The method
06512 /// declaration is now considered finished. There may be a separate
06513 /// ActOnStartOfFunctionDef action later (not necessarily
06514 /// immediately!) for this method, if it was also defined inside the
06515 /// class body.
06516 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
06517   if (!MethodD)
06518     return;
06519 
06520   AdjustDeclIfTemplate(MethodD);
06521 
06522   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
06523 
06524   // Now that we have our default arguments, check the constructor
06525   // again. It could produce additional diagnostics or affect whether
06526   // the class has implicitly-declared destructors, among other
06527   // things.
06528   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
06529     CheckConstructor(Constructor);
06530 
06531   // Check the default arguments, which we may have added.
06532   if (!Method->isInvalidDecl())
06533     CheckCXXDefaultArguments(Method);
06534 }
06535 
06536 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
06537 /// the well-formedness of the constructor declarator @p D with type @p
06538 /// R. If there are any errors in the declarator, this routine will
06539 /// emit diagnostics and set the invalid bit to true.  In any case, the type
06540 /// will be updated to reflect a well-formed type for the constructor and
06541 /// returned.
06542 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
06543                                           StorageClass &SC) {
06544   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
06545 
06546   // C++ [class.ctor]p3:
06547   //   A constructor shall not be virtual (10.3) or static (9.4). A
06548   //   constructor can be invoked for a const, volatile or const
06549   //   volatile object. A constructor shall not be declared const,
06550   //   volatile, or const volatile (9.3.2).
06551   if (isVirtual) {
06552     if (!D.isInvalidType())
06553       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
06554         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
06555         << SourceRange(D.getIdentifierLoc());
06556     D.setInvalidType();
06557   }
06558   if (SC == SC_Static) {
06559     if (!D.isInvalidType())
06560       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
06561         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
06562         << SourceRange(D.getIdentifierLoc());
06563     D.setInvalidType();
06564     SC = SC_None;
06565   }
06566 
06567   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
06568     diagnoseIgnoredQualifiers(
06569         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
06570         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
06571         D.getDeclSpec().getRestrictSpecLoc(),
06572         D.getDeclSpec().getAtomicSpecLoc());
06573     D.setInvalidType();
06574   }
06575 
06576   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
06577   if (FTI.TypeQuals != 0) {
06578     if (FTI.TypeQuals & Qualifiers::Const)
06579       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
06580         << "const" << SourceRange(D.getIdentifierLoc());
06581     if (FTI.TypeQuals & Qualifiers::Volatile)
06582       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
06583         << "volatile" << SourceRange(D.getIdentifierLoc());
06584     if (FTI.TypeQuals & Qualifiers::Restrict)
06585       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
06586         << "restrict" << SourceRange(D.getIdentifierLoc());
06587     D.setInvalidType();
06588   }
06589 
06590   // C++0x [class.ctor]p4:
06591   //   A constructor shall not be declared with a ref-qualifier.
06592   if (FTI.hasRefQualifier()) {
06593     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
06594       << FTI.RefQualifierIsLValueRef 
06595       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
06596     D.setInvalidType();
06597   }
06598   
06599   // Rebuild the function type "R" without any type qualifiers (in
06600   // case any of the errors above fired) and with "void" as the
06601   // return type, since constructors don't have return types.
06602   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
06603   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
06604     return R;
06605 
06606   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
06607   EPI.TypeQuals = 0;
06608   EPI.RefQualifier = RQ_None;
06609 
06610   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
06611 }
06612 
06613 /// CheckConstructor - Checks a fully-formed constructor for
06614 /// well-formedness, issuing any diagnostics required. Returns true if
06615 /// the constructor declarator is invalid.
06616 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
06617   CXXRecordDecl *ClassDecl
06618     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
06619   if (!ClassDecl)
06620     return Constructor->setInvalidDecl();
06621 
06622   // C++ [class.copy]p3:
06623   //   A declaration of a constructor for a class X is ill-formed if
06624   //   its first parameter is of type (optionally cv-qualified) X and
06625   //   either there are no other parameters or else all other
06626   //   parameters have default arguments.
06627   if (!Constructor->isInvalidDecl() &&
06628       ((Constructor->getNumParams() == 1) ||
06629        (Constructor->getNumParams() > 1 &&
06630         Constructor->getParamDecl(1)->hasDefaultArg())) &&
06631       Constructor->getTemplateSpecializationKind()
06632                                               != TSK_ImplicitInstantiation) {
06633     QualType ParamType = Constructor->getParamDecl(0)->getType();
06634     QualType ClassTy = Context.getTagDeclType(ClassDecl);
06635     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
06636       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
06637       const char *ConstRef 
06638         = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 
06639                                                         : " const &";
06640       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
06641         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
06642 
06643       // FIXME: Rather that making the constructor invalid, we should endeavor
06644       // to fix the type.
06645       Constructor->setInvalidDecl();
06646     }
06647   }
06648 }
06649 
06650 /// CheckDestructor - Checks a fully-formed destructor definition for
06651 /// well-formedness, issuing any diagnostics required.  Returns true
06652 /// on error.
06653 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
06654   CXXRecordDecl *RD = Destructor->getParent();
06655   
06656   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
06657     SourceLocation Loc;
06658     
06659     if (!Destructor->isImplicit())
06660       Loc = Destructor->getLocation();
06661     else
06662       Loc = RD->getLocation();
06663     
06664     // If we have a virtual destructor, look up the deallocation function
06665     FunctionDecl *OperatorDelete = nullptr;
06666     DeclarationName Name = 
06667     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
06668     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
06669       return true;
06670     // If there's no class-specific operator delete, look up the global
06671     // non-array delete.
06672     if (!OperatorDelete)
06673       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
06674 
06675     MarkFunctionReferenced(Loc, OperatorDelete);
06676     
06677     Destructor->setOperatorDelete(OperatorDelete);
06678   }
06679   
06680   return false;
06681 }
06682 
06683 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
06684 /// the well-formednes of the destructor declarator @p D with type @p
06685 /// R. If there are any errors in the declarator, this routine will
06686 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
06687 /// will be updated to reflect a well-formed type for the destructor and
06688 /// returned.
06689 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
06690                                          StorageClass& SC) {
06691   // C++ [class.dtor]p1:
06692   //   [...] A typedef-name that names a class is a class-name
06693   //   (7.1.3); however, a typedef-name that names a class shall not
06694   //   be used as the identifier in the declarator for a destructor
06695   //   declaration.
06696   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
06697   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
06698     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
06699       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
06700   else if (const TemplateSpecializationType *TST =
06701              DeclaratorType->getAs<TemplateSpecializationType>())
06702     if (TST->isTypeAlias())
06703       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
06704         << DeclaratorType << 1;
06705 
06706   // C++ [class.dtor]p2:
06707   //   A destructor is used to destroy objects of its class type. A
06708   //   destructor takes no parameters, and no return type can be
06709   //   specified for it (not even void). The address of a destructor
06710   //   shall not be taken. A destructor shall not be static. A
06711   //   destructor can be invoked for a const, volatile or const
06712   //   volatile object. A destructor shall not be declared const,
06713   //   volatile or const volatile (9.3.2).
06714   if (SC == SC_Static) {
06715     if (!D.isInvalidType())
06716       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
06717         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
06718         << SourceRange(D.getIdentifierLoc())
06719         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
06720     
06721     SC = SC_None;
06722   }
06723   if (!D.isInvalidType()) {
06724     // Destructors don't have return types, but the parser will
06725     // happily parse something like:
06726     //
06727     //   class X {
06728     //     float ~X();
06729     //   };
06730     //
06731     // The return type will be eliminated later.
06732     if (D.getDeclSpec().hasTypeSpecifier())
06733       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
06734         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
06735         << SourceRange(D.getIdentifierLoc());
06736     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
06737       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
06738                                 SourceLocation(),
06739                                 D.getDeclSpec().getConstSpecLoc(),
06740                                 D.getDeclSpec().getVolatileSpecLoc(),
06741                                 D.getDeclSpec().getRestrictSpecLoc(),
06742                                 D.getDeclSpec().getAtomicSpecLoc());
06743       D.setInvalidType();
06744     }
06745   }
06746 
06747   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
06748   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
06749     if (FTI.TypeQuals & Qualifiers::Const)
06750       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
06751         << "const" << SourceRange(D.getIdentifierLoc());
06752     if (FTI.TypeQuals & Qualifiers::Volatile)
06753       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
06754         << "volatile" << SourceRange(D.getIdentifierLoc());
06755     if (FTI.TypeQuals & Qualifiers::Restrict)
06756       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
06757         << "restrict" << SourceRange(D.getIdentifierLoc());
06758     D.setInvalidType();
06759   }
06760 
06761   // C++0x [class.dtor]p2:
06762   //   A destructor shall not be declared with a ref-qualifier.
06763   if (FTI.hasRefQualifier()) {
06764     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
06765       << FTI.RefQualifierIsLValueRef
06766       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
06767     D.setInvalidType();
06768   }
06769   
06770   // Make sure we don't have any parameters.
06771   if (FTIHasNonVoidParameters(FTI)) {
06772     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
06773 
06774     // Delete the parameters.
06775     FTI.freeParams();
06776     D.setInvalidType();
06777   }
06778 
06779   // Make sure the destructor isn't variadic.
06780   if (FTI.isVariadic) {
06781     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
06782     D.setInvalidType();
06783   }
06784 
06785   // Rebuild the function type "R" without any type qualifiers or
06786   // parameters (in case any of the errors above fired) and with
06787   // "void" as the return type, since destructors don't have return
06788   // types. 
06789   if (!D.isInvalidType())
06790     return R;
06791 
06792   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
06793   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
06794   EPI.Variadic = false;
06795   EPI.TypeQuals = 0;
06796   EPI.RefQualifier = RQ_None;
06797   return Context.getFunctionType(Context.VoidTy, None, EPI);
06798 }
06799 
06800 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
06801 /// well-formednes of the conversion function declarator @p D with
06802 /// type @p R. If there are any errors in the declarator, this routine
06803 /// will emit diagnostics and return true. Otherwise, it will return
06804 /// false. Either way, the type @p R will be updated to reflect a
06805 /// well-formed type for the conversion operator.
06806 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
06807                                      StorageClass& SC) {
06808   // C++ [class.conv.fct]p1:
06809   //   Neither parameter types nor return type can be specified. The
06810   //   type of a conversion function (8.3.5) is "function taking no
06811   //   parameter returning conversion-type-id."
06812   if (SC == SC_Static) {
06813     if (!D.isInvalidType())
06814       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
06815         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
06816         << D.getName().getSourceRange();
06817     D.setInvalidType();
06818     SC = SC_None;
06819   }
06820 
06821   QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
06822 
06823   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
06824     // Conversion functions don't have return types, but the parser will
06825     // happily parse something like:
06826     //
06827     //   class X {
06828     //     float operator bool();
06829     //   };
06830     //
06831     // The return type will be changed later anyway.
06832     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
06833       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
06834       << SourceRange(D.getIdentifierLoc());
06835     D.setInvalidType();
06836   }
06837 
06838   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
06839 
06840   // Make sure we don't have any parameters.
06841   if (Proto->getNumParams() > 0) {
06842     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
06843 
06844     // Delete the parameters.
06845     D.getFunctionTypeInfo().freeParams();
06846     D.setInvalidType();
06847   } else if (Proto->isVariadic()) {
06848     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
06849     D.setInvalidType();
06850   }
06851 
06852   // Diagnose "&operator bool()" and other such nonsense.  This
06853   // is actually a gcc extension which we don't support.
06854   if (Proto->getReturnType() != ConvType) {
06855     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
06856         << Proto->getReturnType();
06857     D.setInvalidType();
06858     ConvType = Proto->getReturnType();
06859   }
06860 
06861   // C++ [class.conv.fct]p4:
06862   //   The conversion-type-id shall not represent a function type nor
06863   //   an array type.
06864   if (ConvType->isArrayType()) {
06865     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
06866     ConvType = Context.getPointerType(ConvType);
06867     D.setInvalidType();
06868   } else if (ConvType->isFunctionType()) {
06869     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
06870     ConvType = Context.getPointerType(ConvType);
06871     D.setInvalidType();
06872   }
06873 
06874   // Rebuild the function type "R" without any parameters (in case any
06875   // of the errors above fired) and with the conversion type as the
06876   // return type.
06877   if (D.isInvalidType())
06878     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
06879 
06880   // C++0x explicit conversion operators.
06881   if (D.getDeclSpec().isExplicitSpecified())
06882     Diag(D.getDeclSpec().getExplicitSpecLoc(),
06883          getLangOpts().CPlusPlus11 ?
06884            diag::warn_cxx98_compat_explicit_conversion_functions :
06885            diag::ext_explicit_conversion_functions)
06886       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
06887 }
06888 
06889 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
06890 /// the declaration of the given C++ conversion function. This routine
06891 /// is responsible for recording the conversion function in the C++
06892 /// class, if possible.
06893 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
06894   assert(Conversion && "Expected to receive a conversion function declaration");
06895 
06896   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
06897 
06898   // Make sure we aren't redeclaring the conversion function.
06899   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
06900 
06901   // C++ [class.conv.fct]p1:
06902   //   [...] A conversion function is never used to convert a
06903   //   (possibly cv-qualified) object to the (possibly cv-qualified)
06904   //   same object type (or a reference to it), to a (possibly
06905   //   cv-qualified) base class of that type (or a reference to it),
06906   //   or to (possibly cv-qualified) void.
06907   // FIXME: Suppress this warning if the conversion function ends up being a
06908   // virtual function that overrides a virtual function in a base class.
06909   QualType ClassType
06910     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
06911   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
06912     ConvType = ConvTypeRef->getPointeeType();
06913   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
06914       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
06915     /* Suppress diagnostics for instantiations. */;
06916   else if (ConvType->isRecordType()) {
06917     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
06918     if (ConvType == ClassType)
06919       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
06920         << ClassType;
06921     else if (IsDerivedFrom(ClassType, ConvType))
06922       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
06923         <<  ClassType << ConvType;
06924   } else if (ConvType->isVoidType()) {
06925     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
06926       << ClassType << ConvType;
06927   }
06928 
06929   if (FunctionTemplateDecl *ConversionTemplate
06930                                 = Conversion->getDescribedFunctionTemplate())
06931     return ConversionTemplate;
06932   
06933   return Conversion;
06934 }
06935 
06936 //===----------------------------------------------------------------------===//
06937 // Namespace Handling
06938 //===----------------------------------------------------------------------===//
06939 
06940 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
06941 /// reopened.
06942 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
06943                                             SourceLocation Loc,
06944                                             IdentifierInfo *II, bool *IsInline,
06945                                             NamespaceDecl *PrevNS) {
06946   assert(*IsInline != PrevNS->isInline());
06947 
06948   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
06949   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
06950   // inline namespaces, with the intention of bringing names into namespace std.
06951   //
06952   // We support this just well enough to get that case working; this is not
06953   // sufficient to support reopening namespaces as inline in general.
06954   if (*IsInline && II && II->getName().startswith("__atomic") &&
06955       S.getSourceManager().isInSystemHeader(Loc)) {
06956     // Mark all prior declarations of the namespace as inline.
06957     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
06958          NS = NS->getPreviousDecl())
06959       NS->setInline(*IsInline);
06960     // Patch up the lookup table for the containing namespace. This isn't really
06961     // correct, but it's good enough for this particular case.
06962     for (auto *I : PrevNS->decls())
06963       if (auto *ND = dyn_cast<NamedDecl>(I))
06964         PrevNS->getParent()->makeDeclVisibleInContext(ND);
06965     return;
06966   }
06967 
06968   if (PrevNS->isInline())
06969     // The user probably just forgot the 'inline', so suggest that it
06970     // be added back.
06971     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
06972       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
06973   else
06974     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
06975 
06976   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
06977   *IsInline = PrevNS->isInline();
06978 }
06979 
06980 /// ActOnStartNamespaceDef - This is called at the start of a namespace
06981 /// definition.
06982 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
06983                                    SourceLocation InlineLoc,
06984                                    SourceLocation NamespaceLoc,
06985                                    SourceLocation IdentLoc,
06986                                    IdentifierInfo *II,
06987                                    SourceLocation LBrace,
06988                                    AttributeList *AttrList) {
06989   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
06990   // For anonymous namespace, take the location of the left brace.
06991   SourceLocation Loc = II ? IdentLoc : LBrace;
06992   bool IsInline = InlineLoc.isValid();
06993   bool IsInvalid = false;
06994   bool IsStd = false;
06995   bool AddToKnown = false;
06996   Scope *DeclRegionScope = NamespcScope->getParent();
06997 
06998   NamespaceDecl *PrevNS = nullptr;
06999   if (II) {
07000     // C++ [namespace.def]p2:
07001     //   The identifier in an original-namespace-definition shall not
07002     //   have been previously defined in the declarative region in
07003     //   which the original-namespace-definition appears. The
07004     //   identifier in an original-namespace-definition is the name of
07005     //   the namespace. Subsequently in that declarative region, it is
07006     //   treated as an original-namespace-name.
07007     //
07008     // Since namespace names are unique in their scope, and we don't
07009     // look through using directives, just look for any ordinary names.
07010     
07011     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member | 
07012     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag | 
07013     Decl::IDNS_Namespace;
07014     NamedDecl *PrevDecl = nullptr;
07015     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
07016     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
07017          ++I) {
07018       if ((*I)->getIdentifierNamespace() & IDNS) {
07019         PrevDecl = *I;
07020         break;
07021       }
07022     }
07023     
07024     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
07025     
07026     if (PrevNS) {
07027       // This is an extended namespace definition.
07028       if (IsInline != PrevNS->isInline())
07029         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
07030                                         &IsInline, PrevNS);
07031     } else if (PrevDecl) {
07032       // This is an invalid name redefinition.
07033       Diag(Loc, diag::err_redefinition_different_kind)
07034         << II;
07035       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
07036       IsInvalid = true;
07037       // Continue on to push Namespc as current DeclContext and return it.
07038     } else if (II->isStr("std") &&
07039                CurContext->getRedeclContext()->isTranslationUnit()) {
07040       // This is the first "real" definition of the namespace "std", so update
07041       // our cache of the "std" namespace to point at this definition.
07042       PrevNS = getStdNamespace();
07043       IsStd = true;
07044       AddToKnown = !IsInline;
07045     } else {
07046       // We've seen this namespace for the first time.
07047       AddToKnown = !IsInline;
07048     }
07049   } else {
07050     // Anonymous namespaces.
07051     
07052     // Determine whether the parent already has an anonymous namespace.
07053     DeclContext *Parent = CurContext->getRedeclContext();
07054     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
07055       PrevNS = TU->getAnonymousNamespace();
07056     } else {
07057       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
07058       PrevNS = ND->getAnonymousNamespace();
07059     }
07060 
07061     if (PrevNS && IsInline != PrevNS->isInline())
07062       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
07063                                       &IsInline, PrevNS);
07064   }
07065   
07066   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
07067                                                  StartLoc, Loc, II, PrevNS);
07068   if (IsInvalid)
07069     Namespc->setInvalidDecl();
07070   
07071   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
07072 
07073   // FIXME: Should we be merging attributes?
07074   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
07075     PushNamespaceVisibilityAttr(Attr, Loc);
07076 
07077   if (IsStd)
07078     StdNamespace = Namespc;
07079   if (AddToKnown)
07080     KnownNamespaces[Namespc] = false;
07081   
07082   if (II) {
07083     PushOnScopeChains(Namespc, DeclRegionScope);
07084   } else {
07085     // Link the anonymous namespace into its parent.
07086     DeclContext *Parent = CurContext->getRedeclContext();
07087     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
07088       TU->setAnonymousNamespace(Namespc);
07089     } else {
07090       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
07091     }
07092 
07093     CurContext->addDecl(Namespc);
07094 
07095     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
07096     //   behaves as if it were replaced by
07097     //     namespace unique { /* empty body */ }
07098     //     using namespace unique;
07099     //     namespace unique { namespace-body }
07100     //   where all occurrences of 'unique' in a translation unit are
07101     //   replaced by the same identifier and this identifier differs
07102     //   from all other identifiers in the entire program.
07103 
07104     // We just create the namespace with an empty name and then add an
07105     // implicit using declaration, just like the standard suggests.
07106     //
07107     // CodeGen enforces the "universally unique" aspect by giving all
07108     // declarations semantically contained within an anonymous
07109     // namespace internal linkage.
07110 
07111     if (!PrevNS) {
07112       UsingDirectiveDecl* UD
07113         = UsingDirectiveDecl::Create(Context, Parent,
07114                                      /* 'using' */ LBrace,
07115                                      /* 'namespace' */ SourceLocation(),
07116                                      /* qualifier */ NestedNameSpecifierLoc(),
07117                                      /* identifier */ SourceLocation(),
07118                                      Namespc,
07119                                      /* Ancestor */ Parent);
07120       UD->setImplicit();
07121       Parent->addDecl(UD);
07122     }
07123   }
07124 
07125   ActOnDocumentableDecl(Namespc);
07126 
07127   // Although we could have an invalid decl (i.e. the namespace name is a
07128   // redefinition), push it as current DeclContext and try to continue parsing.
07129   // FIXME: We should be able to push Namespc here, so that the each DeclContext
07130   // for the namespace has the declarations that showed up in that particular
07131   // namespace definition.
07132   PushDeclContext(NamespcScope, Namespc);
07133   return Namespc;
07134 }
07135 
07136 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
07137 /// is a namespace alias, returns the namespace it points to.
07138 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
07139   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
07140     return AD->getNamespace();
07141   return dyn_cast_or_null<NamespaceDecl>(D);
07142 }
07143 
07144 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
07145 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
07146 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
07147   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
07148   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
07149   Namespc->setRBraceLoc(RBrace);
07150   PopDeclContext();
07151   if (Namespc->hasAttr<VisibilityAttr>())
07152     PopPragmaVisibility(true, RBrace);
07153 }
07154 
07155 CXXRecordDecl *Sema::getStdBadAlloc() const {
07156   return cast_or_null<CXXRecordDecl>(
07157                                   StdBadAlloc.get(Context.getExternalSource()));
07158 }
07159 
07160 NamespaceDecl *Sema::getStdNamespace() const {
07161   return cast_or_null<NamespaceDecl>(
07162                                  StdNamespace.get(Context.getExternalSource()));
07163 }
07164 
07165 /// \brief Retrieve the special "std" namespace, which may require us to 
07166 /// implicitly define the namespace.
07167 NamespaceDecl *Sema::getOrCreateStdNamespace() {
07168   if (!StdNamespace) {
07169     // The "std" namespace has not yet been defined, so build one implicitly.
07170     StdNamespace = NamespaceDecl::Create(Context, 
07171                                          Context.getTranslationUnitDecl(),
07172                                          /*Inline=*/false,
07173                                          SourceLocation(), SourceLocation(),
07174                                          &PP.getIdentifierTable().get("std"),
07175                                          /*PrevDecl=*/nullptr);
07176     getStdNamespace()->setImplicit(true);
07177   }
07178 
07179   return getStdNamespace();
07180 }
07181 
07182 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
07183   assert(getLangOpts().CPlusPlus &&
07184          "Looking for std::initializer_list outside of C++.");
07185 
07186   // We're looking for implicit instantiations of
07187   // template <typename E> class std::initializer_list.
07188 
07189   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
07190     return false;
07191 
07192   ClassTemplateDecl *Template = nullptr;
07193   const TemplateArgument *Arguments = nullptr;
07194 
07195   if (const RecordType *RT = Ty->getAs<RecordType>()) {
07196 
07197     ClassTemplateSpecializationDecl *Specialization =
07198         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
07199     if (!Specialization)
07200       return false;
07201 
07202     Template = Specialization->getSpecializedTemplate();
07203     Arguments = Specialization->getTemplateArgs().data();
07204   } else if (const TemplateSpecializationType *TST =
07205                  Ty->getAs<TemplateSpecializationType>()) {
07206     Template = dyn_cast_or_null<ClassTemplateDecl>(
07207         TST->getTemplateName().getAsTemplateDecl());
07208     Arguments = TST->getArgs();
07209   }
07210   if (!Template)
07211     return false;
07212 
07213   if (!StdInitializerList) {
07214     // Haven't recognized std::initializer_list yet, maybe this is it.
07215     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
07216     if (TemplateClass->getIdentifier() !=
07217             &PP.getIdentifierTable().get("initializer_list") ||
07218         !getStdNamespace()->InEnclosingNamespaceSetOf(
07219             TemplateClass->getDeclContext()))
07220       return false;
07221     // This is a template called std::initializer_list, but is it the right
07222     // template?
07223     TemplateParameterList *Params = Template->getTemplateParameters();
07224     if (Params->getMinRequiredArguments() != 1)
07225       return false;
07226     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
07227       return false;
07228 
07229     // It's the right template.
07230     StdInitializerList = Template;
07231   }
07232 
07233   if (Template != StdInitializerList)
07234     return false;
07235 
07236   // This is an instance of std::initializer_list. Find the argument type.
07237   if (Element)
07238     *Element = Arguments[0].getAsType();
07239   return true;
07240 }
07241 
07242 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
07243   NamespaceDecl *Std = S.getStdNamespace();
07244   if (!Std) {
07245     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
07246     return nullptr;
07247   }
07248 
07249   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
07250                       Loc, Sema::LookupOrdinaryName);
07251   if (!S.LookupQualifiedName(Result, Std)) {
07252     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
07253     return nullptr;
07254   }
07255   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
07256   if (!Template) {
07257     Result.suppressDiagnostics();
07258     // We found something weird. Complain about the first thing we found.
07259     NamedDecl *Found = *Result.begin();
07260     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
07261     return nullptr;
07262   }
07263 
07264   // We found some template called std::initializer_list. Now verify that it's
07265   // correct.
07266   TemplateParameterList *Params = Template->getTemplateParameters();
07267   if (Params->getMinRequiredArguments() != 1 ||
07268       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
07269     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
07270     return nullptr;
07271   }
07272 
07273   return Template;
07274 }
07275 
07276 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
07277   if (!StdInitializerList) {
07278     StdInitializerList = LookupStdInitializerList(*this, Loc);
07279     if (!StdInitializerList)
07280       return QualType();
07281   }
07282 
07283   TemplateArgumentListInfo Args(Loc, Loc);
07284   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
07285                                        Context.getTrivialTypeSourceInfo(Element,
07286                                                                         Loc)));
07287   return Context.getCanonicalType(
07288       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
07289 }
07290 
07291 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
07292   // C++ [dcl.init.list]p2:
07293   //   A constructor is an initializer-list constructor if its first parameter
07294   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
07295   //   std::initializer_list<E> for some type E, and either there are no other
07296   //   parameters or else all other parameters have default arguments.
07297   if (Ctor->getNumParams() < 1 ||
07298       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
07299     return false;
07300 
07301   QualType ArgType = Ctor->getParamDecl(0)->getType();
07302   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
07303     ArgType = RT->getPointeeType().getUnqualifiedType();
07304 
07305   return isStdInitializerList(ArgType, nullptr);
07306 }
07307 
07308 /// \brief Determine whether a using statement is in a context where it will be
07309 /// apply in all contexts.
07310 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
07311   switch (CurContext->getDeclKind()) {
07312     case Decl::TranslationUnit:
07313       return true;
07314     case Decl::LinkageSpec:
07315       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
07316     default:
07317       return false;
07318   }
07319 }
07320 
07321 namespace {
07322 
07323 // Callback to only accept typo corrections that are namespaces.
07324 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
07325 public:
07326   bool ValidateCandidate(const TypoCorrection &candidate) override {
07327     if (NamedDecl *ND = candidate.getCorrectionDecl())
07328       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
07329     return false;
07330   }
07331 };
07332 
07333 }
07334 
07335 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
07336                                        CXXScopeSpec &SS,
07337                                        SourceLocation IdentLoc,
07338                                        IdentifierInfo *Ident) {
07339   R.clear();
07340   if (TypoCorrection Corrected =
07341           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
07342                         llvm::make_unique<NamespaceValidatorCCC>(),
07343                         Sema::CTK_ErrorRecovery)) {
07344     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
07345       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
07346       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
07347                               Ident->getName().equals(CorrectedStr);
07348       S.diagnoseTypo(Corrected,
07349                      S.PDiag(diag::err_using_directive_member_suggest)
07350                        << Ident << DC << DroppedSpecifier << SS.getRange(),
07351                      S.PDiag(diag::note_namespace_defined_here));
07352     } else {
07353       S.diagnoseTypo(Corrected,
07354                      S.PDiag(diag::err_using_directive_suggest) << Ident,
07355                      S.PDiag(diag::note_namespace_defined_here));
07356     }
07357     R.addDecl(Corrected.getCorrectionDecl());
07358     return true;
07359   }
07360   return false;
07361 }
07362 
07363 Decl *Sema::ActOnUsingDirective(Scope *S,
07364                                           SourceLocation UsingLoc,
07365                                           SourceLocation NamespcLoc,
07366                                           CXXScopeSpec &SS,
07367                                           SourceLocation IdentLoc,
07368                                           IdentifierInfo *NamespcName,
07369                                           AttributeList *AttrList) {
07370   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
07371   assert(NamespcName && "Invalid NamespcName.");
07372   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
07373 
07374   // This can only happen along a recovery path.
07375   while (S->getFlags() & Scope::TemplateParamScope)
07376     S = S->getParent();
07377   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
07378 
07379   UsingDirectiveDecl *UDir = nullptr;
07380   NestedNameSpecifier *Qualifier = nullptr;
07381   if (SS.isSet())
07382     Qualifier = SS.getScopeRep();
07383   
07384   // Lookup namespace name.
07385   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
07386   LookupParsedName(R, S, &SS);
07387   if (R.isAmbiguous())
07388     return nullptr;
07389 
07390   if (R.empty()) {
07391     R.clear();
07392     // Allow "using namespace std;" or "using namespace ::std;" even if 
07393     // "std" hasn't been defined yet, for GCC compatibility.
07394     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
07395         NamespcName->isStr("std")) {
07396       Diag(IdentLoc, diag::ext_using_undefined_std);
07397       R.addDecl(getOrCreateStdNamespace());
07398       R.resolveKind();
07399     } 
07400     // Otherwise, attempt typo correction.
07401     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
07402   }
07403   
07404   if (!R.empty()) {
07405     NamedDecl *Named = R.getFoundDecl();
07406     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
07407         && "expected namespace decl");
07408 
07409     // The use of a nested name specifier may trigger deprecation warnings.
07410     DiagnoseUseOfDecl(Named, IdentLoc);
07411 
07412     // C++ [namespace.udir]p1:
07413     //   A using-directive specifies that the names in the nominated
07414     //   namespace can be used in the scope in which the
07415     //   using-directive appears after the using-directive. During
07416     //   unqualified name lookup (3.4.1), the names appear as if they
07417     //   were declared in the nearest enclosing namespace which
07418     //   contains both the using-directive and the nominated
07419     //   namespace. [Note: in this context, "contains" means "contains
07420     //   directly or indirectly". ]
07421 
07422     // Find enclosing context containing both using-directive and
07423     // nominated namespace.
07424     NamespaceDecl *NS = getNamespaceDecl(Named);
07425     DeclContext *CommonAncestor = cast<DeclContext>(NS);
07426     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
07427       CommonAncestor = CommonAncestor->getParent();
07428 
07429     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
07430                                       SS.getWithLocInContext(Context),
07431                                       IdentLoc, Named, CommonAncestor);
07432 
07433     if (IsUsingDirectiveInToplevelContext(CurContext) &&
07434         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
07435       Diag(IdentLoc, diag::warn_using_directive_in_header);
07436     }
07437 
07438     PushUsingDirective(S, UDir);
07439   } else {
07440     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
07441   }
07442 
07443   if (UDir)
07444     ProcessDeclAttributeList(S, UDir, AttrList);
07445 
07446   return UDir;
07447 }
07448 
07449 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
07450   // If the scope has an associated entity and the using directive is at
07451   // namespace or translation unit scope, add the UsingDirectiveDecl into
07452   // its lookup structure so qualified name lookup can find it.
07453   DeclContext *Ctx = S->getEntity();
07454   if (Ctx && !Ctx->isFunctionOrMethod())
07455     Ctx->addDecl(UDir);
07456   else
07457     // Otherwise, it is at block scope. The using-directives will affect lookup
07458     // only to the end of the scope.
07459     S->PushUsingDirective(UDir);
07460 }
07461 
07462 
07463 Decl *Sema::ActOnUsingDeclaration(Scope *S,
07464                                   AccessSpecifier AS,
07465                                   bool HasUsingKeyword,
07466                                   SourceLocation UsingLoc,
07467                                   CXXScopeSpec &SS,
07468                                   UnqualifiedId &Name,
07469                                   AttributeList *AttrList,
07470                                   bool HasTypenameKeyword,
07471                                   SourceLocation TypenameLoc) {
07472   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
07473 
07474   switch (Name.getKind()) {
07475   case UnqualifiedId::IK_ImplicitSelfParam:
07476   case UnqualifiedId::IK_Identifier:
07477   case UnqualifiedId::IK_OperatorFunctionId:
07478   case UnqualifiedId::IK_LiteralOperatorId:
07479   case UnqualifiedId::IK_ConversionFunctionId:
07480     break;
07481       
07482   case UnqualifiedId::IK_ConstructorName:
07483   case UnqualifiedId::IK_ConstructorTemplateId:
07484     // C++11 inheriting constructors.
07485     Diag(Name.getLocStart(),
07486          getLangOpts().CPlusPlus11 ?
07487            diag::warn_cxx98_compat_using_decl_constructor :
07488            diag::err_using_decl_constructor)
07489       << SS.getRange();
07490 
07491     if (getLangOpts().CPlusPlus11) break;
07492 
07493     return nullptr;
07494 
07495   case UnqualifiedId::IK_DestructorName:
07496     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
07497       << SS.getRange();
07498     return nullptr;
07499 
07500   case UnqualifiedId::IK_TemplateId:
07501     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
07502       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
07503     return nullptr;
07504   }
07505 
07506   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
07507   DeclarationName TargetName = TargetNameInfo.getName();
07508   if (!TargetName)
07509     return nullptr;
07510 
07511   // Warn about access declarations.
07512   if (!HasUsingKeyword) {
07513     Diag(Name.getLocStart(),
07514          getLangOpts().CPlusPlus11 ? diag::err_access_decl
07515                                    : diag::warn_access_decl_deprecated)
07516       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
07517   }
07518 
07519   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
07520       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
07521     return nullptr;
07522 
07523   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
07524                                         TargetNameInfo, AttrList,
07525                                         /* IsInstantiation */ false,
07526                                         HasTypenameKeyword, TypenameLoc);
07527   if (UD)
07528     PushOnScopeChains(UD, S, /*AddToContext*/ false);
07529 
07530   return UD;
07531 }
07532 
07533 /// \brief Determine whether a using declaration considers the given
07534 /// declarations as "equivalent", e.g., if they are redeclarations of
07535 /// the same entity or are both typedefs of the same type.
07536 static bool
07537 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
07538   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
07539     return true;
07540 
07541   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
07542     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
07543       return Context.hasSameType(TD1->getUnderlyingType(),
07544                                  TD2->getUnderlyingType());
07545 
07546   return false;
07547 }
07548 
07549 
07550 /// Determines whether to create a using shadow decl for a particular
07551 /// decl, given the set of decls existing prior to this using lookup.
07552 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
07553                                 const LookupResult &Previous,
07554                                 UsingShadowDecl *&PrevShadow) {
07555   // Diagnose finding a decl which is not from a base class of the
07556   // current class.  We do this now because there are cases where this
07557   // function will silently decide not to build a shadow decl, which
07558   // will pre-empt further diagnostics.
07559   //
07560   // We don't need to do this in C++0x because we do the check once on
07561   // the qualifier.
07562   //
07563   // FIXME: diagnose the following if we care enough:
07564   //   struct A { int foo; };
07565   //   struct B : A { using A::foo; };
07566   //   template <class T> struct C : A {};
07567   //   template <class T> struct D : C<T> { using B::foo; } // <---
07568   // This is invalid (during instantiation) in C++03 because B::foo
07569   // resolves to the using decl in B, which is not a base class of D<T>.
07570   // We can't diagnose it immediately because C<T> is an unknown
07571   // specialization.  The UsingShadowDecl in D<T> then points directly
07572   // to A::foo, which will look well-formed when we instantiate.
07573   // The right solution is to not collapse the shadow-decl chain.
07574   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
07575     DeclContext *OrigDC = Orig->getDeclContext();
07576 
07577     // Handle enums and anonymous structs.
07578     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
07579     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
07580     while (OrigRec->isAnonymousStructOrUnion())
07581       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
07582 
07583     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
07584       if (OrigDC == CurContext) {
07585         Diag(Using->getLocation(),
07586              diag::err_using_decl_nested_name_specifier_is_current_class)
07587           << Using->getQualifierLoc().getSourceRange();
07588         Diag(Orig->getLocation(), diag::note_using_decl_target);
07589         return true;
07590       }
07591 
07592       Diag(Using->getQualifierLoc().getBeginLoc(),
07593            diag::err_using_decl_nested_name_specifier_is_not_base_class)
07594         << Using->getQualifier()
07595         << cast<CXXRecordDecl>(CurContext)
07596         << Using->getQualifierLoc().getSourceRange();
07597       Diag(Orig->getLocation(), diag::note_using_decl_target);
07598       return true;
07599     }
07600   }
07601 
07602   if (Previous.empty()) return false;
07603 
07604   NamedDecl *Target = Orig;
07605   if (isa<UsingShadowDecl>(Target))
07606     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
07607 
07608   // If the target happens to be one of the previous declarations, we
07609   // don't have a conflict.
07610   // 
07611   // FIXME: but we might be increasing its access, in which case we
07612   // should redeclare it.
07613   NamedDecl *NonTag = nullptr, *Tag = nullptr;
07614   bool FoundEquivalentDecl = false;
07615   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
07616          I != E; ++I) {
07617     NamedDecl *D = (*I)->getUnderlyingDecl();
07618     if (IsEquivalentForUsingDecl(Context, D, Target)) {
07619       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
07620         PrevShadow = Shadow;
07621       FoundEquivalentDecl = true;
07622     }
07623 
07624     (isa<TagDecl>(D) ? Tag : NonTag) = D;
07625   }
07626 
07627   if (FoundEquivalentDecl)
07628     return false;
07629 
07630   if (FunctionDecl *FD = Target->getAsFunction()) {
07631     NamedDecl *OldDecl = nullptr;
07632     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
07633                           /*IsForUsingDecl*/ true)) {
07634     case Ovl_Overload:
07635       return false;
07636 
07637     case Ovl_NonFunction:
07638       Diag(Using->getLocation(), diag::err_using_decl_conflict);
07639       break;
07640 
07641     // We found a decl with the exact signature.
07642     case Ovl_Match:
07643       // If we're in a record, we want to hide the target, so we
07644       // return true (without a diagnostic) to tell the caller not to
07645       // build a shadow decl.
07646       if (CurContext->isRecord())
07647         return true;
07648 
07649       // If we're not in a record, this is an error.
07650       Diag(Using->getLocation(), diag::err_using_decl_conflict);
07651       break;
07652     }
07653 
07654     Diag(Target->getLocation(), diag::note_using_decl_target);
07655     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
07656     return true;
07657   }
07658 
07659   // Target is not a function.
07660 
07661   if (isa<TagDecl>(Target)) {
07662     // No conflict between a tag and a non-tag.
07663     if (!Tag) return false;
07664 
07665     Diag(Using->getLocation(), diag::err_using_decl_conflict);
07666     Diag(Target->getLocation(), diag::note_using_decl_target);
07667     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
07668     return true;
07669   }
07670 
07671   // No conflict between a tag and a non-tag.
07672   if (!NonTag) return false;
07673 
07674   Diag(Using->getLocation(), diag::err_using_decl_conflict);
07675   Diag(Target->getLocation(), diag::note_using_decl_target);
07676   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
07677   return true;
07678 }
07679 
07680 /// Builds a shadow declaration corresponding to a 'using' declaration.
07681 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
07682                                             UsingDecl *UD,
07683                                             NamedDecl *Orig,
07684                                             UsingShadowDecl *PrevDecl) {
07685 
07686   // If we resolved to another shadow declaration, just coalesce them.
07687   NamedDecl *Target = Orig;
07688   if (isa<UsingShadowDecl>(Target)) {
07689     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
07690     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
07691   }
07692 
07693   UsingShadowDecl *Shadow
07694     = UsingShadowDecl::Create(Context, CurContext,
07695                               UD->getLocation(), UD, Target);
07696   UD->addShadowDecl(Shadow);
07697 
07698   Shadow->setAccess(UD->getAccess());
07699   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
07700     Shadow->setInvalidDecl();
07701 
07702   Shadow->setPreviousDecl(PrevDecl);
07703 
07704   if (S)
07705     PushOnScopeChains(Shadow, S);
07706   else
07707     CurContext->addDecl(Shadow);
07708 
07709 
07710   return Shadow;
07711 }
07712 
07713 /// Hides a using shadow declaration.  This is required by the current
07714 /// using-decl implementation when a resolvable using declaration in a
07715 /// class is followed by a declaration which would hide or override
07716 /// one or more of the using decl's targets; for example:
07717 ///
07718 ///   struct Base { void foo(int); };
07719 ///   struct Derived : Base {
07720 ///     using Base::foo;
07721 ///     void foo(int);
07722 ///   };
07723 ///
07724 /// The governing language is C++03 [namespace.udecl]p12:
07725 ///
07726 ///   When a using-declaration brings names from a base class into a
07727 ///   derived class scope, member functions in the derived class
07728 ///   override and/or hide member functions with the same name and
07729 ///   parameter types in a base class (rather than conflicting).
07730 ///
07731 /// There are two ways to implement this:
07732 ///   (1) optimistically create shadow decls when they're not hidden
07733 ///       by existing declarations, or
07734 ///   (2) don't create any shadow decls (or at least don't make them
07735 ///       visible) until we've fully parsed/instantiated the class.
07736 /// The problem with (1) is that we might have to retroactively remove
07737 /// a shadow decl, which requires several O(n) operations because the
07738 /// decl structures are (very reasonably) not designed for removal.
07739 /// (2) avoids this but is very fiddly and phase-dependent.
07740 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
07741   if (Shadow->getDeclName().getNameKind() ==
07742         DeclarationName::CXXConversionFunctionName)
07743     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
07744 
07745   // Remove it from the DeclContext...
07746   Shadow->getDeclContext()->removeDecl(Shadow);
07747 
07748   // ...and the scope, if applicable...
07749   if (S) {
07750     S->RemoveDecl(Shadow);
07751     IdResolver.RemoveDecl(Shadow);
07752   }
07753 
07754   // ...and the using decl.
07755   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
07756 
07757   // TODO: complain somehow if Shadow was used.  It shouldn't
07758   // be possible for this to happen, because...?
07759 }
07760 
07761 /// Find the base specifier for a base class with the given type.
07762 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
07763                                                 QualType DesiredBase,
07764                                                 bool &AnyDependentBases) {
07765   // Check whether the named type is a direct base class.
07766   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
07767   for (auto &Base : Derived->bases()) {
07768     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
07769     if (CanonicalDesiredBase == BaseType)
07770       return &Base;
07771     if (BaseType->isDependentType())
07772       AnyDependentBases = true;
07773   }
07774   return nullptr;
07775 }
07776 
07777 namespace {
07778 class UsingValidatorCCC : public CorrectionCandidateCallback {
07779 public:
07780   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
07781                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
07782       : HasTypenameKeyword(HasTypenameKeyword),
07783         IsInstantiation(IsInstantiation), OldNNS(NNS),
07784         RequireMemberOf(RequireMemberOf) {}
07785 
07786   bool ValidateCandidate(const TypoCorrection &Candidate) override {
07787     NamedDecl *ND = Candidate.getCorrectionDecl();
07788 
07789     // Keywords are not valid here.
07790     if (!ND || isa<NamespaceDecl>(ND))
07791       return false;
07792 
07793     // Completely unqualified names are invalid for a 'using' declaration.
07794     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
07795       return false;
07796 
07797     if (RequireMemberOf) {
07798       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
07799       if (FoundRecord && FoundRecord->isInjectedClassName()) {
07800         // No-one ever wants a using-declaration to name an injected-class-name
07801         // of a base class, unless they're declaring an inheriting constructor.
07802         ASTContext &Ctx = ND->getASTContext();
07803         if (!Ctx.getLangOpts().CPlusPlus11)
07804           return false;
07805         QualType FoundType = Ctx.getRecordType(FoundRecord);
07806 
07807         // Check that the injected-class-name is named as a member of its own
07808         // type; we don't want to suggest 'using Derived::Base;', since that
07809         // means something else.
07810         NestedNameSpecifier *Specifier =
07811             Candidate.WillReplaceSpecifier()
07812                 ? Candidate.getCorrectionSpecifier()
07813                 : OldNNS;
07814         if (!Specifier->getAsType() ||
07815             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
07816           return false;
07817 
07818         // Check that this inheriting constructor declaration actually names a
07819         // direct base class of the current class.
07820         bool AnyDependentBases = false;
07821         if (!findDirectBaseWithType(RequireMemberOf,
07822                                     Ctx.getRecordType(FoundRecord),
07823                                     AnyDependentBases) &&
07824             !AnyDependentBases)
07825           return false;
07826       } else {
07827         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
07828         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
07829           return false;
07830 
07831         // FIXME: Check that the base class member is accessible?
07832       }
07833     }
07834 
07835     if (isa<TypeDecl>(ND))
07836       return HasTypenameKeyword || !IsInstantiation;
07837 
07838     return !HasTypenameKeyword;
07839   }
07840 
07841 private:
07842   bool HasTypenameKeyword;
07843   bool IsInstantiation;
07844   NestedNameSpecifier *OldNNS;
07845   CXXRecordDecl *RequireMemberOf;
07846 };
07847 } // end anonymous namespace
07848 
07849 /// Builds a using declaration.
07850 ///
07851 /// \param IsInstantiation - Whether this call arises from an
07852 ///   instantiation of an unresolved using declaration.  We treat
07853 ///   the lookup differently for these declarations.
07854 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
07855                                        SourceLocation UsingLoc,
07856                                        CXXScopeSpec &SS,
07857                                        DeclarationNameInfo NameInfo,
07858                                        AttributeList *AttrList,
07859                                        bool IsInstantiation,
07860                                        bool HasTypenameKeyword,
07861                                        SourceLocation TypenameLoc) {
07862   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
07863   SourceLocation IdentLoc = NameInfo.getLoc();
07864   assert(IdentLoc.isValid() && "Invalid TargetName location.");
07865 
07866   // FIXME: We ignore attributes for now.
07867 
07868   if (SS.isEmpty()) {
07869     Diag(IdentLoc, diag::err_using_requires_qualname);
07870     return nullptr;
07871   }
07872 
07873   // Do the redeclaration lookup in the current scope.
07874   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
07875                         ForRedeclaration);
07876   Previous.setHideTags(false);
07877   if (S) {
07878     LookupName(Previous, S);
07879 
07880     // It is really dumb that we have to do this.
07881     LookupResult::Filter F = Previous.makeFilter();
07882     while (F.hasNext()) {
07883       NamedDecl *D = F.next();
07884       if (!isDeclInScope(D, CurContext, S))
07885         F.erase();
07886       // If we found a local extern declaration that's not ordinarily visible,
07887       // and this declaration is being added to a non-block scope, ignore it.
07888       // We're only checking for scope conflicts here, not also for violations
07889       // of the linkage rules.
07890       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
07891                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
07892         F.erase();
07893     }
07894     F.done();
07895   } else {
07896     assert(IsInstantiation && "no scope in non-instantiation");
07897     assert(CurContext->isRecord() && "scope not record in instantiation");
07898     LookupQualifiedName(Previous, CurContext);
07899   }
07900 
07901   // Check for invalid redeclarations.
07902   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
07903                                   SS, IdentLoc, Previous))
07904     return nullptr;
07905 
07906   // Check for bad qualifiers.
07907   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
07908     return nullptr;
07909 
07910   DeclContext *LookupContext = computeDeclContext(SS);
07911   NamedDecl *D;
07912   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
07913   if (!LookupContext) {
07914     if (HasTypenameKeyword) {
07915       // FIXME: not all declaration name kinds are legal here
07916       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
07917                                               UsingLoc, TypenameLoc,
07918                                               QualifierLoc,
07919                                               IdentLoc, NameInfo.getName());
07920     } else {
07921       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 
07922                                            QualifierLoc, NameInfo);
07923     }
07924     D->setAccess(AS);
07925     CurContext->addDecl(D);
07926     return D;
07927   }
07928 
07929   auto Build = [&](bool Invalid) {
07930     UsingDecl *UD =
07931         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
07932                           HasTypenameKeyword);
07933     UD->setAccess(AS);
07934     CurContext->addDecl(UD);
07935     UD->setInvalidDecl(Invalid);
07936     return UD;
07937   };
07938   auto BuildInvalid = [&]{ return Build(true); };
07939   auto BuildValid = [&]{ return Build(false); };
07940 
07941   if (RequireCompleteDeclContext(SS, LookupContext))
07942     return BuildInvalid();
07943 
07944   // The normal rules do not apply to inheriting constructor declarations.
07945   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
07946     UsingDecl *UD = BuildValid();
07947     CheckInheritingConstructorUsingDecl(UD);
07948     return UD;
07949   }
07950 
07951   // Otherwise, look up the target name.
07952 
07953   LookupResult R(*this, NameInfo, LookupOrdinaryName);
07954 
07955   // Unlike most lookups, we don't always want to hide tag
07956   // declarations: tag names are visible through the using declaration
07957   // even if hidden by ordinary names, *except* in a dependent context
07958   // where it's important for the sanity of two-phase lookup.
07959   if (!IsInstantiation)
07960     R.setHideTags(false);
07961 
07962   // For the purposes of this lookup, we have a base object type
07963   // equal to that of the current context.
07964   if (CurContext->isRecord()) {
07965     R.setBaseObjectType(
07966                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
07967   }
07968 
07969   LookupQualifiedName(R, LookupContext);
07970 
07971   // Try to correct typos if possible.
07972   if (R.empty()) {
07973     if (TypoCorrection Corrected = CorrectTypo(
07974             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
07975             llvm::make_unique<UsingValidatorCCC>(
07976                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
07977                 dyn_cast<CXXRecordDecl>(CurContext)),
07978             CTK_ErrorRecovery)) {
07979       // We reject any correction for which ND would be NULL.
07980       NamedDecl *ND = Corrected.getCorrectionDecl();
07981 
07982       // We reject candidates where DroppedSpecifier == true, hence the
07983       // literal '0' below.
07984       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
07985                                 << NameInfo.getName() << LookupContext << 0
07986                                 << SS.getRange());
07987 
07988       // If we corrected to an inheriting constructor, handle it as one.
07989       auto *RD = dyn_cast<CXXRecordDecl>(ND);
07990       if (RD && RD->isInjectedClassName()) {
07991         // Fix up the information we'll use to build the using declaration.
07992         if (Corrected.WillReplaceSpecifier()) {
07993           NestedNameSpecifierLocBuilder Builder;
07994           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
07995                               QualifierLoc.getSourceRange());
07996           QualifierLoc = Builder.getWithLocInContext(Context);
07997         }
07998 
07999         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
08000             Context.getCanonicalType(Context.getRecordType(RD))));
08001         NameInfo.setNamedTypeInfo(nullptr);
08002 
08003         // Build it and process it as an inheriting constructor.
08004         UsingDecl *UD = BuildValid();
08005         CheckInheritingConstructorUsingDecl(UD);
08006         return UD;
08007       }
08008 
08009       // FIXME: Pick up all the declarations if we found an overloaded function.
08010       R.setLookupName(Corrected.getCorrection());
08011       R.addDecl(ND);
08012     } else {
08013       Diag(IdentLoc, diag::err_no_member)
08014         << NameInfo.getName() << LookupContext << SS.getRange();
08015       return BuildInvalid();
08016     }
08017   }
08018 
08019   if (R.isAmbiguous())
08020     return BuildInvalid();
08021 
08022   if (HasTypenameKeyword) {
08023     // If we asked for a typename and got a non-type decl, error out.
08024     if (!R.getAsSingle<TypeDecl>()) {
08025       Diag(IdentLoc, diag::err_using_typename_non_type);
08026       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
08027         Diag((*I)->getUnderlyingDecl()->getLocation(),
08028              diag::note_using_decl_target);
08029       return BuildInvalid();
08030     }
08031   } else {
08032     // If we asked for a non-typename and we got a type, error out,
08033     // but only if this is an instantiation of an unresolved using
08034     // decl.  Otherwise just silently find the type name.
08035     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
08036       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
08037       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
08038       return BuildInvalid();
08039     }
08040   }
08041 
08042   // C++0x N2914 [namespace.udecl]p6:
08043   // A using-declaration shall not name a namespace.
08044   if (R.getAsSingle<NamespaceDecl>()) {
08045     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
08046       << SS.getRange();
08047     return BuildInvalid();
08048   }
08049 
08050   UsingDecl *UD = BuildValid();
08051   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
08052     UsingShadowDecl *PrevDecl = nullptr;
08053     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
08054       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
08055   }
08056 
08057   return UD;
08058 }
08059 
08060 /// Additional checks for a using declaration referring to a constructor name.
08061 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
08062   assert(!UD->hasTypename() && "expecting a constructor name");
08063 
08064   const Type *SourceType = UD->getQualifier()->getAsType();
08065   assert(SourceType &&
08066          "Using decl naming constructor doesn't have type in scope spec.");
08067   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
08068 
08069   // Check whether the named type is a direct base class.
08070   bool AnyDependentBases = false;
08071   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
08072                                       AnyDependentBases);
08073   if (!Base && !AnyDependentBases) {
08074     Diag(UD->getUsingLoc(),
08075          diag::err_using_decl_constructor_not_in_direct_base)
08076       << UD->getNameInfo().getSourceRange()
08077       << QualType(SourceType, 0) << TargetClass;
08078     UD->setInvalidDecl();
08079     return true;
08080   }
08081 
08082   if (Base)
08083     Base->setInheritConstructors();
08084 
08085   return false;
08086 }
08087 
08088 /// Checks that the given using declaration is not an invalid
08089 /// redeclaration.  Note that this is checking only for the using decl
08090 /// itself, not for any ill-formedness among the UsingShadowDecls.
08091 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
08092                                        bool HasTypenameKeyword,
08093                                        const CXXScopeSpec &SS,
08094                                        SourceLocation NameLoc,
08095                                        const LookupResult &Prev) {
08096   // C++03 [namespace.udecl]p8:
08097   // C++0x [namespace.udecl]p10:
08098   //   A using-declaration is a declaration and can therefore be used
08099   //   repeatedly where (and only where) multiple declarations are
08100   //   allowed.
08101   //
08102   // That's in non-member contexts.
08103   if (!CurContext->getRedeclContext()->isRecord())
08104     return false;
08105 
08106   NestedNameSpecifier *Qual = SS.getScopeRep();
08107 
08108   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
08109     NamedDecl *D = *I;
08110 
08111     bool DTypename;
08112     NestedNameSpecifier *DQual;
08113     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
08114       DTypename = UD->hasTypename();
08115       DQual = UD->getQualifier();
08116     } else if (UnresolvedUsingValueDecl *UD
08117                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
08118       DTypename = false;
08119       DQual = UD->getQualifier();
08120     } else if (UnresolvedUsingTypenameDecl *UD
08121                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
08122       DTypename = true;
08123       DQual = UD->getQualifier();
08124     } else continue;
08125 
08126     // using decls differ if one says 'typename' and the other doesn't.
08127     // FIXME: non-dependent using decls?
08128     if (HasTypenameKeyword != DTypename) continue;
08129 
08130     // using decls differ if they name different scopes (but note that
08131     // template instantiation can cause this check to trigger when it
08132     // didn't before instantiation).
08133     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
08134         Context.getCanonicalNestedNameSpecifier(DQual))
08135       continue;
08136 
08137     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
08138     Diag(D->getLocation(), diag::note_using_decl) << 1;
08139     return true;
08140   }
08141 
08142   return false;
08143 }
08144 
08145 
08146 /// Checks that the given nested-name qualifier used in a using decl
08147 /// in the current context is appropriately related to the current
08148 /// scope.  If an error is found, diagnoses it and returns true.
08149 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
08150                                    const CXXScopeSpec &SS,
08151                                    const DeclarationNameInfo &NameInfo,
08152                                    SourceLocation NameLoc) {
08153   DeclContext *NamedContext = computeDeclContext(SS);
08154 
08155   if (!CurContext->isRecord()) {
08156     // C++03 [namespace.udecl]p3:
08157     // C++0x [namespace.udecl]p8:
08158     //   A using-declaration for a class member shall be a member-declaration.
08159 
08160     // If we weren't able to compute a valid scope, it must be a
08161     // dependent class scope.
08162     if (!NamedContext || NamedContext->isRecord()) {
08163       auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
08164       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
08165         RD = nullptr;
08166 
08167       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
08168         << SS.getRange();
08169 
08170       // If we have a complete, non-dependent source type, try to suggest a
08171       // way to get the same effect.
08172       if (!RD)
08173         return true;
08174 
08175       // Find what this using-declaration was referring to.
08176       LookupResult R(*this, NameInfo, LookupOrdinaryName);
08177       R.setHideTags(false);
08178       R.suppressDiagnostics();
08179       LookupQualifiedName(R, RD);
08180 
08181       if (R.getAsSingle<TypeDecl>()) {
08182         if (getLangOpts().CPlusPlus11) {
08183           // Convert 'using X::Y;' to 'using Y = X::Y;'.
08184           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
08185             << 0 // alias declaration
08186             << FixItHint::CreateInsertion(SS.getBeginLoc(),
08187                                           NameInfo.getName().getAsString() +
08188                                               " = ");
08189         } else {
08190           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
08191           SourceLocation InsertLoc =
08192               PP.getLocForEndOfToken(NameInfo.getLocEnd());
08193           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
08194             << 1 // typedef declaration
08195             << FixItHint::CreateReplacement(UsingLoc, "typedef")
08196             << FixItHint::CreateInsertion(
08197                    InsertLoc, " " + NameInfo.getName().getAsString());
08198         }
08199       } else if (R.getAsSingle<VarDecl>()) {
08200         // Don't provide a fixit outside C++11 mode; we don't want to suggest
08201         // repeating the type of the static data member here.
08202         FixItHint FixIt;
08203         if (getLangOpts().CPlusPlus11) {
08204           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
08205           FixIt = FixItHint::CreateReplacement(
08206               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
08207         }
08208 
08209         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
08210           << 2 // reference declaration
08211           << FixIt;
08212       }
08213       return true;
08214     }
08215 
08216     // Otherwise, everything is known to be fine.
08217     return false;
08218   }
08219 
08220   // The current scope is a record.
08221 
08222   // If the named context is dependent, we can't decide much.
08223   if (!NamedContext) {
08224     // FIXME: in C++0x, we can diagnose if we can prove that the
08225     // nested-name-specifier does not refer to a base class, which is
08226     // still possible in some cases.
08227 
08228     // Otherwise we have to conservatively report that things might be
08229     // okay.
08230     return false;
08231   }
08232 
08233   if (!NamedContext->isRecord()) {
08234     // Ideally this would point at the last name in the specifier,
08235     // but we don't have that level of source info.
08236     Diag(SS.getRange().getBegin(),
08237          diag::err_using_decl_nested_name_specifier_is_not_class)
08238       << SS.getScopeRep() << SS.getRange();
08239     return true;
08240   }
08241 
08242   if (!NamedContext->isDependentContext() &&
08243       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
08244     return true;
08245 
08246   if (getLangOpts().CPlusPlus11) {
08247     // C++0x [namespace.udecl]p3:
08248     //   In a using-declaration used as a member-declaration, the
08249     //   nested-name-specifier shall name a base class of the class
08250     //   being defined.
08251 
08252     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
08253                                  cast<CXXRecordDecl>(NamedContext))) {
08254       if (CurContext == NamedContext) {
08255         Diag(NameLoc,
08256              diag::err_using_decl_nested_name_specifier_is_current_class)
08257           << SS.getRange();
08258         return true;
08259       }
08260 
08261       Diag(SS.getRange().getBegin(),
08262            diag::err_using_decl_nested_name_specifier_is_not_base_class)
08263         << SS.getScopeRep()
08264         << cast<CXXRecordDecl>(CurContext)
08265         << SS.getRange();
08266       return true;
08267     }
08268 
08269     return false;
08270   }
08271 
08272   // C++03 [namespace.udecl]p4:
08273   //   A using-declaration used as a member-declaration shall refer
08274   //   to a member of a base class of the class being defined [etc.].
08275 
08276   // Salient point: SS doesn't have to name a base class as long as
08277   // lookup only finds members from base classes.  Therefore we can
08278   // diagnose here only if we can prove that that can't happen,
08279   // i.e. if the class hierarchies provably don't intersect.
08280 
08281   // TODO: it would be nice if "definitely valid" results were cached
08282   // in the UsingDecl and UsingShadowDecl so that these checks didn't
08283   // need to be repeated.
08284 
08285   struct UserData {
08286     llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
08287 
08288     static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
08289       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
08290       Data->Bases.insert(Base);
08291       return true;
08292     }
08293 
08294     bool hasDependentBases(const CXXRecordDecl *Class) {
08295       return !Class->forallBases(collect, this);
08296     }
08297 
08298     /// Returns true if the base is dependent or is one of the
08299     /// accumulated base classes.
08300     static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
08301       UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
08302       return !Data->Bases.count(Base);
08303     }
08304 
08305     bool mightShareBases(const CXXRecordDecl *Class) {
08306       return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
08307     }
08308   };
08309 
08310   UserData Data;
08311 
08312   // Returns false if we find a dependent base.
08313   if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
08314     return false;
08315 
08316   // Returns false if the class has a dependent base or if it or one
08317   // of its bases is present in the base set of the current context.
08318   if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
08319     return false;
08320 
08321   Diag(SS.getRange().getBegin(),
08322        diag::err_using_decl_nested_name_specifier_is_not_base_class)
08323     << SS.getScopeRep()
08324     << cast<CXXRecordDecl>(CurContext)
08325     << SS.getRange();
08326 
08327   return true;
08328 }
08329 
08330 Decl *Sema::ActOnAliasDeclaration(Scope *S,
08331                                   AccessSpecifier AS,
08332                                   MultiTemplateParamsArg TemplateParamLists,
08333                                   SourceLocation UsingLoc,
08334                                   UnqualifiedId &Name,
08335                                   AttributeList *AttrList,
08336                                   TypeResult Type) {
08337   // Skip up to the relevant declaration scope.
08338   while (S->getFlags() & Scope::TemplateParamScope)
08339     S = S->getParent();
08340   assert((S->getFlags() & Scope::DeclScope) &&
08341          "got alias-declaration outside of declaration scope");
08342 
08343   if (Type.isInvalid())
08344     return nullptr;
08345 
08346   bool Invalid = false;
08347   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
08348   TypeSourceInfo *TInfo = nullptr;
08349   GetTypeFromParser(Type.get(), &TInfo);
08350 
08351   if (DiagnoseClassNameShadow(CurContext, NameInfo))
08352     return nullptr;
08353 
08354   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
08355                                       UPPC_DeclarationType)) {
08356     Invalid = true;
08357     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
08358                                              TInfo->getTypeLoc().getBeginLoc());
08359   }
08360 
08361   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
08362   LookupName(Previous, S);
08363 
08364   // Warn about shadowing the name of a template parameter.
08365   if (Previous.isSingleResult() &&
08366       Previous.getFoundDecl()->isTemplateParameter()) {
08367     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
08368     Previous.clear();
08369   }
08370 
08371   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
08372          "name in alias declaration must be an identifier");
08373   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
08374                                                Name.StartLocation,
08375                                                Name.Identifier, TInfo);
08376 
08377   NewTD->setAccess(AS);
08378 
08379   if (Invalid)
08380     NewTD->setInvalidDecl();
08381 
08382   ProcessDeclAttributeList(S, NewTD, AttrList);
08383 
08384   CheckTypedefForVariablyModifiedType(S, NewTD);
08385   Invalid |= NewTD->isInvalidDecl();
08386 
08387   bool Redeclaration = false;
08388 
08389   NamedDecl *NewND;
08390   if (TemplateParamLists.size()) {
08391     TypeAliasTemplateDecl *OldDecl = nullptr;
08392     TemplateParameterList *OldTemplateParams = nullptr;
08393 
08394     if (TemplateParamLists.size() != 1) {
08395       Diag(UsingLoc, diag::err_alias_template_extra_headers)
08396         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
08397          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
08398     }
08399     TemplateParameterList *TemplateParams = TemplateParamLists[0];
08400 
08401     // Only consider previous declarations in the same scope.
08402     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
08403                          /*ExplicitInstantiationOrSpecialization*/false);
08404     if (!Previous.empty()) {
08405       Redeclaration = true;
08406 
08407       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
08408       if (!OldDecl && !Invalid) {
08409         Diag(UsingLoc, diag::err_redefinition_different_kind)
08410           << Name.Identifier;
08411 
08412         NamedDecl *OldD = Previous.getRepresentativeDecl();
08413         if (OldD->getLocation().isValid())
08414           Diag(OldD->getLocation(), diag::note_previous_definition);
08415 
08416         Invalid = true;
08417       }
08418 
08419       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
08420         if (TemplateParameterListsAreEqual(TemplateParams,
08421                                            OldDecl->getTemplateParameters(),
08422                                            /*Complain=*/true,
08423                                            TPL_TemplateMatch))
08424           OldTemplateParams = OldDecl->getTemplateParameters();
08425         else
08426           Invalid = true;
08427 
08428         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
08429         if (!Invalid &&
08430             !Context.hasSameType(OldTD->getUnderlyingType(),
08431                                  NewTD->getUnderlyingType())) {
08432           // FIXME: The C++0x standard does not clearly say this is ill-formed,
08433           // but we can't reasonably accept it.
08434           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
08435             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
08436           if (OldTD->getLocation().isValid())
08437             Diag(OldTD->getLocation(), diag::note_previous_definition);
08438           Invalid = true;
08439         }
08440       }
08441     }
08442 
08443     // Merge any previous default template arguments into our parameters,
08444     // and check the parameter list.
08445     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
08446                                    TPC_TypeAliasTemplate))
08447       return nullptr;
08448 
08449     TypeAliasTemplateDecl *NewDecl =
08450       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
08451                                     Name.Identifier, TemplateParams,
08452                                     NewTD);
08453     NewTD->setDescribedAliasTemplate(NewDecl);
08454 
08455     NewDecl->setAccess(AS);
08456 
08457     if (Invalid)
08458       NewDecl->setInvalidDecl();
08459     else if (OldDecl)
08460       NewDecl->setPreviousDecl(OldDecl);
08461 
08462     NewND = NewDecl;
08463   } else {
08464     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
08465     NewND = NewTD;
08466   }
08467 
08468   if (!Redeclaration)
08469     PushOnScopeChains(NewND, S);
08470 
08471   ActOnDocumentableDecl(NewND);
08472   return NewND;
08473 }
08474 
08475 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
08476                                    SourceLocation AliasLoc,
08477                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
08478                                    SourceLocation IdentLoc,
08479                                    IdentifierInfo *Ident) {
08480 
08481   // Lookup the namespace name.
08482   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
08483   LookupParsedName(R, S, &SS);
08484 
08485   if (R.isAmbiguous())
08486     return nullptr;
08487 
08488   if (R.empty()) {
08489     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
08490       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
08491       return nullptr;
08492     }
08493   }
08494   assert(!R.isAmbiguous() && !R.empty());
08495 
08496   // Check if we have a previous declaration with the same name.
08497   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
08498                                          ForRedeclaration);
08499   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
08500     PrevDecl = nullptr;
08501 
08502   NamedDecl *ND = R.getFoundDecl();
08503 
08504   if (PrevDecl) {
08505     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
08506       // We already have an alias with the same name that points to the same
08507       // namespace; check that it matches.
08508       if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
08509         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
08510           << Alias;
08511         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
08512           << AD->getNamespace();
08513         return nullptr;
08514       }
08515     } else {
08516       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
08517                             ? diag::err_redefinition
08518                             : diag::err_redefinition_different_kind;
08519       Diag(AliasLoc, DiagID) << Alias;
08520       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
08521       return nullptr;
08522     }
08523   }
08524 
08525   // The use of a nested name specifier may trigger deprecation warnings.
08526   DiagnoseUseOfDecl(ND, IdentLoc);
08527 
08528   NamespaceAliasDecl *AliasDecl =
08529     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
08530                                Alias, SS.getWithLocInContext(Context),
08531                                IdentLoc, ND);
08532   if (PrevDecl)
08533     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
08534 
08535   PushOnScopeChains(AliasDecl, S);
08536   return AliasDecl;
08537 }
08538 
08539 Sema::ImplicitExceptionSpecification
08540 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
08541                                                CXXMethodDecl *MD) {
08542   CXXRecordDecl *ClassDecl = MD->getParent();
08543 
08544   // C++ [except.spec]p14:
08545   //   An implicitly declared special member function (Clause 12) shall have an 
08546   //   exception-specification. [...]
08547   ImplicitExceptionSpecification ExceptSpec(*this);
08548   if (ClassDecl->isInvalidDecl())
08549     return ExceptSpec;
08550 
08551   // Direct base-class constructors.
08552   for (const auto &B : ClassDecl->bases()) {
08553     if (B.isVirtual()) // Handled below.
08554       continue;
08555     
08556     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
08557       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
08558       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
08559       // If this is a deleted function, add it anyway. This might be conformant
08560       // with the standard. This might not. I'm not sure. It might not matter.
08561       if (Constructor)
08562         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
08563     }
08564   }
08565 
08566   // Virtual base-class constructors.
08567   for (const auto &B : ClassDecl->vbases()) {
08568     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
08569       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
08570       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
08571       // If this is a deleted function, add it anyway. This might be conformant
08572       // with the standard. This might not. I'm not sure. It might not matter.
08573       if (Constructor)
08574         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
08575     }
08576   }
08577 
08578   // Field constructors.
08579   for (const auto *F : ClassDecl->fields()) {
08580     if (F->hasInClassInitializer()) {
08581       if (Expr *E = F->getInClassInitializer())
08582         ExceptSpec.CalledExpr(E);
08583     } else if (const RecordType *RecordTy
08584               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
08585       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
08586       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
08587       // If this is a deleted function, add it anyway. This might be conformant
08588       // with the standard. This might not. I'm not sure. It might not matter.
08589       // In particular, the problem is that this function never gets called. It
08590       // might just be ill-formed because this function attempts to refer to
08591       // a deleted function here.
08592       if (Constructor)
08593         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
08594     }
08595   }
08596 
08597   return ExceptSpec;
08598 }
08599 
08600 Sema::ImplicitExceptionSpecification
08601 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
08602   CXXRecordDecl *ClassDecl = CD->getParent();
08603 
08604   // C++ [except.spec]p14:
08605   //   An inheriting constructor [...] shall have an exception-specification. [...]
08606   ImplicitExceptionSpecification ExceptSpec(*this);
08607   if (ClassDecl->isInvalidDecl())
08608     return ExceptSpec;
08609 
08610   // Inherited constructor.
08611   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
08612   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
08613   // FIXME: Copying or moving the parameters could add extra exceptions to the
08614   // set, as could the default arguments for the inherited constructor. This
08615   // will be addressed when we implement the resolution of core issue 1351.
08616   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
08617 
08618   // Direct base-class constructors.
08619   for (const auto &B : ClassDecl->bases()) {
08620     if (B.isVirtual()) // Handled below.
08621       continue;
08622 
08623     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
08624       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
08625       if (BaseClassDecl == InheritedDecl)
08626         continue;
08627       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
08628       if (Constructor)
08629         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
08630     }
08631   }
08632 
08633   // Virtual base-class constructors.
08634   for (const auto &B : ClassDecl->vbases()) {
08635     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
08636       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
08637       if (BaseClassDecl == InheritedDecl)
08638         continue;
08639       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
08640       if (Constructor)
08641         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
08642     }
08643   }
08644 
08645   // Field constructors.
08646   for (const auto *F : ClassDecl->fields()) {
08647     if (F->hasInClassInitializer()) {
08648       if (Expr *E = F->getInClassInitializer())
08649         ExceptSpec.CalledExpr(E);
08650     } else if (const RecordType *RecordTy
08651               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
08652       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
08653       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
08654       if (Constructor)
08655         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
08656     }
08657   }
08658 
08659   return ExceptSpec;
08660 }
08661 
08662 namespace {
08663 /// RAII object to register a special member as being currently declared.
08664 struct DeclaringSpecialMember {
08665   Sema &S;
08666   Sema::SpecialMemberDecl D;
08667   bool WasAlreadyBeingDeclared;
08668 
08669   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
08670     : S(S), D(RD, CSM) {
08671     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
08672     if (WasAlreadyBeingDeclared)
08673       // This almost never happens, but if it does, ensure that our cache
08674       // doesn't contain a stale result.
08675       S.SpecialMemberCache.clear();
08676 
08677     // FIXME: Register a note to be produced if we encounter an error while
08678     // declaring the special member.
08679   }
08680   ~DeclaringSpecialMember() {
08681     if (!WasAlreadyBeingDeclared)
08682       S.SpecialMembersBeingDeclared.erase(D);
08683   }
08684 
08685   /// \brief Are we already trying to declare this special member?
08686   bool isAlreadyBeingDeclared() const {
08687     return WasAlreadyBeingDeclared;
08688   }
08689 };
08690 }
08691 
08692 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
08693                                                      CXXRecordDecl *ClassDecl) {
08694   // C++ [class.ctor]p5:
08695   //   A default constructor for a class X is a constructor of class X
08696   //   that can be called without an argument. If there is no
08697   //   user-declared constructor for class X, a default constructor is
08698   //   implicitly declared. An implicitly-declared default constructor
08699   //   is an inline public member of its class.
08700   assert(ClassDecl->needsImplicitDefaultConstructor() &&
08701          "Should not build implicit default constructor!");
08702 
08703   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
08704   if (DSM.isAlreadyBeingDeclared())
08705     return nullptr;
08706 
08707   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
08708                                                      CXXDefaultConstructor,
08709                                                      false);
08710 
08711   // Create the actual constructor declaration.
08712   CanQualType ClassType
08713     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
08714   SourceLocation ClassLoc = ClassDecl->getLocation();
08715   DeclarationName Name
08716     = Context.DeclarationNames.getCXXConstructorName(ClassType);
08717   DeclarationNameInfo NameInfo(Name, ClassLoc);
08718   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
08719       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
08720       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
08721       /*isImplicitlyDeclared=*/true, Constexpr);
08722   DefaultCon->setAccess(AS_public);
08723   DefaultCon->setDefaulted();
08724 
08725   if (getLangOpts().CUDA) {
08726     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
08727                                             DefaultCon,
08728                                             /* ConstRHS */ false,
08729                                             /* Diagnose */ false);
08730   }
08731 
08732   // Build an exception specification pointing back at this constructor.
08733   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
08734   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
08735 
08736   // We don't need to use SpecialMemberIsTrivial here; triviality for default
08737   // constructors is easy to compute.
08738   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
08739 
08740   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
08741     SetDeclDeleted(DefaultCon, ClassLoc);
08742 
08743   // Note that we have declared this constructor.
08744   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
08745 
08746   if (Scope *S = getScopeForContext(ClassDecl))
08747     PushOnScopeChains(DefaultCon, S, false);
08748   ClassDecl->addDecl(DefaultCon);
08749 
08750   return DefaultCon;
08751 }
08752 
08753 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
08754                                             CXXConstructorDecl *Constructor) {
08755   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
08756           !Constructor->doesThisDeclarationHaveABody() &&
08757           !Constructor->isDeleted()) &&
08758     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
08759 
08760   CXXRecordDecl *ClassDecl = Constructor->getParent();
08761   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
08762 
08763   SynthesizedFunctionScope Scope(*this, Constructor);
08764   DiagnosticErrorTrap Trap(Diags);
08765   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
08766       Trap.hasErrorOccurred()) {
08767     Diag(CurrentLocation, diag::note_member_synthesized_at) 
08768       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
08769     Constructor->setInvalidDecl();
08770     return;
08771   }
08772 
08773   // The exception specification is needed because we are defining the
08774   // function.
08775   ResolveExceptionSpec(CurrentLocation,
08776                        Constructor->getType()->castAs<FunctionProtoType>());
08777 
08778   SourceLocation Loc = Constructor->getLocEnd().isValid()
08779                            ? Constructor->getLocEnd()
08780                            : Constructor->getLocation();
08781   Constructor->setBody(new (Context) CompoundStmt(Loc));
08782 
08783   Constructor->markUsed(Context);
08784   MarkVTableUsed(CurrentLocation, ClassDecl);
08785 
08786   if (ASTMutationListener *L = getASTMutationListener()) {
08787     L->CompletedImplicitDefinition(Constructor);
08788   }
08789 
08790   DiagnoseUninitializedFields(*this, Constructor);
08791 }
08792 
08793 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
08794   // Perform any delayed checks on exception specifications.
08795   CheckDelayedMemberExceptionSpecs();
08796 }
08797 
08798 namespace {
08799 /// Information on inheriting constructors to declare.
08800 class InheritingConstructorInfo {
08801 public:
08802   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
08803       : SemaRef(SemaRef), Derived(Derived) {
08804     // Mark the constructors that we already have in the derived class.
08805     //
08806     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
08807     //   unless there is a user-declared constructor with the same signature in
08808     //   the class where the using-declaration appears.
08809     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
08810   }
08811 
08812   void inheritAll(CXXRecordDecl *RD) {
08813     visitAll(RD, &InheritingConstructorInfo::inherit);
08814   }
08815 
08816 private:
08817   /// Information about an inheriting constructor.
08818   struct InheritingConstructor {
08819     InheritingConstructor()
08820       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
08821 
08822     /// If \c true, a constructor with this signature is already declared
08823     /// in the derived class.
08824     bool DeclaredInDerived;
08825 
08826     /// The constructor which is inherited.
08827     const CXXConstructorDecl *BaseCtor;
08828 
08829     /// The derived constructor we declared.
08830     CXXConstructorDecl *DerivedCtor;
08831   };
08832 
08833   /// Inheriting constructors with a given canonical type. There can be at
08834   /// most one such non-template constructor, and any number of templated
08835   /// constructors.
08836   struct InheritingConstructorsForType {
08837     InheritingConstructor NonTemplate;
08838     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
08839         Templates;
08840 
08841     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
08842       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
08843         TemplateParameterList *ParamList = FTD->getTemplateParameters();
08844         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
08845           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
08846                                                false, S.TPL_TemplateMatch))
08847             return Templates[I].second;
08848         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
08849         return Templates.back().second;
08850       }
08851 
08852       return NonTemplate;
08853     }
08854   };
08855 
08856   /// Get or create the inheriting constructor record for a constructor.
08857   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
08858                                   QualType CtorType) {
08859     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
08860         .getEntry(SemaRef, Ctor);
08861   }
08862 
08863   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
08864 
08865   /// Process all constructors for a class.
08866   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
08867     for (const auto *Ctor : RD->ctors())
08868       (this->*Callback)(Ctor);
08869     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
08870              I(RD->decls_begin()), E(RD->decls_end());
08871          I != E; ++I) {
08872       const FunctionDecl *FD = (*I)->getTemplatedDecl();
08873       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
08874         (this->*Callback)(CD);
08875     }
08876   }
08877 
08878   /// Note that a constructor (or constructor template) was declared in Derived.
08879   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
08880     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
08881   }
08882 
08883   /// Inherit a single constructor.
08884   void inherit(const CXXConstructorDecl *Ctor) {
08885     const FunctionProtoType *CtorType =
08886         Ctor->getType()->castAs<FunctionProtoType>();
08887     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
08888     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
08889 
08890     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
08891 
08892     // Core issue (no number yet): the ellipsis is always discarded.
08893     if (EPI.Variadic) {
08894       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
08895       SemaRef.Diag(Ctor->getLocation(),
08896                    diag::note_using_decl_constructor_ellipsis);
08897       EPI.Variadic = false;
08898     }
08899 
08900     // Declare a constructor for each number of parameters.
08901     //
08902     // C++11 [class.inhctor]p1:
08903     //   The candidate set of inherited constructors from the class X named in
08904     //   the using-declaration consists of [... modulo defects ...] for each
08905     //   constructor or constructor template of X, the set of constructors or
08906     //   constructor templates that results from omitting any ellipsis parameter
08907     //   specification and successively omitting parameters with a default
08908     //   argument from the end of the parameter-type-list
08909     unsigned MinParams = minParamsToInherit(Ctor);
08910     unsigned Params = Ctor->getNumParams();
08911     if (Params >= MinParams) {
08912       do
08913         declareCtor(UsingLoc, Ctor,
08914                     SemaRef.Context.getFunctionType(
08915                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
08916       while (Params > MinParams &&
08917              Ctor->getParamDecl(--Params)->hasDefaultArg());
08918     }
08919   }
08920 
08921   /// Find the using-declaration which specified that we should inherit the
08922   /// constructors of \p Base.
08923   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
08924     // No fancy lookup required; just look for the base constructor name
08925     // directly within the derived class.
08926     ASTContext &Context = SemaRef.Context;
08927     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
08928         Context.getCanonicalType(Context.getRecordType(Base)));
08929     DeclContext::lookup_const_result Decls = Derived->lookup(Name);
08930     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
08931   }
08932 
08933   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
08934     // C++11 [class.inhctor]p3:
08935     //   [F]or each constructor template in the candidate set of inherited
08936     //   constructors, a constructor template is implicitly declared
08937     if (Ctor->getDescribedFunctionTemplate())
08938       return 0;
08939 
08940     //   For each non-template constructor in the candidate set of inherited
08941     //   constructors other than a constructor having no parameters or a
08942     //   copy/move constructor having a single parameter, a constructor is
08943     //   implicitly declared [...]
08944     if (Ctor->getNumParams() == 0)
08945       return 1;
08946     if (Ctor->isCopyOrMoveConstructor())
08947       return 2;
08948 
08949     // Per discussion on core reflector, never inherit a constructor which
08950     // would become a default, copy, or move constructor of Derived either.
08951     const ParmVarDecl *PD = Ctor->getParamDecl(0);
08952     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
08953     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
08954   }
08955 
08956   /// Declare a single inheriting constructor, inheriting the specified
08957   /// constructor, with the given type.
08958   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
08959                    QualType DerivedType) {
08960     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
08961 
08962     // C++11 [class.inhctor]p3:
08963     //   ... a constructor is implicitly declared with the same constructor
08964     //   characteristics unless there is a user-declared constructor with
08965     //   the same signature in the class where the using-declaration appears
08966     if (Entry.DeclaredInDerived)
08967       return;
08968 
08969     // C++11 [class.inhctor]p7:
08970     //   If two using-declarations declare inheriting constructors with the
08971     //   same signature, the program is ill-formed
08972     if (Entry.DerivedCtor) {
08973       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
08974         // Only diagnose this once per constructor.
08975         if (Entry.DerivedCtor->isInvalidDecl())
08976           return;
08977         Entry.DerivedCtor->setInvalidDecl();
08978 
08979         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
08980         SemaRef.Diag(BaseCtor->getLocation(),
08981                      diag::note_using_decl_constructor_conflict_current_ctor);
08982         SemaRef.Diag(Entry.BaseCtor->getLocation(),
08983                      diag::note_using_decl_constructor_conflict_previous_ctor);
08984         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
08985                      diag::note_using_decl_constructor_conflict_previous_using);
08986       } else {
08987         // Core issue (no number): if the same inheriting constructor is
08988         // produced by multiple base class constructors from the same base
08989         // class, the inheriting constructor is defined as deleted.
08990         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
08991       }
08992 
08993       return;
08994     }
08995 
08996     ASTContext &Context = SemaRef.Context;
08997     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
08998         Context.getCanonicalType(Context.getRecordType(Derived)));
08999     DeclarationNameInfo NameInfo(Name, UsingLoc);
09000 
09001     TemplateParameterList *TemplateParams = nullptr;
09002     if (const FunctionTemplateDecl *FTD =
09003             BaseCtor->getDescribedFunctionTemplate()) {
09004       TemplateParams = FTD->getTemplateParameters();
09005       // We're reusing template parameters from a different DeclContext. This
09006       // is questionable at best, but works out because the template depth in
09007       // both places is guaranteed to be 0.
09008       // FIXME: Rebuild the template parameters in the new context, and
09009       // transform the function type to refer to them.
09010     }
09011 
09012     // Build type source info pointing at the using-declaration. This is
09013     // required by template instantiation.
09014     TypeSourceInfo *TInfo =
09015         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
09016     FunctionProtoTypeLoc ProtoLoc =
09017         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
09018 
09019     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
09020         Context, Derived, UsingLoc, NameInfo, DerivedType,
09021         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
09022         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
09023 
09024     // Build an unevaluated exception specification for this constructor.
09025     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
09026     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
09027     EPI.ExceptionSpec.Type = EST_Unevaluated;
09028     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
09029     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
09030                                                  FPT->getParamTypes(), EPI));
09031 
09032     // Build the parameter declarations.
09033     SmallVector<ParmVarDecl *, 16> ParamDecls;
09034     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
09035       TypeSourceInfo *TInfo =
09036           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
09037       ParmVarDecl *PD = ParmVarDecl::Create(
09038           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
09039           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
09040       PD->setScopeInfo(0, I);
09041       PD->setImplicit();
09042       ParamDecls.push_back(PD);
09043       ProtoLoc.setParam(I, PD);
09044     }
09045 
09046     // Set up the new constructor.
09047     DerivedCtor->setAccess(BaseCtor->getAccess());
09048     DerivedCtor->setParams(ParamDecls);
09049     DerivedCtor->setInheritedConstructor(BaseCtor);
09050     if (BaseCtor->isDeleted())
09051       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
09052 
09053     // If this is a constructor template, build the template declaration.
09054     if (TemplateParams) {
09055       FunctionTemplateDecl *DerivedTemplate =
09056           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
09057                                        TemplateParams, DerivedCtor);
09058       DerivedTemplate->setAccess(BaseCtor->getAccess());
09059       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
09060       Derived->addDecl(DerivedTemplate);
09061     } else {
09062       Derived->addDecl(DerivedCtor);
09063     }
09064 
09065     Entry.BaseCtor = BaseCtor;
09066     Entry.DerivedCtor = DerivedCtor;
09067   }
09068 
09069   Sema &SemaRef;
09070   CXXRecordDecl *Derived;
09071   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
09072   MapType Map;
09073 };
09074 }
09075 
09076 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
09077   // Defer declaring the inheriting constructors until the class is
09078   // instantiated.
09079   if (ClassDecl->isDependentContext())
09080     return;
09081 
09082   // Find base classes from which we might inherit constructors.
09083   SmallVector<CXXRecordDecl*, 4> InheritedBases;
09084   for (const auto &BaseIt : ClassDecl->bases())
09085     if (BaseIt.getInheritConstructors())
09086       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
09087 
09088   // Go no further if we're not inheriting any constructors.
09089   if (InheritedBases.empty())
09090     return;
09091 
09092   // Declare the inherited constructors.
09093   InheritingConstructorInfo ICI(*this, ClassDecl);
09094   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
09095     ICI.inheritAll(InheritedBases[I]);
09096 }
09097 
09098 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
09099                                        CXXConstructorDecl *Constructor) {
09100   CXXRecordDecl *ClassDecl = Constructor->getParent();
09101   assert(Constructor->getInheritedConstructor() &&
09102          !Constructor->doesThisDeclarationHaveABody() &&
09103          !Constructor->isDeleted());
09104 
09105   SynthesizedFunctionScope Scope(*this, Constructor);
09106   DiagnosticErrorTrap Trap(Diags);
09107   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
09108       Trap.hasErrorOccurred()) {
09109     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
09110       << Context.getTagDeclType(ClassDecl);
09111     Constructor->setInvalidDecl();
09112     return;
09113   }
09114 
09115   SourceLocation Loc = Constructor->getLocation();
09116   Constructor->setBody(new (Context) CompoundStmt(Loc));
09117 
09118   Constructor->markUsed(Context);
09119   MarkVTableUsed(CurrentLocation, ClassDecl);
09120 
09121   if (ASTMutationListener *L = getASTMutationListener()) {
09122     L->CompletedImplicitDefinition(Constructor);
09123   }
09124 }
09125 
09126 
09127 Sema::ImplicitExceptionSpecification
09128 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
09129   CXXRecordDecl *ClassDecl = MD->getParent();
09130 
09131   // C++ [except.spec]p14: 
09132   //   An implicitly declared special member function (Clause 12) shall have 
09133   //   an exception-specification.
09134   ImplicitExceptionSpecification ExceptSpec(*this);
09135   if (ClassDecl->isInvalidDecl())
09136     return ExceptSpec;
09137 
09138   // Direct base-class destructors.
09139   for (const auto &B : ClassDecl->bases()) {
09140     if (B.isVirtual()) // Handled below.
09141       continue;
09142     
09143     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
09144       ExceptSpec.CalledDecl(B.getLocStart(),
09145                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
09146   }
09147 
09148   // Virtual base-class destructors.
09149   for (const auto &B : ClassDecl->vbases()) {
09150     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
09151       ExceptSpec.CalledDecl(B.getLocStart(),
09152                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
09153   }
09154 
09155   // Field destructors.
09156   for (const auto *F : ClassDecl->fields()) {
09157     if (const RecordType *RecordTy
09158         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
09159       ExceptSpec.CalledDecl(F->getLocation(),
09160                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
09161   }
09162 
09163   return ExceptSpec;
09164 }
09165 
09166 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
09167   // C++ [class.dtor]p2:
09168   //   If a class has no user-declared destructor, a destructor is
09169   //   declared implicitly. An implicitly-declared destructor is an
09170   //   inline public member of its class.
09171   assert(ClassDecl->needsImplicitDestructor());
09172 
09173   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
09174   if (DSM.isAlreadyBeingDeclared())
09175     return nullptr;
09176 
09177   // Create the actual destructor declaration.
09178   CanQualType ClassType
09179     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
09180   SourceLocation ClassLoc = ClassDecl->getLocation();
09181   DeclarationName Name
09182     = Context.DeclarationNames.getCXXDestructorName(ClassType);
09183   DeclarationNameInfo NameInfo(Name, ClassLoc);
09184   CXXDestructorDecl *Destructor
09185       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
09186                                   QualType(), nullptr, /*isInline=*/true,
09187                                   /*isImplicitlyDeclared=*/true);
09188   Destructor->setAccess(AS_public);
09189   Destructor->setDefaulted();
09190 
09191   if (getLangOpts().CUDA) {
09192     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
09193                                             Destructor,
09194                                             /* ConstRHS */ false,
09195                                             /* Diagnose */ false);
09196   }
09197 
09198   // Build an exception specification pointing back at this destructor.
09199   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
09200   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
09201 
09202   AddOverriddenMethods(ClassDecl, Destructor);
09203 
09204   // We don't need to use SpecialMemberIsTrivial here; triviality for
09205   // destructors is easy to compute.
09206   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
09207 
09208   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
09209     SetDeclDeleted(Destructor, ClassLoc);
09210 
09211   // Note that we have declared this destructor.
09212   ++ASTContext::NumImplicitDestructorsDeclared;
09213 
09214   // Introduce this destructor into its scope.
09215   if (Scope *S = getScopeForContext(ClassDecl))
09216     PushOnScopeChains(Destructor, S, false);
09217   ClassDecl->addDecl(Destructor);
09218 
09219   return Destructor;
09220 }
09221 
09222 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
09223                                     CXXDestructorDecl *Destructor) {
09224   assert((Destructor->isDefaulted() &&
09225           !Destructor->doesThisDeclarationHaveABody() &&
09226           !Destructor->isDeleted()) &&
09227          "DefineImplicitDestructor - call it for implicit default dtor");
09228   CXXRecordDecl *ClassDecl = Destructor->getParent();
09229   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
09230 
09231   if (Destructor->isInvalidDecl())
09232     return;
09233 
09234   SynthesizedFunctionScope Scope(*this, Destructor);
09235 
09236   DiagnosticErrorTrap Trap(Diags);
09237   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
09238                                          Destructor->getParent());
09239 
09240   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
09241     Diag(CurrentLocation, diag::note_member_synthesized_at) 
09242       << CXXDestructor << Context.getTagDeclType(ClassDecl);
09243 
09244     Destructor->setInvalidDecl();
09245     return;
09246   }
09247 
09248   // The exception specification is needed because we are defining the
09249   // function.
09250   ResolveExceptionSpec(CurrentLocation,
09251                        Destructor->getType()->castAs<FunctionProtoType>());
09252 
09253   SourceLocation Loc = Destructor->getLocEnd().isValid()
09254                            ? Destructor->getLocEnd()
09255                            : Destructor->getLocation();
09256   Destructor->setBody(new (Context) CompoundStmt(Loc));
09257   Destructor->markUsed(Context);
09258   MarkVTableUsed(CurrentLocation, ClassDecl);
09259 
09260   if (ASTMutationListener *L = getASTMutationListener()) {
09261     L->CompletedImplicitDefinition(Destructor);
09262   }
09263 }
09264 
09265 /// \brief Perform any semantic analysis which needs to be delayed until all
09266 /// pending class member declarations have been parsed.
09267 void Sema::ActOnFinishCXXMemberDecls() {
09268   // If the context is an invalid C++ class, just suppress these checks.
09269   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
09270     if (Record->isInvalidDecl()) {
09271       DelayedDefaultedMemberExceptionSpecs.clear();
09272       DelayedDestructorExceptionSpecChecks.clear();
09273       return;
09274     }
09275   }
09276 }
09277 
09278 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
09279                                          CXXDestructorDecl *Destructor) {
09280   assert(getLangOpts().CPlusPlus11 &&
09281          "adjusting dtor exception specs was introduced in c++11");
09282 
09283   // C++11 [class.dtor]p3:
09284   //   A declaration of a destructor that does not have an exception-
09285   //   specification is implicitly considered to have the same exception-
09286   //   specification as an implicit declaration.
09287   const FunctionProtoType *DtorType = Destructor->getType()->
09288                                         getAs<FunctionProtoType>();
09289   if (DtorType->hasExceptionSpec())
09290     return;
09291 
09292   // Replace the destructor's type, building off the existing one. Fortunately,
09293   // the only thing of interest in the destructor type is its extended info.
09294   // The return and arguments are fixed.
09295   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
09296   EPI.ExceptionSpec.Type = EST_Unevaluated;
09297   EPI.ExceptionSpec.SourceDecl = Destructor;
09298   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
09299 
09300   // FIXME: If the destructor has a body that could throw, and the newly created
09301   // spec doesn't allow exceptions, we should emit a warning, because this
09302   // change in behavior can break conforming C++03 programs at runtime.
09303   // However, we don't have a body or an exception specification yet, so it
09304   // needs to be done somewhere else.
09305 }
09306 
09307 namespace {
09308 /// \brief An abstract base class for all helper classes used in building the
09309 //  copy/move operators. These classes serve as factory functions and help us
09310 //  avoid using the same Expr* in the AST twice.
09311 class ExprBuilder {
09312   ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
09313   ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
09314 
09315 protected:
09316   static Expr *assertNotNull(Expr *E) {
09317     assert(E && "Expression construction must not fail.");
09318     return E;
09319   }
09320 
09321 public:
09322   ExprBuilder() {}
09323   virtual ~ExprBuilder() {}
09324 
09325   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
09326 };
09327 
09328 class RefBuilder: public ExprBuilder {
09329   VarDecl *Var;
09330   QualType VarType;
09331 
09332 public:
09333   Expr *build(Sema &S, SourceLocation Loc) const override {
09334     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
09335   }
09336 
09337   RefBuilder(VarDecl *Var, QualType VarType)
09338       : Var(Var), VarType(VarType) {}
09339 };
09340 
09341 class ThisBuilder: public ExprBuilder {
09342 public:
09343   Expr *build(Sema &S, SourceLocation Loc) const override {
09344     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
09345   }
09346 };
09347 
09348 class CastBuilder: public ExprBuilder {
09349   const ExprBuilder &Builder;
09350   QualType Type;
09351   ExprValueKind Kind;
09352   const CXXCastPath &Path;
09353 
09354 public:
09355   Expr *build(Sema &S, SourceLocation Loc) const override {
09356     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
09357                                              CK_UncheckedDerivedToBase, Kind,
09358                                              &Path).get());
09359   }
09360 
09361   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
09362               const CXXCastPath &Path)
09363       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
09364 };
09365 
09366 class DerefBuilder: public ExprBuilder {
09367   const ExprBuilder &Builder;
09368 
09369 public:
09370   Expr *build(Sema &S, SourceLocation Loc) const override {
09371     return assertNotNull(
09372         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
09373   }
09374 
09375   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
09376 };
09377 
09378 class MemberBuilder: public ExprBuilder {
09379   const ExprBuilder &Builder;
09380   QualType Type;
09381   CXXScopeSpec SS;
09382   bool IsArrow;
09383   LookupResult &MemberLookup;
09384 
09385 public:
09386   Expr *build(Sema &S, SourceLocation Loc) const override {
09387     return assertNotNull(S.BuildMemberReferenceExpr(
09388         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
09389         nullptr, MemberLookup, nullptr).get());
09390   }
09391 
09392   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
09393                 LookupResult &MemberLookup)
09394       : Builder(Builder), Type(Type), IsArrow(IsArrow),
09395         MemberLookup(MemberLookup) {}
09396 };
09397 
09398 class MoveCastBuilder: public ExprBuilder {
09399   const ExprBuilder &Builder;
09400 
09401 public:
09402   Expr *build(Sema &S, SourceLocation Loc) const override {
09403     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
09404   }
09405 
09406   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
09407 };
09408 
09409 class LvalueConvBuilder: public ExprBuilder {
09410   const ExprBuilder &Builder;
09411 
09412 public:
09413   Expr *build(Sema &S, SourceLocation Loc) const override {
09414     return assertNotNull(
09415         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
09416   }
09417 
09418   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
09419 };
09420 
09421 class SubscriptBuilder: public ExprBuilder {
09422   const ExprBuilder &Base;
09423   const ExprBuilder &Index;
09424 
09425 public:
09426   Expr *build(Sema &S, SourceLocation Loc) const override {
09427     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
09428         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
09429   }
09430 
09431   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
09432       : Base(Base), Index(Index) {}
09433 };
09434 
09435 } // end anonymous namespace
09436 
09437 /// When generating a defaulted copy or move assignment operator, if a field
09438 /// should be copied with __builtin_memcpy rather than via explicit assignments,
09439 /// do so. This optimization only applies for arrays of scalars, and for arrays
09440 /// of class type where the selected copy/move-assignment operator is trivial.
09441 static StmtResult
09442 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
09443                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
09444   // Compute the size of the memory buffer to be copied.
09445   QualType SizeType = S.Context.getSizeType();
09446   llvm::APInt Size(S.Context.getTypeSize(SizeType),
09447                    S.Context.getTypeSizeInChars(T).getQuantity());
09448 
09449   // Take the address of the field references for "from" and "to". We
09450   // directly construct UnaryOperators here because semantic analysis
09451   // does not permit us to take the address of an xvalue.
09452   Expr *From = FromB.build(S, Loc);
09453   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
09454                          S.Context.getPointerType(From->getType()),
09455                          VK_RValue, OK_Ordinary, Loc);
09456   Expr *To = ToB.build(S, Loc);
09457   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
09458                        S.Context.getPointerType(To->getType()),
09459                        VK_RValue, OK_Ordinary, Loc);
09460 
09461   const Type *E = T->getBaseElementTypeUnsafe();
09462   bool NeedsCollectableMemCpy =
09463     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
09464 
09465   // Create a reference to the __builtin_objc_memmove_collectable function
09466   StringRef MemCpyName = NeedsCollectableMemCpy ?
09467     "__builtin_objc_memmove_collectable" :
09468     "__builtin_memcpy";
09469   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
09470                  Sema::LookupOrdinaryName);
09471   S.LookupName(R, S.TUScope, true);
09472 
09473   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
09474   if (!MemCpy)
09475     // Something went horribly wrong earlier, and we will have complained
09476     // about it.
09477     return StmtError();
09478 
09479   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
09480                                             VK_RValue, Loc, nullptr);
09481   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
09482 
09483   Expr *CallArgs[] = {
09484     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
09485   };
09486   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
09487                                     Loc, CallArgs, Loc);
09488 
09489   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
09490   return Call.getAs<Stmt>();
09491 }
09492 
09493 /// \brief Builds a statement that copies/moves the given entity from \p From to
09494 /// \c To.
09495 ///
09496 /// This routine is used to copy/move the members of a class with an
09497 /// implicitly-declared copy/move assignment operator. When the entities being
09498 /// copied are arrays, this routine builds for loops to copy them.
09499 ///
09500 /// \param S The Sema object used for type-checking.
09501 ///
09502 /// \param Loc The location where the implicit copy/move is being generated.
09503 ///
09504 /// \param T The type of the expressions being copied/moved. Both expressions
09505 /// must have this type.
09506 ///
09507 /// \param To The expression we are copying/moving to.
09508 ///
09509 /// \param From The expression we are copying/moving from.
09510 ///
09511 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
09512 /// Otherwise, it's a non-static member subobject.
09513 ///
09514 /// \param Copying Whether we're copying or moving.
09515 ///
09516 /// \param Depth Internal parameter recording the depth of the recursion.
09517 ///
09518 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
09519 /// if a memcpy should be used instead.
09520 static StmtResult
09521 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
09522                                  const ExprBuilder &To, const ExprBuilder &From,
09523                                  bool CopyingBaseSubobject, bool Copying,
09524                                  unsigned Depth = 0) {
09525   // C++11 [class.copy]p28:
09526   //   Each subobject is assigned in the manner appropriate to its type:
09527   //
09528   //     - if the subobject is of class type, as if by a call to operator= with
09529   //       the subobject as the object expression and the corresponding
09530   //       subobject of x as a single function argument (as if by explicit
09531   //       qualification; that is, ignoring any possible virtual overriding
09532   //       functions in more derived classes);
09533   //
09534   // C++03 [class.copy]p13:
09535   //     - if the subobject is of class type, the copy assignment operator for
09536   //       the class is used (as if by explicit qualification; that is,
09537   //       ignoring any possible virtual overriding functions in more derived
09538   //       classes);
09539   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
09540     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
09541 
09542     // Look for operator=.
09543     DeclarationName Name
09544       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
09545     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
09546     S.LookupQualifiedName(OpLookup, ClassDecl, false);
09547 
09548     // Prior to C++11, filter out any result that isn't a copy/move-assignment
09549     // operator.
09550     if (!S.getLangOpts().CPlusPlus11) {
09551       LookupResult::Filter F = OpLookup.makeFilter();
09552       while (F.hasNext()) {
09553         NamedDecl *D = F.next();
09554         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
09555           if (Method->isCopyAssignmentOperator() ||
09556               (!Copying && Method->isMoveAssignmentOperator()))
09557             continue;
09558 
09559         F.erase();
09560       }
09561       F.done();
09562     }
09563 
09564     // Suppress the protected check (C++ [class.protected]) for each of the
09565     // assignment operators we found. This strange dance is required when
09566     // we're assigning via a base classes's copy-assignment operator. To
09567     // ensure that we're getting the right base class subobject (without
09568     // ambiguities), we need to cast "this" to that subobject type; to
09569     // ensure that we don't go through the virtual call mechanism, we need
09570     // to qualify the operator= name with the base class (see below). However,
09571     // this means that if the base class has a protected copy assignment
09572     // operator, the protected member access check will fail. So, we
09573     // rewrite "protected" access to "public" access in this case, since we
09574     // know by construction that we're calling from a derived class.
09575     if (CopyingBaseSubobject) {
09576       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
09577            L != LEnd; ++L) {
09578         if (L.getAccess() == AS_protected)
09579           L.setAccess(AS_public);
09580       }
09581     }
09582 
09583     // Create the nested-name-specifier that will be used to qualify the
09584     // reference to operator=; this is required to suppress the virtual
09585     // call mechanism.
09586     CXXScopeSpec SS;
09587     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
09588     SS.MakeTrivial(S.Context,
09589                    NestedNameSpecifier::Create(S.Context, nullptr, false,
09590                                                CanonicalT),
09591                    Loc);
09592 
09593     // Create the reference to operator=.
09594     ExprResult OpEqualRef
09595       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
09596                                    SS, /*TemplateKWLoc=*/SourceLocation(),
09597                                    /*FirstQualifierInScope=*/nullptr,
09598                                    OpLookup,
09599                                    /*TemplateArgs=*/nullptr,
09600                                    /*SuppressQualifierCheck=*/true);
09601     if (OpEqualRef.isInvalid())
09602       return StmtError();
09603 
09604     // Build the call to the assignment operator.
09605 
09606     Expr *FromInst = From.build(S, Loc);
09607     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
09608                                                   OpEqualRef.getAs<Expr>(),
09609                                                   Loc, FromInst, Loc);
09610     if (Call.isInvalid())
09611       return StmtError();
09612 
09613     // If we built a call to a trivial 'operator=' while copying an array,
09614     // bail out. We'll replace the whole shebang with a memcpy.
09615     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
09616     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
09617       return StmtResult((Stmt*)nullptr);
09618 
09619     // Convert to an expression-statement, and clean up any produced
09620     // temporaries.
09621     return S.ActOnExprStmt(Call);
09622   }
09623 
09624   //     - if the subobject is of scalar type, the built-in assignment
09625   //       operator is used.
09626   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
09627   if (!ArrayTy) {
09628     ExprResult Assignment = S.CreateBuiltinBinOp(
09629         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
09630     if (Assignment.isInvalid())
09631       return StmtError();
09632     return S.ActOnExprStmt(Assignment);
09633   }
09634 
09635   //     - if the subobject is an array, each element is assigned, in the
09636   //       manner appropriate to the element type;
09637 
09638   // Construct a loop over the array bounds, e.g.,
09639   //
09640   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
09641   //
09642   // that will copy each of the array elements. 
09643   QualType SizeType = S.Context.getSizeType();
09644 
09645   // Create the iteration variable.
09646   IdentifierInfo *IterationVarName = nullptr;
09647   {
09648     SmallString<8> Str;
09649     llvm::raw_svector_ostream OS(Str);
09650     OS << "__i" << Depth;
09651     IterationVarName = &S.Context.Idents.get(OS.str());
09652   }
09653   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
09654                                           IterationVarName, SizeType,
09655                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
09656                                           SC_None);
09657 
09658   // Initialize the iteration variable to zero.
09659   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
09660   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
09661 
09662   // Creates a reference to the iteration variable.
09663   RefBuilder IterationVarRef(IterationVar, SizeType);
09664   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
09665 
09666   // Create the DeclStmt that holds the iteration variable.
09667   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
09668 
09669   // Subscript the "from" and "to" expressions with the iteration variable.
09670   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
09671   MoveCastBuilder FromIndexMove(FromIndexCopy);
09672   const ExprBuilder *FromIndex;
09673   if (Copying)
09674     FromIndex = &FromIndexCopy;
09675   else
09676     FromIndex = &FromIndexMove;
09677 
09678   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
09679 
09680   // Build the copy/move for an individual element of the array.
09681   StmtResult Copy =
09682     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
09683                                      ToIndex, *FromIndex, CopyingBaseSubobject,
09684                                      Copying, Depth + 1);
09685   // Bail out if copying fails or if we determined that we should use memcpy.
09686   if (Copy.isInvalid() || !Copy.get())
09687     return Copy;
09688 
09689   // Create the comparison against the array bound.
09690   llvm::APInt Upper
09691     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
09692   Expr *Comparison
09693     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
09694                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
09695                                      BO_NE, S.Context.BoolTy,
09696                                      VK_RValue, OK_Ordinary, Loc, false);
09697 
09698   // Create the pre-increment of the iteration variable.
09699   Expr *Increment
09700     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
09701                                     SizeType, VK_LValue, OK_Ordinary, Loc);
09702 
09703   // Construct the loop that copies all elements of this array.
09704   return S.ActOnForStmt(Loc, Loc, InitStmt, 
09705                         S.MakeFullExpr(Comparison),
09706                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
09707                         Loc, Copy.get());
09708 }
09709 
09710 static StmtResult
09711 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
09712                       const ExprBuilder &To, const ExprBuilder &From,
09713                       bool CopyingBaseSubobject, bool Copying) {
09714   // Maybe we should use a memcpy?
09715   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
09716       T.isTriviallyCopyableType(S.Context))
09717     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
09718 
09719   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
09720                                                      CopyingBaseSubobject,
09721                                                      Copying, 0));
09722 
09723   // If we ended up picking a trivial assignment operator for an array of a
09724   // non-trivially-copyable class type, just emit a memcpy.
09725   if (!Result.isInvalid() && !Result.get())
09726     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
09727 
09728   return Result;
09729 }
09730 
09731 Sema::ImplicitExceptionSpecification
09732 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
09733   CXXRecordDecl *ClassDecl = MD->getParent();
09734 
09735   ImplicitExceptionSpecification ExceptSpec(*this);
09736   if (ClassDecl->isInvalidDecl())
09737     return ExceptSpec;
09738 
09739   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
09740   assert(T->getNumParams() == 1 && "not a copy assignment op");
09741   unsigned ArgQuals =
09742       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
09743 
09744   // C++ [except.spec]p14:
09745   //   An implicitly declared special member function (Clause 12) shall have an
09746   //   exception-specification. [...]
09747 
09748   // It is unspecified whether or not an implicit copy assignment operator
09749   // attempts to deduplicate calls to assignment operators of virtual bases are
09750   // made. As such, this exception specification is effectively unspecified.
09751   // Based on a similar decision made for constness in C++0x, we're erring on
09752   // the side of assuming such calls to be made regardless of whether they
09753   // actually happen.
09754   for (const auto &Base : ClassDecl->bases()) {
09755     if (Base.isVirtual())
09756       continue;
09757 
09758     CXXRecordDecl *BaseClassDecl
09759       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
09760     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
09761                                                             ArgQuals, false, 0))
09762       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
09763   }
09764 
09765   for (const auto &Base : ClassDecl->vbases()) {
09766     CXXRecordDecl *BaseClassDecl
09767       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
09768     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
09769                                                             ArgQuals, false, 0))
09770       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
09771   }
09772 
09773   for (const auto *Field : ClassDecl->fields()) {
09774     QualType FieldType = Context.getBaseElementType(Field->getType());
09775     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
09776       if (CXXMethodDecl *CopyAssign =
09777           LookupCopyingAssignment(FieldClassDecl,
09778                                   ArgQuals | FieldType.getCVRQualifiers(),
09779                                   false, 0))
09780         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
09781     }
09782   }
09783 
09784   return ExceptSpec;
09785 }
09786 
09787 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
09788   // Note: The following rules are largely analoguous to the copy
09789   // constructor rules. Note that virtual bases are not taken into account
09790   // for determining the argument type of the operator. Note also that
09791   // operators taking an object instead of a reference are allowed.
09792   assert(ClassDecl->needsImplicitCopyAssignment());
09793 
09794   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
09795   if (DSM.isAlreadyBeingDeclared())
09796     return nullptr;
09797 
09798   QualType ArgType = Context.getTypeDeclType(ClassDecl);
09799   QualType RetType = Context.getLValueReferenceType(ArgType);
09800   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
09801   if (Const)
09802     ArgType = ArgType.withConst();
09803   ArgType = Context.getLValueReferenceType(ArgType);
09804 
09805   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
09806                                                      CXXCopyAssignment,
09807                                                      Const);
09808 
09809   //   An implicitly-declared copy assignment operator is an inline public
09810   //   member of its class.
09811   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
09812   SourceLocation ClassLoc = ClassDecl->getLocation();
09813   DeclarationNameInfo NameInfo(Name, ClassLoc);
09814   CXXMethodDecl *CopyAssignment =
09815       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
09816                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
09817                             /*isInline=*/true, Constexpr, SourceLocation());
09818   CopyAssignment->setAccess(AS_public);
09819   CopyAssignment->setDefaulted();
09820   CopyAssignment->setImplicit();
09821 
09822   if (getLangOpts().CUDA) {
09823     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
09824                                             CopyAssignment,
09825                                             /* ConstRHS */ Const,
09826                                             /* Diagnose */ false);
09827   }
09828 
09829   // Build an exception specification pointing back at this member.
09830   FunctionProtoType::ExtProtoInfo EPI =
09831       getImplicitMethodEPI(*this, CopyAssignment);
09832   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
09833 
09834   // Add the parameter to the operator.
09835   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
09836                                                ClassLoc, ClassLoc,
09837                                                /*Id=*/nullptr, ArgType,
09838                                                /*TInfo=*/nullptr, SC_None,
09839                                                nullptr);
09840   CopyAssignment->setParams(FromParam);
09841 
09842   AddOverriddenMethods(ClassDecl, CopyAssignment);
09843 
09844   CopyAssignment->setTrivial(
09845     ClassDecl->needsOverloadResolutionForCopyAssignment()
09846       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
09847       : ClassDecl->hasTrivialCopyAssignment());
09848 
09849   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
09850     SetDeclDeleted(CopyAssignment, ClassLoc);
09851 
09852   // Note that we have added this copy-assignment operator.
09853   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
09854 
09855   if (Scope *S = getScopeForContext(ClassDecl))
09856     PushOnScopeChains(CopyAssignment, S, false);
09857   ClassDecl->addDecl(CopyAssignment);
09858 
09859   return CopyAssignment;
09860 }
09861 
09862 /// Diagnose an implicit copy operation for a class which is odr-used, but
09863 /// which is deprecated because the class has a user-declared copy constructor,
09864 /// copy assignment operator, or destructor.
09865 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
09866                                             SourceLocation UseLoc) {
09867   assert(CopyOp->isImplicit());
09868 
09869   CXXRecordDecl *RD = CopyOp->getParent();
09870   CXXMethodDecl *UserDeclaredOperation = nullptr;
09871 
09872   // In Microsoft mode, assignment operations don't affect constructors and
09873   // vice versa.
09874   if (RD->hasUserDeclaredDestructor()) {
09875     UserDeclaredOperation = RD->getDestructor();
09876   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
09877              RD->hasUserDeclaredCopyConstructor() &&
09878              !S.getLangOpts().MSVCCompat) {
09879     // Find any user-declared copy constructor.
09880     for (auto *I : RD->ctors()) {
09881       if (I->isCopyConstructor()) {
09882         UserDeclaredOperation = I;
09883         break;
09884       }
09885     }
09886     assert(UserDeclaredOperation);
09887   } else if (isa<CXXConstructorDecl>(CopyOp) &&
09888              RD->hasUserDeclaredCopyAssignment() &&
09889              !S.getLangOpts().MSVCCompat) {
09890     // Find any user-declared move assignment operator.
09891     for (auto *I : RD->methods()) {
09892       if (I->isCopyAssignmentOperator()) {
09893         UserDeclaredOperation = I;
09894         break;
09895       }
09896     }
09897     assert(UserDeclaredOperation);
09898   }
09899 
09900   if (UserDeclaredOperation) {
09901     S.Diag(UserDeclaredOperation->getLocation(),
09902          diag::warn_deprecated_copy_operation)
09903       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
09904       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
09905     S.Diag(UseLoc, diag::note_member_synthesized_at)
09906       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
09907                                           : Sema::CXXCopyAssignment)
09908       << RD;
09909   }
09910 }
09911 
09912 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
09913                                         CXXMethodDecl *CopyAssignOperator) {
09914   assert((CopyAssignOperator->isDefaulted() && 
09915           CopyAssignOperator->isOverloadedOperator() &&
09916           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
09917           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
09918           !CopyAssignOperator->isDeleted()) &&
09919          "DefineImplicitCopyAssignment called for wrong function");
09920 
09921   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
09922 
09923   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
09924     CopyAssignOperator->setInvalidDecl();
09925     return;
09926   }
09927 
09928   // C++11 [class.copy]p18:
09929   //   The [definition of an implicitly declared copy assignment operator] is
09930   //   deprecated if the class has a user-declared copy constructor or a
09931   //   user-declared destructor.
09932   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
09933     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
09934 
09935   CopyAssignOperator->markUsed(Context);
09936 
09937   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
09938   DiagnosticErrorTrap Trap(Diags);
09939 
09940   // C++0x [class.copy]p30:
09941   //   The implicitly-defined or explicitly-defaulted copy assignment operator
09942   //   for a non-union class X performs memberwise copy assignment of its 
09943   //   subobjects. The direct base classes of X are assigned first, in the 
09944   //   order of their declaration in the base-specifier-list, and then the 
09945   //   immediate non-static data members of X are assigned, in the order in 
09946   //   which they were declared in the class definition.
09947   
09948   // The statements that form the synthesized function body.
09949   SmallVector<Stmt*, 8> Statements;
09950   
09951   // The parameter for the "other" object, which we are copying from.
09952   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
09953   Qualifiers OtherQuals = Other->getType().getQualifiers();
09954   QualType OtherRefType = Other->getType();
09955   if (const LValueReferenceType *OtherRef
09956                                 = OtherRefType->getAs<LValueReferenceType>()) {
09957     OtherRefType = OtherRef->getPointeeType();
09958     OtherQuals = OtherRefType.getQualifiers();
09959   }
09960   
09961   // Our location for everything implicitly-generated.
09962   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
09963                            ? CopyAssignOperator->getLocEnd()
09964                            : CopyAssignOperator->getLocation();
09965 
09966   // Builds a DeclRefExpr for the "other" object.
09967   RefBuilder OtherRef(Other, OtherRefType);
09968 
09969   // Builds the "this" pointer.
09970   ThisBuilder This;
09971   
09972   // Assign base classes.
09973   bool Invalid = false;
09974   for (auto &Base : ClassDecl->bases()) {
09975     // Form the assignment:
09976     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
09977     QualType BaseType = Base.getType().getUnqualifiedType();
09978     if (!BaseType->isRecordType()) {
09979       Invalid = true;
09980       continue;
09981     }
09982 
09983     CXXCastPath BasePath;
09984     BasePath.push_back(&Base);
09985 
09986     // Construct the "from" expression, which is an implicit cast to the
09987     // appropriately-qualified base type.
09988     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
09989                      VK_LValue, BasePath);
09990 
09991     // Dereference "this".
09992     DerefBuilder DerefThis(This);
09993     CastBuilder To(DerefThis,
09994                    Context.getCVRQualifiedType(
09995                        BaseType, CopyAssignOperator->getTypeQualifiers()),
09996                    VK_LValue, BasePath);
09997 
09998     // Build the copy.
09999     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10000                                             To, From,
10001                                             /*CopyingBaseSubobject=*/true,
10002                                             /*Copying=*/true);
10003     if (Copy.isInvalid()) {
10004       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10005         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10006       CopyAssignOperator->setInvalidDecl();
10007       return;
10008     }
10009     
10010     // Success! Record the copy.
10011     Statements.push_back(Copy.getAs<Expr>());
10012   }
10013   
10014   // Assign non-static members.
10015   for (auto *Field : ClassDecl->fields()) {
10016     if (Field->isUnnamedBitfield())
10017       continue;
10018 
10019     if (Field->isInvalidDecl()) {
10020       Invalid = true;
10021       continue;
10022     }
10023 
10024     // Check for members of reference type; we can't copy those.
10025     if (Field->getType()->isReferenceType()) {
10026       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10027         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10028       Diag(Field->getLocation(), diag::note_declared_at);
10029       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10030         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10031       Invalid = true;
10032       continue;
10033     }
10034     
10035     // Check for members of const-qualified, non-class type.
10036     QualType BaseType = Context.getBaseElementType(Field->getType());
10037     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10038       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10039         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10040       Diag(Field->getLocation(), diag::note_declared_at);
10041       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10042         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10043       Invalid = true;      
10044       continue;
10045     }
10046 
10047     // Suppress assigning zero-width bitfields.
10048     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10049       continue;
10050     
10051     QualType FieldType = Field->getType().getNonReferenceType();
10052     if (FieldType->isIncompleteArrayType()) {
10053       assert(ClassDecl->hasFlexibleArrayMember() && 
10054              "Incomplete array type is not valid");
10055       continue;
10056     }
10057     
10058     // Build references to the field in the object we're copying from and to.
10059     CXXScopeSpec SS; // Intentionally empty
10060     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10061                               LookupMemberName);
10062     MemberLookup.addDecl(Field);
10063     MemberLookup.resolveKind();
10064 
10065     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10066 
10067     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10068 
10069     // Build the copy of this field.
10070     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10071                                             To, From,
10072                                             /*CopyingBaseSubobject=*/false,
10073                                             /*Copying=*/true);
10074     if (Copy.isInvalid()) {
10075       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10076         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10077       CopyAssignOperator->setInvalidDecl();
10078       return;
10079     }
10080     
10081     // Success! Record the copy.
10082     Statements.push_back(Copy.getAs<Stmt>());
10083   }
10084 
10085   if (!Invalid) {
10086     // Add a "return *this;"
10087     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10088     
10089     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10090     if (Return.isInvalid())
10091       Invalid = true;
10092     else {
10093       Statements.push_back(Return.getAs<Stmt>());
10094 
10095       if (Trap.hasErrorOccurred()) {
10096         Diag(CurrentLocation, diag::note_member_synthesized_at) 
10097           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10098         Invalid = true;
10099       }
10100     }
10101   }
10102 
10103   // The exception specification is needed because we are defining the
10104   // function.
10105   ResolveExceptionSpec(CurrentLocation,
10106                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10107 
10108   if (Invalid) {
10109     CopyAssignOperator->setInvalidDecl();
10110     return;
10111   }
10112 
10113   StmtResult Body;
10114   {
10115     CompoundScopeRAII CompoundScope(*this);
10116     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10117                              /*isStmtExpr=*/false);
10118     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10119   }
10120   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10121 
10122   if (ASTMutationListener *L = getASTMutationListener()) {
10123     L->CompletedImplicitDefinition(CopyAssignOperator);
10124   }
10125 }
10126 
10127 Sema::ImplicitExceptionSpecification
10128 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10129   CXXRecordDecl *ClassDecl = MD->getParent();
10130 
10131   ImplicitExceptionSpecification ExceptSpec(*this);
10132   if (ClassDecl->isInvalidDecl())
10133     return ExceptSpec;
10134 
10135   // C++0x [except.spec]p14:
10136   //   An implicitly declared special member function (Clause 12) shall have an 
10137   //   exception-specification. [...]
10138 
10139   // It is unspecified whether or not an implicit move assignment operator
10140   // attempts to deduplicate calls to assignment operators of virtual bases are
10141   // made. As such, this exception specification is effectively unspecified.
10142   // Based on a similar decision made for constness in C++0x, we're erring on
10143   // the side of assuming such calls to be made regardless of whether they
10144   // actually happen.
10145   // Note that a move constructor is not implicitly declared when there are
10146   // virtual bases, but it can still be user-declared and explicitly defaulted.
10147   for (const auto &Base : ClassDecl->bases()) {
10148     if (Base.isVirtual())
10149       continue;
10150 
10151     CXXRecordDecl *BaseClassDecl
10152       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10153     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10154                                                            0, false, 0))
10155       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10156   }
10157 
10158   for (const auto &Base : ClassDecl->vbases()) {
10159     CXXRecordDecl *BaseClassDecl
10160       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10161     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10162                                                            0, false, 0))
10163       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10164   }
10165 
10166   for (const auto *Field : ClassDecl->fields()) {
10167     QualType FieldType = Context.getBaseElementType(Field->getType());
10168     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10169       if (CXXMethodDecl *MoveAssign =
10170               LookupMovingAssignment(FieldClassDecl,
10171                                      FieldType.getCVRQualifiers(),
10172                                      false, 0))
10173         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10174     }
10175   }
10176 
10177   return ExceptSpec;
10178 }
10179 
10180 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10181   assert(ClassDecl->needsImplicitMoveAssignment());
10182 
10183   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10184   if (DSM.isAlreadyBeingDeclared())
10185     return nullptr;
10186 
10187   // Note: The following rules are largely analoguous to the move
10188   // constructor rules.
10189 
10190   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10191   QualType RetType = Context.getLValueReferenceType(ArgType);
10192   ArgType = Context.getRValueReferenceType(ArgType);
10193 
10194   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10195                                                      CXXMoveAssignment,
10196                                                      false);
10197 
10198   //   An implicitly-declared move assignment operator is an inline public
10199   //   member of its class.
10200   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10201   SourceLocation ClassLoc = ClassDecl->getLocation();
10202   DeclarationNameInfo NameInfo(Name, ClassLoc);
10203   CXXMethodDecl *MoveAssignment =
10204       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10205                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10206                             /*isInline=*/true, Constexpr, SourceLocation());
10207   MoveAssignment->setAccess(AS_public);
10208   MoveAssignment->setDefaulted();
10209   MoveAssignment->setImplicit();
10210 
10211   if (getLangOpts().CUDA) {
10212     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10213                                             MoveAssignment,
10214                                             /* ConstRHS */ false,
10215                                             /* Diagnose */ false);
10216   }
10217 
10218   // Build an exception specification pointing back at this member.
10219   FunctionProtoType::ExtProtoInfo EPI =
10220       getImplicitMethodEPI(*this, MoveAssignment);
10221   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10222 
10223   // Add the parameter to the operator.
10224   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10225                                                ClassLoc, ClassLoc,
10226                                                /*Id=*/nullptr, ArgType,
10227                                                /*TInfo=*/nullptr, SC_None,
10228                                                nullptr);
10229   MoveAssignment->setParams(FromParam);
10230 
10231   AddOverriddenMethods(ClassDecl, MoveAssignment);
10232 
10233   MoveAssignment->setTrivial(
10234     ClassDecl->needsOverloadResolutionForMoveAssignment()
10235       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10236       : ClassDecl->hasTrivialMoveAssignment());
10237 
10238   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10239     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10240     SetDeclDeleted(MoveAssignment, ClassLoc);
10241   }
10242 
10243   // Note that we have added this copy-assignment operator.
10244   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10245 
10246   if (Scope *S = getScopeForContext(ClassDecl))
10247     PushOnScopeChains(MoveAssignment, S, false);
10248   ClassDecl->addDecl(MoveAssignment);
10249 
10250   return MoveAssignment;
10251 }
10252 
10253 /// Check if we're implicitly defining a move assignment operator for a class
10254 /// with virtual bases. Such a move assignment might move-assign the virtual
10255 /// base multiple times.
10256 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10257                                                SourceLocation CurrentLocation) {
10258   assert(!Class->isDependentContext() && "should not define dependent move");
10259 
10260   // Only a virtual base could get implicitly move-assigned multiple times.
10261   // Only a non-trivial move assignment can observe this. We only want to
10262   // diagnose if we implicitly define an assignment operator that assigns
10263   // two base classes, both of which move-assign the same virtual base.
10264   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10265       Class->getNumBases() < 2)
10266     return;
10267 
10268   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10269   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10270   VBaseMap VBases;
10271 
10272   for (auto &BI : Class->bases()) {
10273     Worklist.push_back(&BI);
10274     while (!Worklist.empty()) {
10275       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10276       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10277 
10278       // If the base has no non-trivial move assignment operators,
10279       // we don't care about moves from it.
10280       if (!Base->hasNonTrivialMoveAssignment())
10281         continue;
10282 
10283       // If there's nothing virtual here, skip it.
10284       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10285         continue;
10286 
10287       // If we're not actually going to call a move assignment for this base,
10288       // or the selected move assignment is trivial, skip it.
10289       Sema::SpecialMemberOverloadResult *SMOR =
10290         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10291                               /*ConstArg*/false, /*VolatileArg*/false,
10292                               /*RValueThis*/true, /*ConstThis*/false,
10293                               /*VolatileThis*/false);
10294       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10295           !SMOR->getMethod()->isMoveAssignmentOperator())
10296         continue;
10297 
10298       if (BaseSpec->isVirtual()) {
10299         // We're going to move-assign this virtual base, and its move
10300         // assignment operator is not trivial. If this can happen for
10301         // multiple distinct direct bases of Class, diagnose it. (If it
10302         // only happens in one base, we'll diagnose it when synthesizing
10303         // that base class's move assignment operator.)
10304         CXXBaseSpecifier *&Existing =
10305             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10306                 .first->second;
10307         if (Existing && Existing != &BI) {
10308           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10309             << Class << Base;
10310           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10311             << (Base->getCanonicalDecl() ==
10312                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10313             << Base << Existing->getType() << Existing->getSourceRange();
10314           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10315             << (Base->getCanonicalDecl() ==
10316                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10317             << Base << BI.getType() << BaseSpec->getSourceRange();
10318 
10319           // Only diagnose each vbase once.
10320           Existing = nullptr;
10321         }
10322       } else {
10323         // Only walk over bases that have defaulted move assignment operators.
10324         // We assume that any user-provided move assignment operator handles
10325         // the multiple-moves-of-vbase case itself somehow.
10326         if (!SMOR->getMethod()->isDefaulted())
10327           continue;
10328 
10329         // We're going to move the base classes of Base. Add them to the list.
10330         for (auto &BI : Base->bases())
10331           Worklist.push_back(&BI);
10332       }
10333     }
10334   }
10335 }
10336 
10337 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10338                                         CXXMethodDecl *MoveAssignOperator) {
10339   assert((MoveAssignOperator->isDefaulted() && 
10340           MoveAssignOperator->isOverloadedOperator() &&
10341           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10342           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10343           !MoveAssignOperator->isDeleted()) &&
10344          "DefineImplicitMoveAssignment called for wrong function");
10345 
10346   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10347 
10348   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10349     MoveAssignOperator->setInvalidDecl();
10350     return;
10351   }
10352   
10353   MoveAssignOperator->markUsed(Context);
10354 
10355   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10356   DiagnosticErrorTrap Trap(Diags);
10357 
10358   // C++0x [class.copy]p28:
10359   //   The implicitly-defined or move assignment operator for a non-union class
10360   //   X performs memberwise move assignment of its subobjects. The direct base
10361   //   classes of X are assigned first, in the order of their declaration in the
10362   //   base-specifier-list, and then the immediate non-static data members of X
10363   //   are assigned, in the order in which they were declared in the class
10364   //   definition.
10365 
10366   // Issue a warning if our implicit move assignment operator will move
10367   // from a virtual base more than once.
10368   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10369 
10370   // The statements that form the synthesized function body.
10371   SmallVector<Stmt*, 8> Statements;
10372 
10373   // The parameter for the "other" object, which we are move from.
10374   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10375   QualType OtherRefType = Other->getType()->
10376       getAs<RValueReferenceType>()->getPointeeType();
10377   assert(!OtherRefType.getQualifiers() &&
10378          "Bad argument type of defaulted move assignment");
10379 
10380   // Our location for everything implicitly-generated.
10381   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10382                            ? MoveAssignOperator->getLocEnd()
10383                            : MoveAssignOperator->getLocation();
10384 
10385   // Builds a reference to the "other" object.
10386   RefBuilder OtherRef(Other, OtherRefType);
10387   // Cast to rvalue.
10388   MoveCastBuilder MoveOther(OtherRef);
10389 
10390   // Builds the "this" pointer.
10391   ThisBuilder This;
10392 
10393   // Assign base classes.
10394   bool Invalid = false;
10395   for (auto &Base : ClassDecl->bases()) {
10396     // C++11 [class.copy]p28:
10397     //   It is unspecified whether subobjects representing virtual base classes
10398     //   are assigned more than once by the implicitly-defined copy assignment
10399     //   operator.
10400     // FIXME: Do not assign to a vbase that will be assigned by some other base
10401     // class. For a move-assignment, this can result in the vbase being moved
10402     // multiple times.
10403 
10404     // Form the assignment:
10405     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10406     QualType BaseType = Base.getType().getUnqualifiedType();
10407     if (!BaseType->isRecordType()) {
10408       Invalid = true;
10409       continue;
10410     }
10411 
10412     CXXCastPath BasePath;
10413     BasePath.push_back(&Base);
10414 
10415     // Construct the "from" expression, which is an implicit cast to the
10416     // appropriately-qualified base type.
10417     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10418 
10419     // Dereference "this".
10420     DerefBuilder DerefThis(This);
10421 
10422     // Implicitly cast "this" to the appropriately-qualified base type.
10423     CastBuilder To(DerefThis,
10424                    Context.getCVRQualifiedType(
10425                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10426                    VK_LValue, BasePath);
10427 
10428     // Build the move.
10429     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10430                                             To, From,
10431                                             /*CopyingBaseSubobject=*/true,
10432                                             /*Copying=*/false);
10433     if (Move.isInvalid()) {
10434       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10435         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10436       MoveAssignOperator->setInvalidDecl();
10437       return;
10438     }
10439 
10440     // Success! Record the move.
10441     Statements.push_back(Move.getAs<Expr>());
10442   }
10443 
10444   // Assign non-static members.
10445   for (auto *Field : ClassDecl->fields()) {
10446     if (Field->isUnnamedBitfield())
10447       continue;
10448 
10449     if (Field->isInvalidDecl()) {
10450       Invalid = true;
10451       continue;
10452     }
10453 
10454     // Check for members of reference type; we can't move those.
10455     if (Field->getType()->isReferenceType()) {
10456       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10457         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10458       Diag(Field->getLocation(), diag::note_declared_at);
10459       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10460         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10461       Invalid = true;
10462       continue;
10463     }
10464 
10465     // Check for members of const-qualified, non-class type.
10466     QualType BaseType = Context.getBaseElementType(Field->getType());
10467     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10468       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10469         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10470       Diag(Field->getLocation(), diag::note_declared_at);
10471       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10472         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10473       Invalid = true;      
10474       continue;
10475     }
10476 
10477     // Suppress assigning zero-width bitfields.
10478     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10479       continue;
10480     
10481     QualType FieldType = Field->getType().getNonReferenceType();
10482     if (FieldType->isIncompleteArrayType()) {
10483       assert(ClassDecl->hasFlexibleArrayMember() && 
10484              "Incomplete array type is not valid");
10485       continue;
10486     }
10487     
10488     // Build references to the field in the object we're copying from and to.
10489     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10490                               LookupMemberName);
10491     MemberLookup.addDecl(Field);
10492     MemberLookup.resolveKind();
10493     MemberBuilder From(MoveOther, OtherRefType,
10494                        /*IsArrow=*/false, MemberLookup);
10495     MemberBuilder To(This, getCurrentThisType(),
10496                      /*IsArrow=*/true, MemberLookup);
10497 
10498     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10499         "Member reference with rvalue base must be rvalue except for reference "
10500         "members, which aren't allowed for move assignment.");
10501 
10502     // Build the move of this field.
10503     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10504                                             To, From,
10505                                             /*CopyingBaseSubobject=*/false,
10506                                             /*Copying=*/false);
10507     if (Move.isInvalid()) {
10508       Diag(CurrentLocation, diag::note_member_synthesized_at) 
10509         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10510       MoveAssignOperator->setInvalidDecl();
10511       return;
10512     }
10513 
10514     // Success! Record the copy.
10515     Statements.push_back(Move.getAs<Stmt>());
10516   }
10517 
10518   if (!Invalid) {
10519     // Add a "return *this;"
10520     ExprResult ThisObj =
10521         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10522 
10523     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10524     if (Return.isInvalid())
10525       Invalid = true;
10526     else {
10527       Statements.push_back(Return.getAs<Stmt>());
10528 
10529       if (Trap.hasErrorOccurred()) {
10530         Diag(CurrentLocation, diag::note_member_synthesized_at) 
10531           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10532         Invalid = true;
10533       }
10534     }
10535   }
10536 
10537   // The exception specification is needed because we are defining the
10538   // function.
10539   ResolveExceptionSpec(CurrentLocation,
10540                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10541 
10542   if (Invalid) {
10543     MoveAssignOperator->setInvalidDecl();
10544     return;
10545   }
10546 
10547   StmtResult Body;
10548   {
10549     CompoundScopeRAII CompoundScope(*this);
10550     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10551                              /*isStmtExpr=*/false);
10552     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10553   }
10554   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10555 
10556   if (ASTMutationListener *L = getASTMutationListener()) {
10557     L->CompletedImplicitDefinition(MoveAssignOperator);
10558   }
10559 }
10560 
10561 Sema::ImplicitExceptionSpecification
10562 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10563   CXXRecordDecl *ClassDecl = MD->getParent();
10564 
10565   ImplicitExceptionSpecification ExceptSpec(*this);
10566   if (ClassDecl->isInvalidDecl())
10567     return ExceptSpec;
10568 
10569   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10570   assert(T->getNumParams() >= 1 && "not a copy ctor");
10571   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10572 
10573   // C++ [except.spec]p14:
10574   //   An implicitly declared special member function (Clause 12) shall have an 
10575   //   exception-specification. [...]
10576   for (const auto &Base : ClassDecl->bases()) {
10577     // Virtual bases are handled below.
10578     if (Base.isVirtual())
10579       continue;
10580     
10581     CXXRecordDecl *BaseClassDecl
10582       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10583     if (CXXConstructorDecl *CopyConstructor =
10584           LookupCopyingConstructor(BaseClassDecl, Quals))
10585       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10586   }
10587   for (const auto &Base : ClassDecl->vbases()) {
10588     CXXRecordDecl *BaseClassDecl
10589       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10590     if (CXXConstructorDecl *CopyConstructor =
10591           LookupCopyingConstructor(BaseClassDecl, Quals))
10592       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10593   }
10594   for (const auto *Field : ClassDecl->fields()) {
10595     QualType FieldType = Context.getBaseElementType(Field->getType());
10596     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10597       if (CXXConstructorDecl *CopyConstructor =
10598               LookupCopyingConstructor(FieldClassDecl,
10599                                        Quals | FieldType.getCVRQualifiers()))
10600       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10601     }
10602   }
10603 
10604   return ExceptSpec;
10605 }
10606 
10607 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10608                                                     CXXRecordDecl *ClassDecl) {
10609   // C++ [class.copy]p4:
10610   //   If the class definition does not explicitly declare a copy
10611   //   constructor, one is declared implicitly.
10612   assert(ClassDecl->needsImplicitCopyConstructor());
10613 
10614   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10615   if (DSM.isAlreadyBeingDeclared())
10616     return nullptr;
10617 
10618   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10619   QualType ArgType = ClassType;
10620   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10621   if (Const)
10622     ArgType = ArgType.withConst();
10623   ArgType = Context.getLValueReferenceType(ArgType);
10624 
10625   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10626                                                      CXXCopyConstructor,
10627                                                      Const);
10628 
10629   DeclarationName Name
10630     = Context.DeclarationNames.getCXXConstructorName(
10631                                            Context.getCanonicalType(ClassType));
10632   SourceLocation ClassLoc = ClassDecl->getLocation();
10633   DeclarationNameInfo NameInfo(Name, ClassLoc);
10634 
10635   //   An implicitly-declared copy constructor is an inline public
10636   //   member of its class.
10637   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10638       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10639       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10640       Constexpr);
10641   CopyConstructor->setAccess(AS_public);
10642   CopyConstructor->setDefaulted();
10643 
10644   if (getLangOpts().CUDA) {
10645     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10646                                             CopyConstructor,
10647                                             /* ConstRHS */ Const,
10648                                             /* Diagnose */ false);
10649   }
10650 
10651   // Build an exception specification pointing back at this member.
10652   FunctionProtoType::ExtProtoInfo EPI =
10653       getImplicitMethodEPI(*this, CopyConstructor);
10654   CopyConstructor->setType(
10655       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10656 
10657   // Add the parameter to the constructor.
10658   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10659                                                ClassLoc, ClassLoc,
10660                                                /*IdentifierInfo=*/nullptr,
10661                                                ArgType, /*TInfo=*/nullptr,
10662                                                SC_None, nullptr);
10663   CopyConstructor->setParams(FromParam);
10664 
10665   CopyConstructor->setTrivial(
10666     ClassDecl->needsOverloadResolutionForCopyConstructor()
10667       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10668       : ClassDecl->hasTrivialCopyConstructor());
10669 
10670   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10671     SetDeclDeleted(CopyConstructor, ClassLoc);
10672 
10673   // Note that we have declared this constructor.
10674   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10675 
10676   if (Scope *S = getScopeForContext(ClassDecl))
10677     PushOnScopeChains(CopyConstructor, S, false);
10678   ClassDecl->addDecl(CopyConstructor);
10679 
10680   return CopyConstructor;
10681 }
10682 
10683 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10684                                    CXXConstructorDecl *CopyConstructor) {
10685   assert((CopyConstructor->isDefaulted() &&
10686           CopyConstructor->isCopyConstructor() &&
10687           !CopyConstructor->doesThisDeclarationHaveABody() &&
10688           !CopyConstructor->isDeleted()) &&
10689          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10690 
10691   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10692   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10693 
10694   // C++11 [class.copy]p7:
10695   //   The [definition of an implicitly declared copy constructor] is
10696   //   deprecated if the class has a user-declared copy assignment operator
10697   //   or a user-declared destructor.
10698   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10699     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10700 
10701   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10702   DiagnosticErrorTrap Trap(Diags);
10703 
10704   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10705       Trap.hasErrorOccurred()) {
10706     Diag(CurrentLocation, diag::note_member_synthesized_at) 
10707       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10708     CopyConstructor->setInvalidDecl();
10709   }  else {
10710     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10711                              ? CopyConstructor->getLocEnd()
10712                              : CopyConstructor->getLocation();
10713     Sema::CompoundScopeRAII CompoundScope(*this);
10714     CopyConstructor->setBody(
10715         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10716   }
10717 
10718   // The exception specification is needed because we are defining the
10719   // function.
10720   ResolveExceptionSpec(CurrentLocation,
10721                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10722 
10723   CopyConstructor->markUsed(Context);
10724   MarkVTableUsed(CurrentLocation, ClassDecl);
10725 
10726   if (ASTMutationListener *L = getASTMutationListener()) {
10727     L->CompletedImplicitDefinition(CopyConstructor);
10728   }
10729 }
10730 
10731 Sema::ImplicitExceptionSpecification
10732 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10733   CXXRecordDecl *ClassDecl = MD->getParent();
10734 
10735   // C++ [except.spec]p14:
10736   //   An implicitly declared special member function (Clause 12) shall have an 
10737   //   exception-specification. [...]
10738   ImplicitExceptionSpecification ExceptSpec(*this);
10739   if (ClassDecl->isInvalidDecl())
10740     return ExceptSpec;
10741 
10742   // Direct base-class constructors.
10743   for (const auto &B : ClassDecl->bases()) {
10744     if (B.isVirtual()) // Handled below.
10745       continue;
10746     
10747     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10748       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10749       CXXConstructorDecl *Constructor =
10750           LookupMovingConstructor(BaseClassDecl, 0);
10751       // If this is a deleted function, add it anyway. This might be conformant
10752       // with the standard. This might not. I'm not sure. It might not matter.
10753       if (Constructor)
10754         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10755     }
10756   }
10757 
10758   // Virtual base-class constructors.
10759   for (const auto &B : ClassDecl->vbases()) {
10760     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10761       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10762       CXXConstructorDecl *Constructor =
10763           LookupMovingConstructor(BaseClassDecl, 0);
10764       // If this is a deleted function, add it anyway. This might be conformant
10765       // with the standard. This might not. I'm not sure. It might not matter.
10766       if (Constructor)
10767         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10768     }
10769   }
10770 
10771   // Field constructors.
10772   for (const auto *F : ClassDecl->fields()) {
10773     QualType FieldType = Context.getBaseElementType(F->getType());
10774     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10775       CXXConstructorDecl *Constructor =
10776           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10777       // If this is a deleted function, add it anyway. This might be conformant
10778       // with the standard. This might not. I'm not sure. It might not matter.
10779       // In particular, the problem is that this function never gets called. It
10780       // might just be ill-formed because this function attempts to refer to
10781       // a deleted function here.
10782       if (Constructor)
10783         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10784     }
10785   }
10786 
10787   return ExceptSpec;
10788 }
10789 
10790 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10791                                                     CXXRecordDecl *ClassDecl) {
10792   assert(ClassDecl->needsImplicitMoveConstructor());
10793 
10794   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10795   if (DSM.isAlreadyBeingDeclared())
10796     return nullptr;
10797 
10798   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10799   QualType ArgType = Context.getRValueReferenceType(ClassType);
10800 
10801   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10802                                                      CXXMoveConstructor,
10803                                                      false);
10804 
10805   DeclarationName Name
10806     = Context.DeclarationNames.getCXXConstructorName(
10807                                            Context.getCanonicalType(ClassType));
10808   SourceLocation ClassLoc = ClassDecl->getLocation();
10809   DeclarationNameInfo NameInfo(Name, ClassLoc);
10810 
10811   // C++11 [class.copy]p11:
10812   //   An implicitly-declared copy/move constructor is an inline public
10813   //   member of its class.
10814   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10815       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10816       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10817       Constexpr);
10818   MoveConstructor->setAccess(AS_public);
10819   MoveConstructor->setDefaulted();
10820 
10821   if (getLangOpts().CUDA) {
10822     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10823                                             MoveConstructor,
10824                                             /* ConstRHS */ false,
10825                                             /* Diagnose */ false);
10826   }
10827 
10828   // Build an exception specification pointing back at this member.
10829   FunctionProtoType::ExtProtoInfo EPI =
10830       getImplicitMethodEPI(*this, MoveConstructor);
10831   MoveConstructor->setType(
10832       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10833 
10834   // Add the parameter to the constructor.
10835   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10836                                                ClassLoc, ClassLoc,
10837                                                /*IdentifierInfo=*/nullptr,
10838                                                ArgType, /*TInfo=*/nullptr,
10839                                                SC_None, nullptr);
10840   MoveConstructor->setParams(FromParam);
10841 
10842   MoveConstructor->setTrivial(
10843     ClassDecl->needsOverloadResolutionForMoveConstructor()
10844       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10845       : ClassDecl->hasTrivialMoveConstructor());
10846 
10847   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10848     ClassDecl->setImplicitMoveConstructorIsDeleted();
10849     SetDeclDeleted(MoveConstructor, ClassLoc);
10850   }
10851 
10852   // Note that we have declared this constructor.
10853   ++ASTContext::NumImplicitMoveConstructorsDeclared;
10854 
10855   if (Scope *S = getScopeForContext(ClassDecl))
10856     PushOnScopeChains(MoveConstructor, S, false);
10857   ClassDecl->addDecl(MoveConstructor);
10858 
10859   return MoveConstructor;
10860 }
10861 
10862 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10863                                    CXXConstructorDecl *MoveConstructor) {
10864   assert((MoveConstructor->isDefaulted() &&
10865           MoveConstructor->isMoveConstructor() &&
10866           !MoveConstructor->doesThisDeclarationHaveABody() &&
10867           !MoveConstructor->isDeleted()) &&
10868          "DefineImplicitMoveConstructor - call it for implicit move ctor");
10869 
10870   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10871   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10872 
10873   SynthesizedFunctionScope Scope(*this, MoveConstructor);
10874   DiagnosticErrorTrap Trap(Diags);
10875 
10876   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10877       Trap.hasErrorOccurred()) {
10878     Diag(CurrentLocation, diag::note_member_synthesized_at) 
10879       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10880     MoveConstructor->setInvalidDecl();
10881   }  else {
10882     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10883                              ? MoveConstructor->getLocEnd()
10884                              : MoveConstructor->getLocation();
10885     Sema::CompoundScopeRAII CompoundScope(*this);
10886     MoveConstructor->setBody(ActOnCompoundStmt(
10887         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
10888   }
10889 
10890   // The exception specification is needed because we are defining the
10891   // function.
10892   ResolveExceptionSpec(CurrentLocation,
10893                        MoveConstructor->getType()->castAs<FunctionProtoType>());
10894 
10895   MoveConstructor->markUsed(Context);
10896   MarkVTableUsed(CurrentLocation, ClassDecl);
10897 
10898   if (ASTMutationListener *L = getASTMutationListener()) {
10899     L->CompletedImplicitDefinition(MoveConstructor);
10900   }
10901 }
10902 
10903 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10904   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10905 }
10906 
10907 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10908                             SourceLocation CurrentLocation,
10909                             CXXConversionDecl *Conv) {
10910   CXXRecordDecl *Lambda = Conv->getParent();
10911   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10912   // If we are defining a specialization of a conversion to function-ptr
10913   // cache the deduced template arguments for this specialization
10914   // so that we can use them to retrieve the corresponding call-operator
10915   // and static-invoker. 
10916   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10917 
10918   // Retrieve the corresponding call-operator specialization.
10919   if (Lambda->isGenericLambda()) {
10920     assert(Conv->isFunctionTemplateSpecialization());
10921     FunctionTemplateDecl *CallOpTemplate = 
10922         CallOp->getDescribedFunctionTemplate();
10923     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10924     void *InsertPos = nullptr;
10925     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10926                                                 DeducedTemplateArgs->asArray(),
10927                                                 InsertPos);
10928     assert(CallOpSpec && 
10929           "Conversion operator must have a corresponding call operator");
10930     CallOp = cast<CXXMethodDecl>(CallOpSpec);
10931   }
10932   // Mark the call operator referenced (and add to pending instantiations
10933   // if necessary).
10934   // For both the conversion and static-invoker template specializations
10935   // we construct their body's in this function, so no need to add them
10936   // to the PendingInstantiations.
10937   MarkFunctionReferenced(CurrentLocation, CallOp);
10938 
10939   SynthesizedFunctionScope Scope(*this, Conv);
10940   DiagnosticErrorTrap Trap(Diags);
10941    
10942   // Retrieve the static invoker...
10943   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10944   // ... and get the corresponding specialization for a generic lambda.
10945   if (Lambda->isGenericLambda()) {
10946     assert(DeducedTemplateArgs && 
10947       "Must have deduced template arguments from Conversion Operator");
10948     FunctionTemplateDecl *InvokeTemplate = 
10949                           Invoker->getDescribedFunctionTemplate();
10950     void *InsertPos = nullptr;
10951     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10952                                                 DeducedTemplateArgs->asArray(),
10953                                                 InsertPos);
10954     assert(InvokeSpec && 
10955       "Must have a corresponding static invoker specialization");
10956     Invoker = cast<CXXMethodDecl>(InvokeSpec);
10957   }
10958   // Construct the body of the conversion function { return __invoke; }.
10959   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10960                                         VK_LValue, Conv->getLocation()).get();
10961    assert(FunctionRef && "Can't refer to __invoke function?");
10962    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
10963    Conv->setBody(new (Context) CompoundStmt(Context, Return,
10964                                             Conv->getLocation(),
10965                                             Conv->getLocation()));
10966 
10967   Conv->markUsed(Context);
10968   Conv->setReferenced();
10969   
10970   // Fill in the __invoke function with a dummy implementation. IR generation
10971   // will fill in the actual details.
10972   Invoker->markUsed(Context);
10973   Invoker->setReferenced();
10974   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10975    
10976   if (ASTMutationListener *L = getASTMutationListener()) {
10977     L->CompletedImplicitDefinition(Conv);
10978     L->CompletedImplicitDefinition(Invoker);
10979    }
10980 }
10981 
10982 
10983 
10984 void Sema::DefineImplicitLambdaToBlockPointerConversion(
10985        SourceLocation CurrentLocation,
10986        CXXConversionDecl *Conv) 
10987 {
10988   assert(!Conv->getParent()->isGenericLambda());
10989 
10990   Conv->markUsed(Context);
10991   
10992   SynthesizedFunctionScope Scope(*this, Conv);
10993   DiagnosticErrorTrap Trap(Diags);
10994   
10995   // Copy-initialize the lambda object as needed to capture it.
10996   Expr *This = ActOnCXXThis(CurrentLocation).get();
10997   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
10998   
10999   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11000                                                         Conv->getLocation(),
11001                                                         Conv, DerefThis);
11002 
11003   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11004   // behavior.  Note that only the general conversion function does this
11005   // (since it's unusable otherwise); in the case where we inline the
11006   // block literal, it has block literal lifetime semantics.
11007   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11008     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11009                                           CK_CopyAndAutoreleaseBlockObject,
11010                                           BuildBlock.get(), nullptr, VK_RValue);
11011 
11012   if (BuildBlock.isInvalid()) {
11013     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11014     Conv->setInvalidDecl();
11015     return;
11016   }
11017 
11018   // Create the return statement that returns the block from the conversion
11019   // function.
11020   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11021   if (Return.isInvalid()) {
11022     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11023     Conv->setInvalidDecl();
11024     return;
11025   }
11026 
11027   // Set the body of the conversion function.
11028   Stmt *ReturnS = Return.get();
11029   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11030                                            Conv->getLocation(), 
11031                                            Conv->getLocation()));
11032   
11033   // We're done; notify the mutation listener, if any.
11034   if (ASTMutationListener *L = getASTMutationListener()) {
11035     L->CompletedImplicitDefinition(Conv);
11036   }
11037 }
11038 
11039 /// \brief Determine whether the given list arguments contains exactly one 
11040 /// "real" (non-default) argument.
11041 static bool hasOneRealArgument(MultiExprArg Args) {
11042   switch (Args.size()) {
11043   case 0:
11044     return false;
11045     
11046   default:
11047     if (!Args[1]->isDefaultArgument())
11048       return false;
11049     
11050     // fall through
11051   case 1:
11052     return !Args[0]->isDefaultArgument();
11053   }
11054   
11055   return false;
11056 }
11057 
11058 ExprResult
11059 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11060                             CXXConstructorDecl *Constructor,
11061                             MultiExprArg ExprArgs,
11062                             bool HadMultipleCandidates,
11063                             bool IsListInitialization,
11064                             bool IsStdInitListInitialization,
11065                             bool RequiresZeroInit,
11066                             unsigned ConstructKind,
11067                             SourceRange ParenRange) {
11068   bool Elidable = false;
11069 
11070   // C++0x [class.copy]p34:
11071   //   When certain criteria are met, an implementation is allowed to
11072   //   omit the copy/move construction of a class object, even if the
11073   //   copy/move constructor and/or destructor for the object have
11074   //   side effects. [...]
11075   //     - when a temporary class object that has not been bound to a
11076   //       reference (12.2) would be copied/moved to a class object
11077   //       with the same cv-unqualified type, the copy/move operation
11078   //       can be omitted by constructing the temporary object
11079   //       directly into the target of the omitted copy/move
11080   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11081       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11082     Expr *SubExpr = ExprArgs[0];
11083     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11084   }
11085 
11086   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11087                                Elidable, ExprArgs, HadMultipleCandidates,
11088                                IsListInitialization,
11089                                IsStdInitListInitialization, RequiresZeroInit,
11090                                ConstructKind, ParenRange);
11091 }
11092 
11093 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11094 /// including handling of its default argument expressions.
11095 ExprResult
11096 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11097                             CXXConstructorDecl *Constructor, bool Elidable,
11098                             MultiExprArg ExprArgs,
11099                             bool HadMultipleCandidates,
11100                             bool IsListInitialization,
11101                             bool IsStdInitListInitialization,
11102                             bool RequiresZeroInit,
11103                             unsigned ConstructKind,
11104                             SourceRange ParenRange) {
11105   MarkFunctionReferenced(ConstructLoc, Constructor);
11106   return CXXConstructExpr::Create(
11107       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11108       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11109       RequiresZeroInit,
11110       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11111       ParenRange);
11112 }
11113 
11114 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11115   assert(Field->hasInClassInitializer());
11116 
11117   // If we already have the in-class initializer nothing needs to be done.
11118   if (Field->getInClassInitializer())
11119     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11120 
11121   // Maybe we haven't instantiated the in-class initializer. Go check the
11122   // pattern FieldDecl to see if it has one.
11123   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11124 
11125   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11126     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11127     DeclContext::lookup_result Lookup =
11128         ClassPattern->lookup(Field->getDeclName());
11129     assert(Lookup.size() == 1);
11130     FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11131     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11132                                       getTemplateInstantiationArgs(Field)))
11133       return ExprError();
11134     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11135   }
11136 
11137   // DR1351:
11138   //   If the brace-or-equal-initializer of a non-static data member
11139   //   invokes a defaulted default constructor of its class or of an
11140   //   enclosing class in a potentially evaluated subexpression, the
11141   //   program is ill-formed.
11142   //
11143   // This resolution is unworkable: the exception specification of the
11144   // default constructor can be needed in an unevaluated context, in
11145   // particular, in the operand of a noexcept-expression, and we can be
11146   // unable to compute an exception specification for an enclosed class.
11147   //
11148   // Any attempt to resolve the exception specification of a defaulted default
11149   // constructor before the initializer is lexically complete will ultimately
11150   // come here at which point we can diagnose it.
11151   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11152   if (OutermostClass == ParentRD) {
11153     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11154         << ParentRD << Field;
11155   } else {
11156     Diag(Field->getLocEnd(),
11157          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11158         << ParentRD << OutermostClass << Field;
11159   }
11160 
11161   return ExprError();
11162 }
11163 
11164 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11165   if (VD->isInvalidDecl()) return;
11166 
11167   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11168   if (ClassDecl->isInvalidDecl()) return;
11169   if (ClassDecl->hasIrrelevantDestructor()) return;
11170   if (ClassDecl->isDependentContext()) return;
11171 
11172   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11173   MarkFunctionReferenced(VD->getLocation(), Destructor);
11174   CheckDestructorAccess(VD->getLocation(), Destructor,
11175                         PDiag(diag::err_access_dtor_var)
11176                         << VD->getDeclName()
11177                         << VD->getType());
11178   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11179 
11180   if (Destructor->isTrivial()) return;
11181   if (!VD->hasGlobalStorage()) return;
11182 
11183   // Emit warning for non-trivial dtor in global scope (a real global,
11184   // class-static, function-static).
11185   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11186 
11187   // TODO: this should be re-enabled for static locals by !CXAAtExit
11188   if (!VD->isStaticLocal())
11189     Diag(VD->getLocation(), diag::warn_global_destructor);
11190 }
11191 
11192 /// \brief Given a constructor and the set of arguments provided for the
11193 /// constructor, convert the arguments and add any required default arguments
11194 /// to form a proper call to this constructor.
11195 ///
11196 /// \returns true if an error occurred, false otherwise.
11197 bool 
11198 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11199                               MultiExprArg ArgsPtr,
11200                               SourceLocation Loc,
11201                               SmallVectorImpl<Expr*> &ConvertedArgs,
11202                               bool AllowExplicit,
11203                               bool IsListInitialization) {
11204   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11205   unsigned NumArgs = ArgsPtr.size();
11206   Expr **Args = ArgsPtr.data();
11207 
11208   const FunctionProtoType *Proto 
11209     = Constructor->getType()->getAs<FunctionProtoType>();
11210   assert(Proto && "Constructor without a prototype?");
11211   unsigned NumParams = Proto->getNumParams();
11212 
11213   // If too few arguments are available, we'll fill in the rest with defaults.
11214   if (NumArgs < NumParams)
11215     ConvertedArgs.reserve(NumParams);
11216   else
11217     ConvertedArgs.reserve(NumArgs);
11218 
11219   VariadicCallType CallType = 
11220     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11221   SmallVector<Expr *, 8> AllArgs;
11222   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11223                                         Proto, 0,
11224                                         llvm::makeArrayRef(Args, NumArgs),
11225                                         AllArgs,
11226                                         CallType, AllowExplicit,
11227                                         IsListInitialization);
11228   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11229 
11230   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11231 
11232   CheckConstructorCall(Constructor,
11233                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11234                        Proto, Loc);
11235 
11236   return Invalid;
11237 }
11238 
11239 static inline bool
11240 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 
11241                                        const FunctionDecl *FnDecl) {
11242   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11243   if (isa<NamespaceDecl>(DC)) {
11244     return SemaRef.Diag(FnDecl->getLocation(), 
11245                         diag::err_operator_new_delete_declared_in_namespace)
11246       << FnDecl->getDeclName();
11247   }
11248   
11249   if (isa<TranslationUnitDecl>(DC) && 
11250       FnDecl->getStorageClass() == SC_Static) {
11251     return SemaRef.Diag(FnDecl->getLocation(),
11252                         diag::err_operator_new_delete_declared_static)
11253       << FnDecl->getDeclName();
11254   }
11255   
11256   return false;
11257 }
11258 
11259 static inline bool
11260 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11261                             CanQualType ExpectedResultType,
11262                             CanQualType ExpectedFirstParamType,
11263                             unsigned DependentParamTypeDiag,
11264                             unsigned InvalidParamTypeDiag) {
11265   QualType ResultType =
11266       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11267 
11268   // Check that the result type is not dependent.
11269   if (ResultType->isDependentType())
11270     return SemaRef.Diag(FnDecl->getLocation(),
11271                         diag::err_operator_new_delete_dependent_result_type)
11272     << FnDecl->getDeclName() << ExpectedResultType;
11273 
11274   // Check that the result type is what we expect.
11275   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11276     return SemaRef.Diag(FnDecl->getLocation(),
11277                         diag::err_operator_new_delete_invalid_result_type) 
11278     << FnDecl->getDeclName() << ExpectedResultType;
11279   
11280   // A function template must have at least 2 parameters.
11281   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11282     return SemaRef.Diag(FnDecl->getLocation(),
11283                       diag::err_operator_new_delete_template_too_few_parameters)
11284         << FnDecl->getDeclName();
11285   
11286   // The function decl must have at least 1 parameter.
11287   if (FnDecl->getNumParams() == 0)
11288     return SemaRef.Diag(FnDecl->getLocation(),
11289                         diag::err_operator_new_delete_too_few_parameters)
11290       << FnDecl->getDeclName();
11291  
11292   // Check the first parameter type is not dependent.
11293   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11294   if (FirstParamType->isDependentType())
11295     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11296       << FnDecl->getDeclName() << ExpectedFirstParamType;
11297 
11298   // Check that the first parameter type is what we expect.
11299   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 
11300       ExpectedFirstParamType)
11301     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11302     << FnDecl->getDeclName() << ExpectedFirstParamType;
11303   
11304   return false;
11305 }
11306 
11307 static bool
11308 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11309   // C++ [basic.stc.dynamic.allocation]p1:
11310   //   A program is ill-formed if an allocation function is declared in a
11311   //   namespace scope other than global scope or declared static in global 
11312   //   scope.
11313   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11314     return true;
11315 
11316   CanQualType SizeTy = 
11317     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11318 
11319   // C++ [basic.stc.dynamic.allocation]p1:
11320   //  The return type shall be void*. The first parameter shall have type 
11321   //  std::size_t.
11322   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 
11323                                   SizeTy,
11324                                   diag::err_operator_new_dependent_param_type,
11325                                   diag::err_operator_new_param_type))
11326     return true;
11327 
11328   // C++ [basic.stc.dynamic.allocation]p1:
11329   //  The first parameter shall not have an associated default argument.
11330   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11331     return SemaRef.Diag(FnDecl->getLocation(),
11332                         diag::err_operator_new_default_arg)
11333       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11334 
11335   return false;
11336 }
11337 
11338 static bool
11339 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11340   // C++ [basic.stc.dynamic.deallocation]p1:
11341   //   A program is ill-formed if deallocation functions are declared in a
11342   //   namespace scope other than global scope or declared static in global 
11343   //   scope.
11344   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11345     return true;
11346 
11347   // C++ [basic.stc.dynamic.deallocation]p2:
11348   //   Each deallocation function shall return void and its first parameter 
11349   //   shall be void*.
11350   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy, 
11351                                   SemaRef.Context.VoidPtrTy,
11352                                  diag::err_operator_delete_dependent_param_type,
11353                                  diag::err_operator_delete_param_type))
11354     return true;
11355 
11356   return false;
11357 }
11358 
11359 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11360 /// of this overloaded operator is well-formed. If so, returns false;
11361 /// otherwise, emits appropriate diagnostics and returns true.
11362 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11363   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11364          "Expected an overloaded operator declaration");
11365 
11366   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11367 
11368   // C++ [over.oper]p5:
11369   //   The allocation and deallocation functions, operator new,
11370   //   operator new[], operator delete and operator delete[], are
11371   //   described completely in 3.7.3. The attributes and restrictions
11372   //   found in the rest of this subclause do not apply to them unless
11373   //   explicitly stated in 3.7.3.
11374   if (Op == OO_Delete || Op == OO_Array_Delete)
11375     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11376   
11377   if (Op == OO_New || Op == OO_Array_New)
11378     return CheckOperatorNewDeclaration(*this, FnDecl);
11379 
11380   // C++ [over.oper]p6:
11381   //   An operator function shall either be a non-static member
11382   //   function or be a non-member function and have at least one
11383   //   parameter whose type is a class, a reference to a class, an
11384   //   enumeration, or a reference to an enumeration.
11385   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11386     if (MethodDecl->isStatic())
11387       return Diag(FnDecl->getLocation(),
11388                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11389   } else {
11390     bool ClassOrEnumParam = false;
11391     for (auto Param : FnDecl->params()) {
11392       QualType ParamType = Param->getType().getNonReferenceType();
11393       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11394           ParamType->isEnumeralType()) {
11395         ClassOrEnumParam = true;
11396         break;
11397       }
11398     }
11399 
11400     if (!ClassOrEnumParam)
11401       return Diag(FnDecl->getLocation(),
11402                   diag::err_operator_overload_needs_class_or_enum)
11403         << FnDecl->getDeclName();
11404   }
11405 
11406   // C++ [over.oper]p8:
11407   //   An operator function cannot have default arguments (8.3.6),
11408   //   except where explicitly stated below.
11409   //
11410   // Only the function-call operator allows default arguments
11411   // (C++ [over.call]p1).
11412   if (Op != OO_Call) {
11413     for (auto Param : FnDecl->params()) {
11414       if (Param->hasDefaultArg())
11415         return Diag(Param->getLocation(),
11416                     diag::err_operator_overload_default_arg)
11417           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11418     }
11419   }
11420 
11421   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11422     { false, false, false }
11423 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11424     , { Unary, Binary, MemberOnly }
11425 #include "clang/Basic/OperatorKinds.def"
11426   };
11427 
11428   bool CanBeUnaryOperator = OperatorUses[Op][0];
11429   bool CanBeBinaryOperator = OperatorUses[Op][1];
11430   bool MustBeMemberOperator = OperatorUses[Op][2];
11431 
11432   // C++ [over.oper]p8:
11433   //   [...] Operator functions cannot have more or fewer parameters
11434   //   than the number required for the corresponding operator, as
11435   //   described in the rest of this subclause.
11436   unsigned NumParams = FnDecl->getNumParams()
11437                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11438   if (Op != OO_Call &&
11439       ((NumParams == 1 && !CanBeUnaryOperator) ||
11440        (NumParams == 2 && !CanBeBinaryOperator) ||
11441        (NumParams < 1) || (NumParams > 2))) {
11442     // We have the wrong number of parameters.
11443     unsigned ErrorKind;
11444     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11445       ErrorKind = 2;  // 2 -> unary or binary.
11446     } else if (CanBeUnaryOperator) {
11447       ErrorKind = 0;  // 0 -> unary
11448     } else {
11449       assert(CanBeBinaryOperator &&
11450              "All non-call overloaded operators are unary or binary!");
11451       ErrorKind = 1;  // 1 -> binary
11452     }
11453 
11454     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11455       << FnDecl->getDeclName() << NumParams << ErrorKind;
11456   }
11457 
11458   // Overloaded operators other than operator() cannot be variadic.
11459   if (Op != OO_Call &&
11460       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11461     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11462       << FnDecl->getDeclName();
11463   }
11464 
11465   // Some operators must be non-static member functions.
11466   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11467     return Diag(FnDecl->getLocation(),
11468                 diag::err_operator_overload_must_be_member)
11469       << FnDecl->getDeclName();
11470   }
11471 
11472   // C++ [over.inc]p1:
11473   //   The user-defined function called operator++ implements the
11474   //   prefix and postfix ++ operator. If this function is a member
11475   //   function with no parameters, or a non-member function with one
11476   //   parameter of class or enumeration type, it defines the prefix
11477   //   increment operator ++ for objects of that type. If the function
11478   //   is a member function with one parameter (which shall be of type
11479   //   int) or a non-member function with two parameters (the second
11480   //   of which shall be of type int), it defines the postfix
11481   //   increment operator ++ for objects of that type.
11482   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11483     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11484     QualType ParamType = LastParam->getType();
11485 
11486     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11487         !ParamType->isDependentType())
11488       return Diag(LastParam->getLocation(),
11489                   diag::err_operator_overload_post_incdec_must_be_int)
11490         << LastParam->getType() << (Op == OO_MinusMinus);
11491   }
11492 
11493   return false;
11494 }
11495 
11496 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11497 /// of this literal operator function is well-formed. If so, returns
11498 /// false; otherwise, emits appropriate diagnostics and returns true.
11499 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11500   if (isa<CXXMethodDecl>(FnDecl)) {
11501     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11502       << FnDecl->getDeclName();
11503     return true;
11504   }
11505 
11506   if (FnDecl->isExternC()) {
11507     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11508     return true;
11509   }
11510 
11511   bool Valid = false;
11512 
11513   // This might be the definition of a literal operator template.
11514   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11515   // This might be a specialization of a literal operator template.
11516   if (!TpDecl)
11517     TpDecl = FnDecl->getPrimaryTemplate();
11518 
11519   // template <char...> type operator "" name() and
11520   // template <class T, T...> type operator "" name() are the only valid
11521   // template signatures, and the only valid signatures with no parameters.
11522   if (TpDecl) {
11523     if (FnDecl->param_size() == 0) {
11524       // Must have one or two template parameters
11525       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11526       if (Params->size() == 1) {
11527         NonTypeTemplateParmDecl *PmDecl =
11528           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11529 
11530         // The template parameter must be a char parameter pack.
11531         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11532             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11533           Valid = true;
11534       } else if (Params->size() == 2) {
11535         TemplateTypeParmDecl *PmType =
11536           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11537         NonTypeTemplateParmDecl *PmArgs =
11538           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11539 
11540         // The second template parameter must be a parameter pack with the
11541         // first template parameter as its type.
11542         if (PmType && PmArgs &&
11543             !PmType->isTemplateParameterPack() &&
11544             PmArgs->isTemplateParameterPack()) {
11545           const TemplateTypeParmType *TArgs =
11546             PmArgs->getType()->getAs<TemplateTypeParmType>();
11547           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11548               TArgs->getIndex() == PmType->getIndex()) {
11549             Valid = true;
11550             if (ActiveTemplateInstantiations.empty())
11551               Diag(FnDecl->getLocation(),
11552                    diag::ext_string_literal_operator_template);
11553           }
11554         }
11555       }
11556     }
11557   } else if (FnDecl->param_size()) {
11558     // Check the first parameter
11559     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11560 
11561     QualType T = (*Param)->getType().getUnqualifiedType();
11562 
11563     // unsigned long long int, long double, and any character type are allowed
11564     // as the only parameters.
11565     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11566         Context.hasSameType(T, Context.LongDoubleTy) ||
11567         Context.hasSameType(T, Context.CharTy) ||
11568         Context.hasSameType(T, Context.WideCharTy) ||
11569         Context.hasSameType(T, Context.Char16Ty) ||
11570         Context.hasSameType(T, Context.Char32Ty)) {
11571       if (++Param == FnDecl->param_end())
11572         Valid = true;
11573       goto FinishedParams;
11574     }
11575 
11576     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11577     const PointerType *PT = T->getAs<PointerType>();
11578     if (!PT)
11579       goto FinishedParams;
11580     T = PT->getPointeeType();
11581     if (!T.isConstQualified() || T.isVolatileQualified())
11582       goto FinishedParams;
11583     T = T.getUnqualifiedType();
11584 
11585     // Move on to the second parameter;
11586     ++Param;
11587 
11588     // If there is no second parameter, the first must be a const char *
11589     if (Param == FnDecl->param_end()) {
11590       if (Context.hasSameType(T, Context.CharTy))
11591         Valid = true;
11592       goto FinishedParams;
11593     }
11594 
11595     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11596     // are allowed as the first parameter to a two-parameter function
11597     if (!(Context.hasSameType(T, Context.CharTy) ||
11598           Context.hasSameType(T, Context.WideCharTy) ||
11599           Context.hasSameType(T, Context.Char16Ty) ||
11600           Context.hasSameType(T, Context.Char32Ty)))
11601       goto FinishedParams;
11602 
11603     // The second and final parameter must be an std::size_t
11604     T = (*Param)->getType().getUnqualifiedType();
11605     if (Context.hasSameType(T, Context.getSizeType()) &&
11606         ++Param == FnDecl->param_end())
11607       Valid = true;
11608   }
11609 
11610   // FIXME: This diagnostic is absolutely terrible.
11611 FinishedParams:
11612   if (!Valid) {
11613     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11614       << FnDecl->getDeclName();
11615     return true;
11616   }
11617 
11618   // A parameter-declaration-clause containing a default argument is not
11619   // equivalent to any of the permitted forms.
11620   for (auto Param : FnDecl->params()) {
11621     if (Param->hasDefaultArg()) {
11622       Diag(Param->getDefaultArgRange().getBegin(),
11623            diag::err_literal_operator_default_argument)
11624         << Param->getDefaultArgRange();
11625       break;
11626     }
11627   }
11628 
11629   StringRef LiteralName
11630     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11631   if (LiteralName[0] != '_') {
11632     // C++11 [usrlit.suffix]p1:
11633     //   Literal suffix identifiers that do not start with an underscore
11634     //   are reserved for future standardization.
11635     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11636       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11637   }
11638 
11639   return false;
11640 }
11641 
11642 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11643 /// linkage specification, including the language and (if present)
11644 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11645 /// language string literal. LBraceLoc, if valid, provides the location of
11646 /// the '{' brace. Otherwise, this linkage specification does not
11647 /// have any braces.
11648 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11649                                            Expr *LangStr,
11650                                            SourceLocation LBraceLoc) {
11651   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11652   if (!Lit->isAscii()) {
11653     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11654       << LangStr->getSourceRange();
11655     return nullptr;
11656   }
11657 
11658   StringRef Lang = Lit->getString();
11659   LinkageSpecDecl::LanguageIDs Language;
11660   if (Lang == "C")
11661     Language = LinkageSpecDecl::lang_c;
11662   else if (Lang == "C++")
11663     Language = LinkageSpecDecl::lang_cxx;
11664   else {
11665     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11666       << LangStr->getSourceRange();
11667     return nullptr;
11668   }
11669 
11670   // FIXME: Add all the various semantics of linkage specifications
11671 
11672   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11673                                                LangStr->getExprLoc(), Language,
11674                                                LBraceLoc.isValid());
11675   CurContext->addDecl(D);
11676   PushDeclContext(S, D);
11677   return D;
11678 }
11679 
11680 /// ActOnFinishLinkageSpecification - Complete the definition of
11681 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11682 /// valid, it's the position of the closing '}' brace in a linkage
11683 /// specification that uses braces.
11684 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11685                                             Decl *LinkageSpec,
11686                                             SourceLocation RBraceLoc) {
11687   if (RBraceLoc.isValid()) {
11688     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11689     LSDecl->setRBraceLoc(RBraceLoc);
11690   }
11691   PopDeclContext();
11692   return LinkageSpec;
11693 }
11694 
11695 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11696                                   AttributeList *AttrList,
11697                                   SourceLocation SemiLoc) {
11698   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11699   // Attribute declarations appertain to empty declaration so we handle
11700   // them here.
11701   if (AttrList)
11702     ProcessDeclAttributeList(S, ED, AttrList);
11703 
11704   CurContext->addDecl(ED);
11705   return ED;
11706 }
11707 
11708 /// \brief Perform semantic analysis for the variable declaration that
11709 /// occurs within a C++ catch clause, returning the newly-created
11710 /// variable.
11711 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11712                                          TypeSourceInfo *TInfo,
11713                                          SourceLocation StartLoc,
11714                                          SourceLocation Loc,
11715                                          IdentifierInfo *Name) {
11716   bool Invalid = false;
11717   QualType ExDeclType = TInfo->getType();
11718   
11719   // Arrays and functions decay.
11720   if (ExDeclType->isArrayType())
11721     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11722   else if (ExDeclType->isFunctionType())
11723     ExDeclType = Context.getPointerType(ExDeclType);
11724 
11725   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11726   // The exception-declaration shall not denote a pointer or reference to an
11727   // incomplete type, other than [cv] void*.
11728   // N2844 forbids rvalue references.
11729   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11730     Diag(Loc, diag::err_catch_rvalue_ref);
11731     Invalid = true;
11732   }
11733 
11734   QualType BaseType = ExDeclType;
11735   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11736   unsigned DK = diag::err_catch_incomplete;
11737   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11738     BaseType = Ptr->getPointeeType();
11739     Mode = 1;
11740     DK = diag::err_catch_incomplete_ptr;
11741   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11742     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11743     BaseType = Ref->getPointeeType();
11744     Mode = 2;
11745     DK = diag::err_catch_incomplete_ref;
11746   }
11747   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11748       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11749     Invalid = true;
11750 
11751   if (!Invalid && !ExDeclType->isDependentType() &&
11752       RequireNonAbstractType(Loc, ExDeclType,
11753                              diag::err_abstract_type_in_decl,
11754                              AbstractVariableType))
11755     Invalid = true;
11756 
11757   // Only the non-fragile NeXT runtime currently supports C++ catches
11758   // of ObjC types, and no runtime supports catching ObjC types by value.
11759   if (!Invalid && getLangOpts().ObjC1) {
11760     QualType T = ExDeclType;
11761     if (const ReferenceType *RT = T->getAs<ReferenceType>())
11762       T = RT->getPointeeType();
11763 
11764     if (T->isObjCObjectType()) {
11765       Diag(Loc, diag::err_objc_object_catch);
11766       Invalid = true;
11767     } else if (T->isObjCObjectPointerType()) {
11768       // FIXME: should this be a test for macosx-fragile specifically?
11769       if (getLangOpts().ObjCRuntime.isFragile())
11770         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11771     }
11772   }
11773 
11774   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11775                                     ExDeclType, TInfo, SC_None);
11776   ExDecl->setExceptionVariable(true);
11777   
11778   // In ARC, infer 'retaining' for variables of retainable type.
11779   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11780     Invalid = true;
11781 
11782   if (!Invalid && !ExDeclType->isDependentType()) {
11783     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11784       // Insulate this from anything else we might currently be parsing.
11785       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11786 
11787       // C++ [except.handle]p16:
11788       //   The object declared in an exception-declaration or, if the
11789       //   exception-declaration does not specify a name, a temporary (12.2) is
11790       //   copy-initialized (8.5) from the exception object. [...]
11791       //   The object is destroyed when the handler exits, after the destruction
11792       //   of any automatic objects initialized within the handler.
11793       //
11794       // We just pretend to initialize the object with itself, then make sure
11795       // it can be destroyed later.
11796       QualType initType = ExDeclType;
11797 
11798       InitializedEntity entity =
11799         InitializedEntity::InitializeVariable(ExDecl);
11800       InitializationKind initKind =
11801         InitializationKind::CreateCopy(Loc, SourceLocation());
11802 
11803       Expr *opaqueValue =
11804         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11805       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11806       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11807       if (result.isInvalid())
11808         Invalid = true;
11809       else {
11810         // If the constructor used was non-trivial, set this as the
11811         // "initializer".
11812         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
11813         if (!construct->getConstructor()->isTrivial()) {
11814           Expr *init = MaybeCreateExprWithCleanups(construct);
11815           ExDecl->setInit(init);
11816         }
11817         
11818         // And make sure it's destructable.
11819         FinalizeVarWithDestructor(ExDecl, recordType);
11820       }
11821     }
11822   }
11823   
11824   if (Invalid)
11825     ExDecl->setInvalidDecl();
11826 
11827   return ExDecl;
11828 }
11829 
11830 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11831 /// handler.
11832 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11833   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11834   bool Invalid = D.isInvalidType();
11835 
11836   // Check for unexpanded parameter packs.
11837   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11838                                       UPPC_ExceptionType)) {
11839     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 
11840                                              D.getIdentifierLoc());
11841     Invalid = true;
11842   }
11843 
11844   IdentifierInfo *II = D.getIdentifier();
11845   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11846                                              LookupOrdinaryName,
11847                                              ForRedeclaration)) {
11848     // The scope should be freshly made just for us. There is just no way
11849     // it contains any previous declaration, except for function parameters in
11850     // a function-try-block's catch statement.
11851     assert(!S->isDeclScope(PrevDecl));
11852     if (isDeclInScope(PrevDecl, CurContext, S)) {
11853       Diag(D.getIdentifierLoc(), diag::err_redefinition)
11854         << D.getIdentifier();
11855       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11856       Invalid = true;
11857     } else if (PrevDecl->isTemplateParameter())
11858       // Maybe we will complain about the shadowed template parameter.
11859       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11860   }
11861 
11862   if (D.getCXXScopeSpec().isSet() && !Invalid) {
11863     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11864       << D.getCXXScopeSpec().getRange();
11865     Invalid = true;
11866   }
11867 
11868   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11869                                               D.getLocStart(),
11870                                               D.getIdentifierLoc(),
11871                                               D.getIdentifier());
11872   if (Invalid)
11873     ExDecl->setInvalidDecl();
11874 
11875   // Add the exception declaration into this scope.
11876   if (II)
11877     PushOnScopeChains(ExDecl, S);
11878   else
11879     CurContext->addDecl(ExDecl);
11880 
11881   ProcessDeclAttributes(S, ExDecl, D);
11882   return ExDecl;
11883 }
11884 
11885 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11886                                          Expr *AssertExpr,
11887                                          Expr *AssertMessageExpr,
11888                                          SourceLocation RParenLoc) {
11889   StringLiteral *AssertMessage =
11890       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
11891 
11892   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11893     return nullptr;
11894 
11895   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11896                                       AssertMessage, RParenLoc, false);
11897 }
11898 
11899 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11900                                          Expr *AssertExpr,
11901                                          StringLiteral *AssertMessage,
11902                                          SourceLocation RParenLoc,
11903                                          bool Failed) {
11904   assert(AssertExpr != nullptr && "Expected non-null condition");
11905   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11906       !Failed) {
11907     // In a static_assert-declaration, the constant-expression shall be a
11908     // constant expression that can be contextually converted to bool.
11909     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11910     if (Converted.isInvalid())
11911       Failed = true;
11912 
11913     llvm::APSInt Cond;
11914     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11915           diag::err_static_assert_expression_is_not_constant,
11916           /*AllowFold=*/false).isInvalid())
11917       Failed = true;
11918 
11919     if (!Failed && !Cond) {
11920       SmallString<256> MsgBuffer;
11921       llvm::raw_svector_ostream Msg(MsgBuffer);
11922       if (AssertMessage)
11923         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
11924       Diag(StaticAssertLoc, diag::err_static_assert_failed)
11925         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
11926       Failed = true;
11927     }
11928   }
11929 
11930   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11931                                         AssertExpr, AssertMessage, RParenLoc,
11932                                         Failed);
11933 
11934   CurContext->addDecl(Decl);
11935   return Decl;
11936 }
11937 
11938 /// \brief Perform semantic analysis of the given friend type declaration.
11939 ///
11940 /// \returns A friend declaration that.
11941 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11942                                       SourceLocation FriendLoc,
11943                                       TypeSourceInfo *TSInfo) {
11944   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11945   
11946   QualType T = TSInfo->getType();
11947   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11948   
11949   // C++03 [class.friend]p2:
11950   //   An elaborated-type-specifier shall be used in a friend declaration
11951   //   for a class.*
11952   //
11953   //   * The class-key of the elaborated-type-specifier is required.
11954   if (!ActiveTemplateInstantiations.empty()) {
11955     // Do not complain about the form of friend template types during
11956     // template instantiation; we will already have complained when the
11957     // template was declared.
11958   } else {
11959     if (!T->isElaboratedTypeSpecifier()) {
11960       // If we evaluated the type to a record type, suggest putting
11961       // a tag in front.
11962       if (const RecordType *RT = T->getAs<RecordType>()) {
11963         RecordDecl *RD = RT->getDecl();
11964 
11965         SmallString<16> InsertionText(" ");
11966         InsertionText += RD->getKindName();
11967 
11968         Diag(TypeRange.getBegin(),
11969              getLangOpts().CPlusPlus11 ?
11970                diag::warn_cxx98_compat_unelaborated_friend_type :
11971                diag::ext_unelaborated_friend_type)
11972           << (unsigned) RD->getTagKind()
11973           << T
11974           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11975                                         InsertionText);
11976       } else {
11977         Diag(FriendLoc,
11978              getLangOpts().CPlusPlus11 ?
11979                diag::warn_cxx98_compat_nonclass_type_friend :
11980                diag::ext_nonclass_type_friend)
11981           << T
11982           << TypeRange;
11983       }
11984     } else if (T->getAs<EnumType>()) {
11985       Diag(FriendLoc,
11986            getLangOpts().CPlusPlus11 ?
11987              diag::warn_cxx98_compat_enum_friend :
11988              diag::ext_enum_friend)
11989         << T
11990         << TypeRange;
11991     }
11992   
11993     // C++11 [class.friend]p3:
11994     //   A friend declaration that does not declare a function shall have one
11995     //   of the following forms:
11996     //     friend elaborated-type-specifier ;
11997     //     friend simple-type-specifier ;
11998     //     friend typename-specifier ;
11999     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12000       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12001   }
12002 
12003   //   If the type specifier in a friend declaration designates a (possibly
12004   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12005   //   the friend declaration is ignored.
12006   return FriendDecl::Create(Context, CurContext,
12007                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12008                             FriendLoc);
12009 }
12010 
12011 /// Handle a friend tag declaration where the scope specifier was
12012 /// templated.
12013 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12014                                     unsigned TagSpec, SourceLocation TagLoc,
12015                                     CXXScopeSpec &SS,
12016                                     IdentifierInfo *Name,
12017                                     SourceLocation NameLoc,
12018                                     AttributeList *Attr,
12019                                     MultiTemplateParamsArg TempParamLists) {
12020   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12021 
12022   bool isExplicitSpecialization = false;
12023   bool Invalid = false;
12024 
12025   if (TemplateParameterList *TemplateParams =
12026           MatchTemplateParametersToScopeSpecifier(
12027               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12028               isExplicitSpecialization, Invalid)) {
12029     if (TemplateParams->size() > 0) {
12030       // This is a declaration of a class template.
12031       if (Invalid)
12032         return nullptr;
12033 
12034       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12035                                 NameLoc, Attr, TemplateParams, AS_public,
12036                                 /*ModulePrivateLoc=*/SourceLocation(),
12037                                 FriendLoc, TempParamLists.size() - 1,
12038                                 TempParamLists.data()).get();
12039     } else {
12040       // The "template<>" header is extraneous.
12041       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12042         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12043       isExplicitSpecialization = true;
12044     }
12045   }
12046 
12047   if (Invalid) return nullptr;
12048 
12049   bool isAllExplicitSpecializations = true;
12050   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12051     if (TempParamLists[I]->size()) {
12052       isAllExplicitSpecializations = false;
12053       break;
12054     }
12055   }
12056 
12057   // FIXME: don't ignore attributes.
12058 
12059   // If it's explicit specializations all the way down, just forget
12060   // about the template header and build an appropriate non-templated
12061   // friend.  TODO: for source fidelity, remember the headers.
12062   if (isAllExplicitSpecializations) {
12063     if (SS.isEmpty()) {
12064       bool Owned = false;
12065       bool IsDependent = false;
12066       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12067                       Attr, AS_public,
12068                       /*ModulePrivateLoc=*/SourceLocation(),
12069                       MultiTemplateParamsArg(), Owned, IsDependent,
12070                       /*ScopedEnumKWLoc=*/SourceLocation(),
12071                       /*ScopedEnumUsesClassTag=*/false,
12072                       /*UnderlyingType=*/TypeResult(),
12073                       /*IsTypeSpecifier=*/false);
12074     }
12075 
12076     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12077     ElaboratedTypeKeyword Keyword
12078       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12079     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12080                                    *Name, NameLoc);
12081     if (T.isNull())
12082       return nullptr;
12083 
12084     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12085     if (isa<DependentNameType>(T)) {
12086       DependentNameTypeLoc TL =
12087           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12088       TL.setElaboratedKeywordLoc(TagLoc);
12089       TL.setQualifierLoc(QualifierLoc);
12090       TL.setNameLoc(NameLoc);
12091     } else {
12092       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12093       TL.setElaboratedKeywordLoc(TagLoc);
12094       TL.setQualifierLoc(QualifierLoc);
12095       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12096     }
12097 
12098     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12099                                             TSI, FriendLoc, TempParamLists);
12100     Friend->setAccess(AS_public);
12101     CurContext->addDecl(Friend);
12102     return Friend;
12103   }
12104   
12105   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12106   
12107 
12108 
12109   // Handle the case of a templated-scope friend class.  e.g.
12110   //   template <class T> class A<T>::B;
12111   // FIXME: we don't support these right now.
12112   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12113     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12114   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12115   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12116   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12117   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12118   TL.setElaboratedKeywordLoc(TagLoc);
12119   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12120   TL.setNameLoc(NameLoc);
12121 
12122   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12123                                           TSI, FriendLoc, TempParamLists);
12124   Friend->setAccess(AS_public);
12125   Friend->setUnsupportedFriend(true);
12126   CurContext->addDecl(Friend);
12127   return Friend;
12128 }
12129 
12130 
12131 /// Handle a friend type declaration.  This works in tandem with
12132 /// ActOnTag.
12133 ///
12134 /// Notes on friend class templates:
12135 ///
12136 /// We generally treat friend class declarations as if they were
12137 /// declaring a class.  So, for example, the elaborated type specifier
12138 /// in a friend declaration is required to obey the restrictions of a
12139 /// class-head (i.e. no typedefs in the scope chain), template
12140 /// parameters are required to match up with simple template-ids, &c.
12141 /// However, unlike when declaring a template specialization, it's
12142 /// okay to refer to a template specialization without an empty
12143 /// template parameter declaration, e.g.
12144 ///   friend class A<T>::B<unsigned>;
12145 /// We permit this as a special case; if there are any template
12146 /// parameters present at all, require proper matching, i.e.
12147 ///   template <> template <class T> friend class A<int>::B;
12148 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12149                                 MultiTemplateParamsArg TempParams) {
12150   SourceLocation Loc = DS.getLocStart();
12151 
12152   assert(DS.isFriendSpecified());
12153   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12154 
12155   // Try to convert the decl specifier to a type.  This works for
12156   // friend templates because ActOnTag never produces a ClassTemplateDecl
12157   // for a TUK_Friend.
12158   Declarator TheDeclarator(DS, Declarator::MemberContext);
12159   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12160   QualType T = TSI->getType();
12161   if (TheDeclarator.isInvalidType())
12162     return nullptr;
12163 
12164   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12165     return nullptr;
12166 
12167   // This is definitely an error in C++98.  It's probably meant to
12168   // be forbidden in C++0x, too, but the specification is just
12169   // poorly written.
12170   //
12171   // The problem is with declarations like the following:
12172   //   template <T> friend A<T>::foo;
12173   // where deciding whether a class C is a friend or not now hinges
12174   // on whether there exists an instantiation of A that causes
12175   // 'foo' to equal C.  There are restrictions on class-heads
12176   // (which we declare (by fiat) elaborated friend declarations to
12177   // be) that makes this tractable.
12178   //
12179   // FIXME: handle "template <> friend class A<T>;", which
12180   // is possibly well-formed?  Who even knows?
12181   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12182     Diag(Loc, diag::err_tagless_friend_type_template)
12183       << DS.getSourceRange();
12184     return nullptr;
12185   }
12186   
12187   // C++98 [class.friend]p1: A friend of a class is a function
12188   //   or class that is not a member of the class . . .
12189   // This is fixed in DR77, which just barely didn't make the C++03
12190   // deadline.  It's also a very silly restriction that seriously
12191   // affects inner classes and which nobody else seems to implement;
12192   // thus we never diagnose it, not even in -pedantic.
12193   //
12194   // But note that we could warn about it: it's always useless to
12195   // friend one of your own members (it's not, however, worthless to
12196   // friend a member of an arbitrary specialization of your template).
12197 
12198   Decl *D;
12199   if (unsigned NumTempParamLists = TempParams.size())
12200     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12201                                    NumTempParamLists,
12202                                    TempParams.data(),
12203                                    TSI,
12204                                    DS.getFriendSpecLoc());
12205   else
12206     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12207   
12208   if (!D)
12209     return nullptr;
12210 
12211   D->setAccess(AS_public);
12212   CurContext->addDecl(D);
12213 
12214   return D;
12215 }
12216 
12217 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12218                                         MultiTemplateParamsArg TemplateParams) {
12219   const DeclSpec &DS = D.getDeclSpec();
12220 
12221   assert(DS.isFriendSpecified());
12222   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12223 
12224   SourceLocation Loc = D.getIdentifierLoc();
12225   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12226 
12227   // C++ [class.friend]p1
12228   //   A friend of a class is a function or class....
12229   // Note that this sees through typedefs, which is intended.
12230   // It *doesn't* see through dependent types, which is correct
12231   // according to [temp.arg.type]p3:
12232   //   If a declaration acquires a function type through a
12233   //   type dependent on a template-parameter and this causes
12234   //   a declaration that does not use the syntactic form of a
12235   //   function declarator to have a function type, the program
12236   //   is ill-formed.
12237   if (!TInfo->getType()->isFunctionType()) {
12238     Diag(Loc, diag::err_unexpected_friend);
12239 
12240     // It might be worthwhile to try to recover by creating an
12241     // appropriate declaration.
12242     return nullptr;
12243   }
12244 
12245   // C++ [namespace.memdef]p3
12246   //  - If a friend declaration in a non-local class first declares a
12247   //    class or function, the friend class or function is a member
12248   //    of the innermost enclosing namespace.
12249   //  - The name of the friend is not found by simple name lookup
12250   //    until a matching declaration is provided in that namespace
12251   //    scope (either before or after the class declaration granting
12252   //    friendship).
12253   //  - If a friend function is called, its name may be found by the
12254   //    name lookup that considers functions from namespaces and
12255   //    classes associated with the types of the function arguments.
12256   //  - When looking for a prior declaration of a class or a function
12257   //    declared as a friend, scopes outside the innermost enclosing
12258   //    namespace scope are not considered.
12259 
12260   CXXScopeSpec &SS = D.getCXXScopeSpec();
12261   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12262   DeclarationName Name = NameInfo.getName();
12263   assert(Name);
12264 
12265   // Check for unexpanded parameter packs.
12266   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12267       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12268       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12269     return nullptr;
12270 
12271   // The context we found the declaration in, or in which we should
12272   // create the declaration.
12273   DeclContext *DC;
12274   Scope *DCScope = S;
12275   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12276                         ForRedeclaration);
12277 
12278   // There are five cases here.
12279   //   - There's no scope specifier and we're in a local class. Only look
12280   //     for functions declared in the immediately-enclosing block scope.
12281   // We recover from invalid scope qualifiers as if they just weren't there.
12282   FunctionDecl *FunctionContainingLocalClass = nullptr;
12283   if ((SS.isInvalid() || !SS.isSet()) &&
12284       (FunctionContainingLocalClass =
12285            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12286     // C++11 [class.friend]p11:
12287     //   If a friend declaration appears in a local class and the name
12288     //   specified is an unqualified name, a prior declaration is
12289     //   looked up without considering scopes that are outside the
12290     //   innermost enclosing non-class scope. For a friend function
12291     //   declaration, if there is no prior declaration, the program is
12292     //   ill-formed.
12293 
12294     // Find the innermost enclosing non-class scope. This is the block
12295     // scope containing the local class definition (or for a nested class,
12296     // the outer local class).
12297     DCScope = S->getFnParent();
12298 
12299     // Look up the function name in the scope.
12300     Previous.clear(LookupLocalFriendName);
12301     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12302 
12303     if (!Previous.empty()) {
12304       // All possible previous declarations must have the same context:
12305       // either they were declared at block scope or they are members of
12306       // one of the enclosing local classes.
12307       DC = Previous.getRepresentativeDecl()->getDeclContext();
12308     } else {
12309       // This is ill-formed, but provide the context that we would have
12310       // declared the function in, if we were permitted to, for error recovery.
12311       DC = FunctionContainingLocalClass;
12312     }
12313     adjustContextForLocalExternDecl(DC);
12314 
12315     // C++ [class.friend]p6:
12316     //   A function can be defined in a friend declaration of a class if and
12317     //   only if the class is a non-local class (9.8), the function name is
12318     //   unqualified, and the function has namespace scope.
12319     if (D.isFunctionDefinition()) {
12320       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12321     }
12322 
12323   //   - There's no scope specifier, in which case we just go to the
12324   //     appropriate scope and look for a function or function template
12325   //     there as appropriate.
12326   } else if (SS.isInvalid() || !SS.isSet()) {
12327     // C++11 [namespace.memdef]p3:
12328     //   If the name in a friend declaration is neither qualified nor
12329     //   a template-id and the declaration is a function or an
12330     //   elaborated-type-specifier, the lookup to determine whether
12331     //   the entity has been previously declared shall not consider
12332     //   any scopes outside the innermost enclosing namespace.
12333     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12334 
12335     // Find the appropriate context according to the above.
12336     DC = CurContext;
12337 
12338     // Skip class contexts.  If someone can cite chapter and verse
12339     // for this behavior, that would be nice --- it's what GCC and
12340     // EDG do, and it seems like a reasonable intent, but the spec
12341     // really only says that checks for unqualified existing
12342     // declarations should stop at the nearest enclosing namespace,
12343     // not that they should only consider the nearest enclosing
12344     // namespace.
12345     while (DC->isRecord())
12346       DC = DC->getParent();
12347 
12348     DeclContext *LookupDC = DC;
12349     while (LookupDC->isTransparentContext())
12350       LookupDC = LookupDC->getParent();
12351 
12352     while (true) {
12353       LookupQualifiedName(Previous, LookupDC);
12354 
12355       if (!Previous.empty()) {
12356         DC = LookupDC;
12357         break;
12358       }
12359 
12360       if (isTemplateId) {
12361         if (isa<TranslationUnitDecl>(LookupDC)) break;
12362       } else {
12363         if (LookupDC->isFileContext()) break;
12364       }
12365       LookupDC = LookupDC->getParent();
12366     }
12367 
12368     DCScope = getScopeForDeclContext(S, DC);
12369 
12370   //   - There's a non-dependent scope specifier, in which case we
12371   //     compute it and do a previous lookup there for a function
12372   //     or function template.
12373   } else if (!SS.getScopeRep()->isDependent()) {
12374     DC = computeDeclContext(SS);
12375     if (!DC) return nullptr;
12376 
12377     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12378 
12379     LookupQualifiedName(Previous, DC);
12380 
12381     // Ignore things found implicitly in the wrong scope.
12382     // TODO: better diagnostics for this case.  Suggesting the right
12383     // qualified scope would be nice...
12384     LookupResult::Filter F = Previous.makeFilter();
12385     while (F.hasNext()) {
12386       NamedDecl *D = F.next();
12387       if (!DC->InEnclosingNamespaceSetOf(
12388               D->getDeclContext()->getRedeclContext()))
12389         F.erase();
12390     }
12391     F.done();
12392 
12393     if (Previous.empty()) {
12394       D.setInvalidType();
12395       Diag(Loc, diag::err_qualified_friend_not_found)
12396           << Name << TInfo->getType();
12397       return nullptr;
12398     }
12399 
12400     // C++ [class.friend]p1: A friend of a class is a function or
12401     //   class that is not a member of the class . . .
12402     if (DC->Equals(CurContext))
12403       Diag(DS.getFriendSpecLoc(),
12404            getLangOpts().CPlusPlus11 ?
12405              diag::warn_cxx98_compat_friend_is_member :
12406              diag::err_friend_is_member);
12407     
12408     if (D.isFunctionDefinition()) {
12409       // C++ [class.friend]p6:
12410       //   A function can be defined in a friend declaration of a class if and 
12411       //   only if the class is a non-local class (9.8), the function name is
12412       //   unqualified, and the function has namespace scope.
12413       SemaDiagnosticBuilder DB
12414         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12415       
12416       DB << SS.getScopeRep();
12417       if (DC->isFileContext())
12418         DB << FixItHint::CreateRemoval(SS.getRange());
12419       SS.clear();
12420     }
12421 
12422   //   - There's a scope specifier that does not match any template
12423   //     parameter lists, in which case we use some arbitrary context,
12424   //     create a method or method template, and wait for instantiation.
12425   //   - There's a scope specifier that does match some template
12426   //     parameter lists, which we don't handle right now.
12427   } else {
12428     if (D.isFunctionDefinition()) {
12429       // C++ [class.friend]p6:
12430       //   A function can be defined in a friend declaration of a class if and 
12431       //   only if the class is a non-local class (9.8), the function name is
12432       //   unqualified, and the function has namespace scope.
12433       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12434         << SS.getScopeRep();
12435     }
12436     
12437     DC = CurContext;
12438     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12439   }
12440   
12441   if (!DC->isRecord()) {
12442     // This implies that it has to be an operator or function.
12443     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12444         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12445         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12446       Diag(Loc, diag::err_introducing_special_friend) <<
12447         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12448          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12449       return nullptr;
12450     }
12451   }
12452 
12453   // FIXME: This is an egregious hack to cope with cases where the scope stack
12454   // does not contain the declaration context, i.e., in an out-of-line 
12455   // definition of a class.
12456   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12457   if (!DCScope) {
12458     FakeDCScope.setEntity(DC);
12459     DCScope = &FakeDCScope;
12460   }
12461 
12462   bool AddToScope = true;
12463   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12464                                           TemplateParams, AddToScope);
12465   if (!ND) return nullptr;
12466 
12467   assert(ND->getLexicalDeclContext() == CurContext);
12468 
12469   // If we performed typo correction, we might have added a scope specifier
12470   // and changed the decl context.
12471   DC = ND->getDeclContext();
12472 
12473   // Add the function declaration to the appropriate lookup tables,
12474   // adjusting the redeclarations list as necessary.  We don't
12475   // want to do this yet if the friending class is dependent.
12476   //
12477   // Also update the scope-based lookup if the target context's
12478   // lookup context is in lexical scope.
12479   if (!CurContext->isDependentContext()) {
12480     DC = DC->getRedeclContext();
12481     DC->makeDeclVisibleInContext(ND);
12482     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12483       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12484   }
12485 
12486   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12487                                        D.getIdentifierLoc(), ND,
12488                                        DS.getFriendSpecLoc());
12489   FrD->setAccess(AS_public);
12490   CurContext->addDecl(FrD);
12491 
12492   if (ND->isInvalidDecl()) {
12493     FrD->setInvalidDecl();
12494   } else {
12495     if (DC->isRecord()) CheckFriendAccess(ND);
12496 
12497     FunctionDecl *FD;
12498     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12499       FD = FTD->getTemplatedDecl();
12500     else
12501       FD = cast<FunctionDecl>(ND);
12502 
12503     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12504     // default argument expression, that declaration shall be a definition
12505     // and shall be the only declaration of the function or function
12506     // template in the translation unit.
12507     if (functionDeclHasDefaultArgument(FD)) {
12508       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12509         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12510         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12511       } else if (!D.isFunctionDefinition())
12512         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12513     }
12514 
12515     // Mark templated-scope function declarations as unsupported.
12516     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12517       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12518         << SS.getScopeRep() << SS.getRange()
12519         << cast<CXXRecordDecl>(CurContext);
12520       FrD->setUnsupportedFriend(true);
12521     }
12522   }
12523 
12524   return ND;
12525 }
12526 
12527 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12528   AdjustDeclIfTemplate(Dcl);
12529 
12530   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12531   if (!Fn) {
12532     Diag(DelLoc, diag::err_deleted_non_function);
12533     return;
12534   }
12535 
12536   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12537     // Don't consider the implicit declaration we generate for explicit
12538     // specializations. FIXME: Do not generate these implicit declarations.
12539     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12540          Prev->getPreviousDecl()) &&
12541         !Prev->isDefined()) {
12542       Diag(DelLoc, diag::err_deleted_decl_not_first);
12543       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12544            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12545                               : diag::note_previous_declaration);
12546     }
12547     // If the declaration wasn't the first, we delete the function anyway for
12548     // recovery.
12549     Fn = Fn->getCanonicalDecl();
12550   }
12551 
12552   // dllimport/dllexport cannot be deleted.
12553   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12554     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12555     Fn->setInvalidDecl();
12556   }
12557 
12558   if (Fn->isDeleted())
12559     return;
12560 
12561   // See if we're deleting a function which is already known to override a
12562   // non-deleted virtual function.
12563   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12564     bool IssuedDiagnostic = false;
12565     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12566                                         E = MD->end_overridden_methods();
12567          I != E; ++I) {
12568       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12569         if (!IssuedDiagnostic) {
12570           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12571           IssuedDiagnostic = true;
12572         }
12573         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12574       }
12575     }
12576   }
12577 
12578   // C++11 [basic.start.main]p3:
12579   //   A program that defines main as deleted [...] is ill-formed.
12580   if (Fn->isMain())
12581     Diag(DelLoc, diag::err_deleted_main);
12582 
12583   Fn->setDeletedAsWritten();
12584 }
12585 
12586 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12587   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12588 
12589   if (MD) {
12590     if (MD->getParent()->isDependentType()) {
12591       MD->setDefaulted();
12592       MD->setExplicitlyDefaulted();
12593       return;
12594     }
12595 
12596     CXXSpecialMember Member = getSpecialMember(MD);
12597     if (Member == CXXInvalid) {
12598       if (!MD->isInvalidDecl())
12599         Diag(DefaultLoc, diag::err_default_special_members);
12600       return;
12601     }
12602 
12603     MD->setDefaulted();
12604     MD->setExplicitlyDefaulted();
12605 
12606     // If this definition appears within the record, do the checking when
12607     // the record is complete.
12608     const FunctionDecl *Primary = MD;
12609     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12610       // Find the uninstantiated declaration that actually had the '= default'
12611       // on it.
12612       Pattern->isDefined(Primary);
12613 
12614     // If the method was defaulted on its first declaration, we will have
12615     // already performed the checking in CheckCompletedCXXClass. Such a
12616     // declaration doesn't trigger an implicit definition.
12617     if (Primary == Primary->getCanonicalDecl())
12618       return;
12619 
12620     CheckExplicitlyDefaultedSpecialMember(MD);
12621 
12622     if (MD->isInvalidDecl())
12623       return;
12624 
12625     switch (Member) {
12626     case CXXDefaultConstructor:
12627       DefineImplicitDefaultConstructor(DefaultLoc,
12628                                        cast<CXXConstructorDecl>(MD));
12629       break;
12630     case CXXCopyConstructor:
12631       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12632       break;
12633     case CXXCopyAssignment:
12634       DefineImplicitCopyAssignment(DefaultLoc, MD);
12635       break;
12636     case CXXDestructor:
12637       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12638       break;
12639     case CXXMoveConstructor:
12640       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12641       break;
12642     case CXXMoveAssignment:
12643       DefineImplicitMoveAssignment(DefaultLoc, MD);
12644       break;
12645     case CXXInvalid:
12646       llvm_unreachable("Invalid special member.");
12647     }
12648   } else {
12649     Diag(DefaultLoc, diag::err_default_special_members);
12650   }
12651 }
12652 
12653 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12654   for (Stmt::child_range CI = S->children(); CI; ++CI) {
12655     Stmt *SubStmt = *CI;
12656     if (!SubStmt)
12657       continue;
12658     if (isa<ReturnStmt>(SubStmt))
12659       Self.Diag(SubStmt->getLocStart(),
12660            diag::err_return_in_constructor_handler);
12661     if (!isa<Expr>(SubStmt))
12662       SearchForReturnInStmt(Self, SubStmt);
12663   }
12664 }
12665 
12666 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12667   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12668     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12669     SearchForReturnInStmt(*this, Handler);
12670   }
12671 }
12672 
12673 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12674                                              const CXXMethodDecl *Old) {
12675   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12676   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12677 
12678   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12679 
12680   // If the calling conventions match, everything is fine
12681   if (NewCC == OldCC)
12682     return false;
12683 
12684   // If the calling conventions mismatch because the new function is static,
12685   // suppress the calling convention mismatch error; the error about static
12686   // function override (err_static_overrides_virtual from
12687   // Sema::CheckFunctionDeclaration) is more clear.
12688   if (New->getStorageClass() == SC_Static)
12689     return false;
12690 
12691   Diag(New->getLocation(),
12692        diag::err_conflicting_overriding_cc_attributes)
12693     << New->getDeclName() << New->getType() << Old->getType();
12694   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12695   return true;
12696 }
12697 
12698 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12699                                              const CXXMethodDecl *Old) {
12700   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12701   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12702 
12703   if (Context.hasSameType(NewTy, OldTy) ||
12704       NewTy->isDependentType() || OldTy->isDependentType())
12705     return false;
12706 
12707   // Check if the return types are covariant
12708   QualType NewClassTy, OldClassTy;
12709 
12710   /// Both types must be pointers or references to classes.
12711   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12712     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12713       NewClassTy = NewPT->getPointeeType();
12714       OldClassTy = OldPT->getPointeeType();
12715     }
12716   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12717     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12718       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12719         NewClassTy = NewRT->getPointeeType();
12720         OldClassTy = OldRT->getPointeeType();
12721       }
12722     }
12723   }
12724 
12725   // The return types aren't either both pointers or references to a class type.
12726   if (NewClassTy.isNull()) {
12727     Diag(New->getLocation(),
12728          diag::err_different_return_type_for_overriding_virtual_function)
12729         << New->getDeclName() << NewTy << OldTy
12730         << New->getReturnTypeSourceRange();
12731     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12732         << Old->getReturnTypeSourceRange();
12733 
12734     return true;
12735   }
12736 
12737   // C++ [class.virtual]p6:
12738   //   If the return type of D::f differs from the return type of B::f, the 
12739   //   class type in the return type of D::f shall be complete at the point of
12740   //   declaration of D::f or shall be the class type D.
12741   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12742     if (!RT->isBeingDefined() &&
12743         RequireCompleteType(New->getLocation(), NewClassTy, 
12744                             diag::err_covariant_return_incomplete,
12745                             New->getDeclName()))
12746     return true;
12747   }
12748 
12749   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12750     // Check if the new class derives from the old class.
12751     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12752       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12753           << New->getDeclName() << NewTy << OldTy
12754           << New->getReturnTypeSourceRange();
12755       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12756           << Old->getReturnTypeSourceRange();
12757       return true;
12758     }
12759 
12760     // Check if we the conversion from derived to base is valid.
12761     if (CheckDerivedToBaseConversion(
12762             NewClassTy, OldClassTy,
12763             diag::err_covariant_return_inaccessible_base,
12764             diag::err_covariant_return_ambiguous_derived_to_base_conv,
12765             New->getLocation(), New->getReturnTypeSourceRange(),
12766             New->getDeclName(), nullptr)) {
12767       // FIXME: this note won't trigger for delayed access control
12768       // diagnostics, and it's impossible to get an undelayed error
12769       // here from access control during the original parse because
12770       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12771       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12772           << Old->getReturnTypeSourceRange();
12773       return true;
12774     }
12775   }
12776 
12777   // The qualifiers of the return types must be the same.
12778   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12779     Diag(New->getLocation(),
12780          diag::err_covariant_return_type_different_qualifications)
12781         << New->getDeclName() << NewTy << OldTy
12782         << New->getReturnTypeSourceRange();
12783     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12784         << Old->getReturnTypeSourceRange();
12785     return true;
12786   };
12787 
12788 
12789   // The new class type must have the same or less qualifiers as the old type.
12790   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12791     Diag(New->getLocation(),
12792          diag::err_covariant_return_type_class_type_more_qualified)
12793         << New->getDeclName() << NewTy << OldTy
12794         << New->getReturnTypeSourceRange();
12795     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12796         << Old->getReturnTypeSourceRange();
12797     return true;
12798   };
12799 
12800   return false;
12801 }
12802 
12803 /// \brief Mark the given method pure.
12804 ///
12805 /// \param Method the method to be marked pure.
12806 ///
12807 /// \param InitRange the source range that covers the "0" initializer.
12808 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12809   SourceLocation EndLoc = InitRange.getEnd();
12810   if (EndLoc.isValid())
12811     Method->setRangeEnd(EndLoc);
12812 
12813   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12814     Method->setPure();
12815     return false;
12816   }
12817 
12818   if (!Method->isInvalidDecl())
12819     Diag(Method->getLocation(), diag::err_non_virtual_pure)
12820       << Method->getDeclName() << InitRange;
12821   return true;
12822 }
12823 
12824 /// \brief Determine whether the given declaration is a static data member.
12825 static bool isStaticDataMember(const Decl *D) {
12826   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12827     return Var->isStaticDataMember();
12828 
12829   return false;
12830 }
12831 
12832 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12833 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
12834 /// is a fresh scope pushed for just this purpose.
12835 ///
12836 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12837 /// static data member of class X, names should be looked up in the scope of
12838 /// class X.
12839 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12840   // If there is no declaration, there was an error parsing it.
12841   if (!D || D->isInvalidDecl())
12842     return;
12843 
12844   // We will always have a nested name specifier here, but this declaration
12845   // might not be out of line if the specifier names the current namespace:
12846   //   extern int n;
12847   //   int ::n = 0;
12848   if (D->isOutOfLine())
12849     EnterDeclaratorContext(S, D->getDeclContext());
12850 
12851   // If we are parsing the initializer for a static data member, push a
12852   // new expression evaluation context that is associated with this static
12853   // data member.
12854   if (isStaticDataMember(D))
12855     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12856 }
12857 
12858 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12859 /// initializer for the out-of-line declaration 'D'.
12860 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12861   // If there is no declaration, there was an error parsing it.
12862   if (!D || D->isInvalidDecl())
12863     return;
12864 
12865   if (isStaticDataMember(D))
12866     PopExpressionEvaluationContext();
12867 
12868   if (D->isOutOfLine())
12869     ExitDeclaratorContext(S);
12870 }
12871 
12872 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12873 /// C++ if/switch/while/for statement.
12874 /// e.g: "if (int x = f()) {...}"
12875 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12876   // C++ 6.4p2:
12877   // The declarator shall not specify a function or an array.
12878   // The type-specifier-seq shall not contain typedef and shall not declare a
12879   // new class or enumeration.
12880   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12881          "Parser allowed 'typedef' as storage class of condition decl.");
12882 
12883   Decl *Dcl = ActOnDeclarator(S, D);
12884   if (!Dcl)
12885     return true;
12886 
12887   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12888     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12889       << D.getSourceRange();
12890     return true;
12891   }
12892 
12893   return Dcl;
12894 }
12895 
12896 void Sema::LoadExternalVTableUses() {
12897   if (!ExternalSource)
12898     return;
12899   
12900   SmallVector<ExternalVTableUse, 4> VTables;
12901   ExternalSource->ReadUsedVTables(VTables);
12902   SmallVector<VTableUse, 4> NewUses;
12903   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12904     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12905       = VTablesUsed.find(VTables[I].Record);
12906     // Even if a definition wasn't required before, it may be required now.
12907     if (Pos != VTablesUsed.end()) {
12908       if (!Pos->second && VTables[I].DefinitionRequired)
12909         Pos->second = true;
12910       continue;
12911     }
12912     
12913     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12914     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12915   }
12916   
12917   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12918 }
12919 
12920 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12921                           bool DefinitionRequired) {
12922   // Ignore any vtable uses in unevaluated operands or for classes that do
12923   // not have a vtable.
12924   if (!Class->isDynamicClass() || Class->isDependentContext() ||
12925       CurContext->isDependentContext() || isUnevaluatedContext())
12926     return;
12927 
12928   // Try to insert this class into the map.
12929   LoadExternalVTableUses();
12930   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12931   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12932     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12933   if (!Pos.second) {
12934     // If we already had an entry, check to see if we are promoting this vtable
12935     // to required a definition. If so, we need to reappend to the VTableUses
12936     // list, since we may have already processed the first entry.
12937     if (DefinitionRequired && !Pos.first->second) {
12938       Pos.first->second = true;
12939     } else {
12940       // Otherwise, we can early exit.
12941       return;
12942     }
12943   } else {
12944     // The Microsoft ABI requires that we perform the destructor body
12945     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12946     // the deleting destructor is emitted with the vtable, not with the
12947     // destructor definition as in the Itanium ABI.
12948     // If it has a definition, we do the check at that point instead.
12949     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12950         Class->hasUserDeclaredDestructor() &&
12951         !Class->getDestructor()->isDefined() &&
12952         !Class->getDestructor()->isDeleted()) {
12953       CXXDestructorDecl *DD = Class->getDestructor();
12954       ContextRAII SavedContext(*this, DD);
12955       CheckDestructor(DD);
12956     }
12957   }
12958 
12959   // Local classes need to have their virtual members marked
12960   // immediately. For all other classes, we mark their virtual members
12961   // at the end of the translation unit.
12962   if (Class->isLocalClass())
12963     MarkVirtualMembersReferenced(Loc, Class);
12964   else
12965     VTableUses.push_back(std::make_pair(Class, Loc));
12966 }
12967 
12968 bool Sema::DefineUsedVTables() {
12969   LoadExternalVTableUses();
12970   if (VTableUses.empty())
12971     return false;
12972 
12973   // Note: The VTableUses vector could grow as a result of marking
12974   // the members of a class as "used", so we check the size each
12975   // time through the loop and prefer indices (which are stable) to
12976   // iterators (which are not).
12977   bool DefinedAnything = false;
12978   for (unsigned I = 0; I != VTableUses.size(); ++I) {
12979     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12980     if (!Class)
12981       continue;
12982 
12983     SourceLocation Loc = VTableUses[I].second;
12984 
12985     bool DefineVTable = true;
12986 
12987     // If this class has a key function, but that key function is
12988     // defined in another translation unit, we don't need to emit the
12989     // vtable even though we're using it.
12990     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12991     if (KeyFunction && !KeyFunction->hasBody()) {
12992       // The key function is in another translation unit.
12993       DefineVTable = false;
12994       TemplateSpecializationKind TSK =
12995           KeyFunction->getTemplateSpecializationKind();
12996       assert(TSK != TSK_ExplicitInstantiationDefinition &&
12997              TSK != TSK_ImplicitInstantiation &&
12998              "Instantiations don't have key functions");
12999       (void)TSK;
13000     } else if (!KeyFunction) {
13001       // If we have a class with no key function that is the subject
13002       // of an explicit instantiation declaration, suppress the
13003       // vtable; it will live with the explicit instantiation
13004       // definition.
13005       bool IsExplicitInstantiationDeclaration
13006         = Class->getTemplateSpecializationKind()
13007                                       == TSK_ExplicitInstantiationDeclaration;
13008       for (auto R : Class->redecls()) {
13009         TemplateSpecializationKind TSK
13010           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13011         if (TSK == TSK_ExplicitInstantiationDeclaration)
13012           IsExplicitInstantiationDeclaration = true;
13013         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13014           IsExplicitInstantiationDeclaration = false;
13015           break;
13016         }
13017       }
13018 
13019       if (IsExplicitInstantiationDeclaration)
13020         DefineVTable = false;
13021     }
13022 
13023     // The exception specifications for all virtual members may be needed even
13024     // if we are not providing an authoritative form of the vtable in this TU.
13025     // We may choose to emit it available_externally anyway.
13026     if (!DefineVTable) {
13027       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13028       continue;
13029     }
13030 
13031     // Mark all of the virtual members of this class as referenced, so
13032     // that we can build a vtable. Then, tell the AST consumer that a
13033     // vtable for this class is required.
13034     DefinedAnything = true;
13035     MarkVirtualMembersReferenced(Loc, Class);
13036     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13037     Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
13038 
13039     // Optionally warn if we're emitting a weak vtable.
13040     if (Class->isExternallyVisible() &&
13041         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13042       const FunctionDecl *KeyFunctionDef = nullptr;
13043       if (!KeyFunction || 
13044           (KeyFunction->hasBody(KeyFunctionDef) && 
13045            KeyFunctionDef->isInlined()))
13046         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13047              TSK_ExplicitInstantiationDefinition 
13048              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable) 
13049           << Class;
13050     }
13051   }
13052   VTableUses.clear();
13053 
13054   return DefinedAnything;
13055 }
13056 
13057 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13058                                                  const CXXRecordDecl *RD) {
13059   for (const auto *I : RD->methods())
13060     if (I->isVirtual() && !I->isPure())
13061       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13062 }
13063 
13064 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13065                                         const CXXRecordDecl *RD) {
13066   // Mark all functions which will appear in RD's vtable as used.
13067   CXXFinalOverriderMap FinalOverriders;
13068   RD->getFinalOverriders(FinalOverriders);
13069   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13070                                             E = FinalOverriders.end();
13071        I != E; ++I) {
13072     for (OverridingMethods::const_iterator OI = I->second.begin(),
13073                                            OE = I->second.end();
13074          OI != OE; ++OI) {
13075       assert(OI->second.size() > 0 && "no final overrider");
13076       CXXMethodDecl *Overrider = OI->second.front().Method;
13077 
13078       // C++ [basic.def.odr]p2:
13079       //   [...] A virtual member function is used if it is not pure. [...]
13080       if (!Overrider->isPure())
13081         MarkFunctionReferenced(Loc, Overrider);
13082     }
13083   }
13084 
13085   // Only classes that have virtual bases need a VTT.
13086   if (RD->getNumVBases() == 0)
13087     return;
13088 
13089   for (const auto &I : RD->bases()) {
13090     const CXXRecordDecl *Base =
13091         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13092     if (Base->getNumVBases() == 0)
13093       continue;
13094     MarkVirtualMembersReferenced(Loc, Base);
13095   }
13096 }
13097 
13098 /// SetIvarInitializers - This routine builds initialization ASTs for the
13099 /// Objective-C implementation whose ivars need be initialized.
13100 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13101   if (!getLangOpts().CPlusPlus)
13102     return;
13103   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13104     SmallVector<ObjCIvarDecl*, 8> ivars;
13105     CollectIvarsToConstructOrDestruct(OID, ivars);
13106     if (ivars.empty())
13107       return;
13108     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13109     for (unsigned i = 0; i < ivars.size(); i++) {
13110       FieldDecl *Field = ivars[i];
13111       if (Field->isInvalidDecl())
13112         continue;
13113       
13114       CXXCtorInitializer *Member;
13115       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13116       InitializationKind InitKind = 
13117         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13118 
13119       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13120       ExprResult MemberInit =
13121         InitSeq.Perform(*this, InitEntity, InitKind, None);
13122       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13123       // Note, MemberInit could actually come back empty if no initialization 
13124       // is required (e.g., because it would call a trivial default constructor)
13125       if (!MemberInit.get() || MemberInit.isInvalid())
13126         continue;
13127 
13128       Member =
13129         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13130                                          SourceLocation(),
13131                                          MemberInit.getAs<Expr>(),
13132                                          SourceLocation());
13133       AllToInit.push_back(Member);
13134       
13135       // Be sure that the destructor is accessible and is marked as referenced.
13136       if (const RecordType *RecordTy =
13137               Context.getBaseElementType(Field->getType())
13138                   ->getAs<RecordType>()) {
13139         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13140         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13141           MarkFunctionReferenced(Field->getLocation(), Destructor);
13142           CheckDestructorAccess(Field->getLocation(), Destructor,
13143                             PDiag(diag::err_access_dtor_ivar)
13144                               << Context.getBaseElementType(Field->getType()));
13145         }
13146       }      
13147     }
13148     ObjCImplementation->setIvarInitializers(Context, 
13149                                             AllToInit.data(), AllToInit.size());
13150   }
13151 }
13152 
13153 static
13154 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13155                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13156                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13157                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13158                            Sema &S) {
13159   if (Ctor->isInvalidDecl())
13160     return;
13161 
13162   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13163 
13164   // Target may not be determinable yet, for instance if this is a dependent
13165   // call in an uninstantiated template.
13166   if (Target) {
13167     const FunctionDecl *FNTarget = nullptr;
13168     (void)Target->hasBody(FNTarget);
13169     Target = const_cast<CXXConstructorDecl*>(
13170       cast_or_null<CXXConstructorDecl>(FNTarget));
13171   }
13172 
13173   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13174                      // Avoid dereferencing a null pointer here.
13175                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13176 
13177   if (!Current.insert(Canonical))
13178     return;
13179 
13180   // We know that beyond here, we aren't chaining into a cycle.
13181   if (!Target || !Target->isDelegatingConstructor() ||
13182       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13183     Valid.insert(Current.begin(), Current.end());
13184     Current.clear();
13185   // We've hit a cycle.
13186   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13187              Current.count(TCanonical)) {
13188     // If we haven't diagnosed this cycle yet, do so now.
13189     if (!Invalid.count(TCanonical)) {
13190       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13191              diag::warn_delegating_ctor_cycle)
13192         << Ctor;
13193 
13194       // Don't add a note for a function delegating directly to itself.
13195       if (TCanonical != Canonical)
13196         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13197 
13198       CXXConstructorDecl *C = Target;
13199       while (C->getCanonicalDecl() != Canonical) {
13200         const FunctionDecl *FNTarget = nullptr;
13201         (void)C->getTargetConstructor()->hasBody(FNTarget);
13202         assert(FNTarget && "Ctor cycle through bodiless function");
13203 
13204         C = const_cast<CXXConstructorDecl*>(
13205           cast<CXXConstructorDecl>(FNTarget));
13206         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13207       }
13208     }
13209 
13210     Invalid.insert(Current.begin(), Current.end());
13211     Current.clear();
13212   } else {
13213     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13214   }
13215 }
13216    
13217 
13218 void Sema::CheckDelegatingCtorCycles() {
13219   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13220 
13221   for (DelegatingCtorDeclsType::iterator
13222          I = DelegatingCtorDecls.begin(ExternalSource),
13223          E = DelegatingCtorDecls.end();
13224        I != E; ++I)
13225     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13226 
13227   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13228                                                          CE = Invalid.end();
13229        CI != CE; ++CI)
13230     (*CI)->setInvalidDecl();
13231 }
13232 
13233 namespace {
13234   /// \brief AST visitor that finds references to the 'this' expression.
13235   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13236     Sema &S;
13237     
13238   public:
13239     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13240     
13241     bool VisitCXXThisExpr(CXXThisExpr *E) {
13242       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13243         << E->isImplicit();
13244       return false;
13245     }
13246   };
13247 }
13248 
13249 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13250   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13251   if (!TSInfo)
13252     return false;
13253   
13254   TypeLoc TL = TSInfo->getTypeLoc();
13255   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13256   if (!ProtoTL)
13257     return false;
13258   
13259   // C++11 [expr.prim.general]p3:
13260   //   [The expression this] shall not appear before the optional 
13261   //   cv-qualifier-seq and it shall not appear within the declaration of a 
13262   //   static member function (although its type and value category are defined
13263   //   within a static member function as they are within a non-static member
13264   //   function). [ Note: this is because declaration matching does not occur
13265   //  until the complete declarator is known. - end note ]
13266   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13267   FindCXXThisExpr Finder(*this);
13268   
13269   // If the return type came after the cv-qualifier-seq, check it now.
13270   if (Proto->hasTrailingReturn() &&
13271       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13272     return true;
13273 
13274   // Check the exception specification.
13275   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13276     return true;
13277   
13278   return checkThisInStaticMemberFunctionAttributes(Method);
13279 }
13280 
13281 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13282   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13283   if (!TSInfo)
13284     return false;
13285   
13286   TypeLoc TL = TSInfo->getTypeLoc();
13287   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13288   if (!ProtoTL)
13289     return false;
13290   
13291   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13292   FindCXXThisExpr Finder(*this);
13293 
13294   switch (Proto->getExceptionSpecType()) {
13295   case EST_Unparsed:
13296   case EST_Uninstantiated:
13297   case EST_Unevaluated:
13298   case EST_BasicNoexcept:
13299   case EST_DynamicNone:
13300   case EST_MSAny:
13301   case EST_None:
13302     break;
13303     
13304   case EST_ComputedNoexcept:
13305     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13306       return true;
13307     
13308   case EST_Dynamic:
13309     for (const auto &E : Proto->exceptions()) {
13310       if (!Finder.TraverseType(E))
13311         return true;
13312     }
13313     break;
13314   }
13315 
13316   return false;
13317 }
13318 
13319 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13320   FindCXXThisExpr Finder(*this);
13321 
13322   // Check attributes.
13323   for (const auto *A : Method->attrs()) {
13324     // FIXME: This should be emitted by tblgen.
13325     Expr *Arg = nullptr;
13326     ArrayRef<Expr *> Args;
13327     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13328       Arg = G->getArg();
13329     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13330       Arg = G->getArg();
13331     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13332       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13333     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13334       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13335     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13336       Arg = ETLF->getSuccessValue();
13337       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13338     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13339       Arg = STLF->getSuccessValue();
13340       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13341     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13342       Arg = LR->getArg();
13343     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13344       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13345     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13346       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13347     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13348       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13349     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13350       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13351     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13352       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13353 
13354     if (Arg && !Finder.TraverseStmt(Arg))
13355       return true;
13356     
13357     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13358       if (!Finder.TraverseStmt(Args[I]))
13359         return true;
13360     }
13361   }
13362   
13363   return false;
13364 }
13365 
13366 void Sema::checkExceptionSpecification(
13367     bool IsTopLevel, ExceptionSpecificationType EST,
13368     ArrayRef<ParsedType> DynamicExceptions,
13369     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13370     SmallVectorImpl<QualType> &Exceptions,
13371     FunctionProtoType::ExceptionSpecInfo &ESI) {
13372   Exceptions.clear();
13373   ESI.Type = EST;
13374   if (EST == EST_Dynamic) {
13375     Exceptions.reserve(DynamicExceptions.size());
13376     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13377       // FIXME: Preserve type source info.
13378       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13379 
13380       if (IsTopLevel) {
13381         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13382         collectUnexpandedParameterPacks(ET, Unexpanded);
13383         if (!Unexpanded.empty()) {
13384           DiagnoseUnexpandedParameterPacks(
13385               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13386               Unexpanded);
13387           continue;
13388         }
13389       }
13390 
13391       // Check that the type is valid for an exception spec, and
13392       // drop it if not.
13393       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13394         Exceptions.push_back(ET);
13395     }
13396     ESI.Exceptions = Exceptions;
13397     return;
13398   }
13399 
13400   if (EST == EST_ComputedNoexcept) {
13401     // If an error occurred, there's no expression here.
13402     if (NoexceptExpr) {
13403       assert((NoexceptExpr->isTypeDependent() ||
13404               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13405               Context.BoolTy) &&
13406              "Parser should have made sure that the expression is boolean");
13407       if (IsTopLevel && NoexceptExpr &&
13408           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13409         ESI.Type = EST_BasicNoexcept;
13410         return;
13411       }
13412 
13413       if (!NoexceptExpr->isValueDependent())
13414         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13415                          diag::err_noexcept_needs_constant_expression,
13416                          /*AllowFold*/ false).get();
13417       ESI.NoexceptExpr = NoexceptExpr;
13418     }
13419     return;
13420   }
13421 }
13422 
13423 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13424              ExceptionSpecificationType EST,
13425              SourceRange SpecificationRange,
13426              ArrayRef<ParsedType> DynamicExceptions,
13427              ArrayRef<SourceRange> DynamicExceptionRanges,
13428              Expr *NoexceptExpr) {
13429   if (!MethodD)
13430     return;
13431 
13432   // Dig out the method we're referring to.
13433   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13434     MethodD = FunTmpl->getTemplatedDecl();
13435 
13436   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13437   if (!Method)
13438     return;
13439 
13440   // Check the exception specification.
13441   llvm::SmallVector<QualType, 4> Exceptions;
13442   FunctionProtoType::ExceptionSpecInfo ESI;
13443   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13444                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13445                               ESI);
13446 
13447   // Update the exception specification on the function type.
13448   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13449 
13450   if (Method->isStatic())
13451     checkThisInStaticMemberFunctionExceptionSpec(Method);
13452 
13453   if (Method->isVirtual()) {
13454     // Check overrides, which we previously had to delay.
13455     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13456                                      OEnd = Method->end_overridden_methods();
13457          O != OEnd; ++O)
13458       CheckOverridingFunctionExceptionSpec(Method, *O);
13459   }
13460 }
13461 
13462 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13463 ///
13464 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13465                                        SourceLocation DeclStart,
13466                                        Declarator &D, Expr *BitWidth,
13467                                        InClassInitStyle InitStyle,
13468                                        AccessSpecifier AS,
13469                                        AttributeList *MSPropertyAttr) {
13470   IdentifierInfo *II = D.getIdentifier();
13471   if (!II) {
13472     Diag(DeclStart, diag::err_anonymous_property);
13473     return nullptr;
13474   }
13475   SourceLocation Loc = D.getIdentifierLoc();
13476 
13477   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13478   QualType T = TInfo->getType();
13479   if (getLangOpts().CPlusPlus) {
13480     CheckExtraCXXDefaultArguments(D);
13481 
13482     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13483                                         UPPC_DataMemberType)) {
13484       D.setInvalidType();
13485       T = Context.IntTy;
13486       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13487     }
13488   }
13489 
13490   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13491 
13492   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13493     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13494          diag::err_invalid_thread)
13495       << DeclSpec::getSpecifierName(TSCS);
13496 
13497   // Check to see if this name was declared as a member previously
13498   NamedDecl *PrevDecl = nullptr;
13499   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13500   LookupName(Previous, S);
13501   switch (Previous.getResultKind()) {
13502   case LookupResult::Found:
13503   case LookupResult::FoundUnresolvedValue:
13504     PrevDecl = Previous.getAsSingle<NamedDecl>();
13505     break;
13506 
13507   case LookupResult::FoundOverloaded:
13508     PrevDecl = Previous.getRepresentativeDecl();
13509     break;
13510 
13511   case LookupResult::NotFound:
13512   case LookupResult::NotFoundInCurrentInstantiation:
13513   case LookupResult::Ambiguous:
13514     break;
13515   }
13516 
13517   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13518     // Maybe we will complain about the shadowed template parameter.
13519     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13520     // Just pretend that we didn't see the previous declaration.
13521     PrevDecl = nullptr;
13522   }
13523 
13524   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13525     PrevDecl = nullptr;
13526 
13527   SourceLocation TSSL = D.getLocStart();
13528   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13529   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13530       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13531   ProcessDeclAttributes(TUScope, NewPD, D);
13532   NewPD->setAccess(AS);
13533 
13534   if (NewPD->isInvalidDecl())
13535     Record->setInvalidDecl();
13536 
13537   if (D.getDeclSpec().isModulePrivateSpecified())
13538     NewPD->setModulePrivate();
13539 
13540   if (NewPD->isInvalidDecl() && PrevDecl) {
13541     // Don't introduce NewFD into scope; there's already something
13542     // with the same name in the same scope.
13543   } else if (II) {
13544     PushOnScopeChains(NewPD, S);
13545   } else
13546     Record->addDecl(NewPD);
13547 
13548   return NewPD;
13549 }