1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include <map>
43 #include <set>
44 
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 // CheckDefaultArgumentVisitor
49 //===----------------------------------------------------------------------===//
50 
51 namespace {
52   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53   /// the default argument of a parameter to determine whether it
54   /// contains any ill-formed subexpressions. For example, this will
55   /// diagnose the use of local variables or parameters within the
56   /// default argument expression.
57   class CheckDefaultArgumentVisitor
58     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59     Expr *DefaultArg;
60     Sema *S;
61 
62   public:
63     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64       : DefaultArg(defarg), S(s) {}
65 
66     bool VisitExpr(Expr *Node);
67     bool VisitDeclRefExpr(DeclRefExpr *DRE);
68     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69     bool VisitLambdaExpr(LambdaExpr *Lambda);
70     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71   };
72 
73   /// VisitExpr - Visit all of the children of this expression.
74   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75     bool IsInvalid = false;
76     for (Stmt *SubStmt : Node->children())
77       IsInvalid |= Visit(SubStmt);
78     return IsInvalid;
79   }
80 
81   /// VisitDeclRefExpr - Visit a reference to a declaration, to
82   /// determine whether this declaration can be used in the default
83   /// argument expression.
84   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85     NamedDecl *Decl = DRE->getDecl();
86     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87       // C++ [dcl.fct.default]p9
88       //   Default arguments are evaluated each time the function is
89       //   called. The order of evaluation of function arguments is
90       //   unspecified. Consequently, parameters of a function shall not
91       //   be used in default argument expressions, even if they are not
92       //   evaluated. Parameters of a function declared before a default
93       //   argument expression are in scope and can hide namespace and
94       //   class member names.
95       return S->Diag(DRE->getLocStart(),
96                      diag::err_param_default_argument_references_param)
97          << Param->getDeclName() << DefaultArg->getSourceRange();
98     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99       // C++ [dcl.fct.default]p7
100       //   Local variables shall not be used in default argument
101       //   expressions.
102       if (VDecl->isLocalVarDecl())
103         return S->Diag(DRE->getLocStart(),
104                        diag::err_param_default_argument_references_local)
105           << VDecl->getDeclName() << DefaultArg->getSourceRange();
106     }
107 
108     return false;
109   }
110 
111   /// VisitCXXThisExpr - Visit a C++ "this" expression.
112   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113     // C++ [dcl.fct.default]p8:
114     //   The keyword this shall not be used in a default argument of a
115     //   member function.
116     return S->Diag(ThisE->getLocStart(),
117                    diag::err_param_default_argument_references_this)
118                << ThisE->getSourceRange();
119   }
120 
121   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122     bool Invalid = false;
123     for (PseudoObjectExpr::semantics_iterator
124            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125       Expr *E = *i;
126 
127       // Look through bindings.
128       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129         E = OVE->getSourceExpr();
130         assert(E && "pseudo-object binding without source expression?");
131       }
132 
133       Invalid |= Visit(E);
134     }
135     return Invalid;
136   }
137 
138   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139     // C++11 [expr.lambda.prim]p13:
140     //   A lambda-expression appearing in a default argument shall not
141     //   implicitly or explicitly capture any entity.
142     if (Lambda->capture_begin() == Lambda->capture_end())
143       return false;
144 
145     return S->Diag(Lambda->getLocStart(),
146                    diag::err_lambda_capture_default_arg);
147   }
148 }
149 
150 void
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                  const CXXMethodDecl *Method) {
153   // If we have an MSAny spec already, don't bother.
154   if (!Method || ComputedEST == EST_MSAny)
155     return;
156 
157   const FunctionProtoType *Proto
158     = Method->getType()->getAs<FunctionProtoType>();
159   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160   if (!Proto)
161     return;
162 
163   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164 
165   // If we have a throw-all spec at this point, ignore the function.
166   if (ComputedEST == EST_None)
167     return;
168 
169   switch(EST) {
170   // If this function can throw any exceptions, make a note of that.
171   case EST_MSAny:
172   case EST_None:
173     ClearExceptions();
174     ComputedEST = EST;
175     return;
176   // FIXME: If the call to this decl is using any of its default arguments, we
177   // need to search them for potentially-throwing calls.
178   // If this function has a basic noexcept, it doesn't affect the outcome.
179   case EST_BasicNoexcept:
180     return;
181   // If we're still at noexcept(true) and there's a nothrow() callee,
182   // change to that specification.
183   case EST_DynamicNone:
184     if (ComputedEST == EST_BasicNoexcept)
185       ComputedEST = EST_DynamicNone;
186     return;
187   // Check out noexcept specs.
188   case EST_ComputedNoexcept:
189   {
190     FunctionProtoType::NoexceptResult NR =
191         Proto->getNoexceptSpec(Self->Context);
192     assert(NR != FunctionProtoType::NR_NoNoexcept &&
193            "Must have noexcept result for EST_ComputedNoexcept.");
194     assert(NR != FunctionProtoType::NR_Dependent &&
195            "Should not generate implicit declarations for dependent cases, "
196            "and don't know how to handle them anyway.");
197     // noexcept(false) -> no spec on the new function
198     if (NR == FunctionProtoType::NR_Throw) {
199       ClearExceptions();
200       ComputedEST = EST_None;
201     }
202     // noexcept(true) won't change anything either.
203     return;
204   }
205   default:
206     break;
207   }
208   assert(EST == EST_Dynamic && "EST case not considered earlier.");
209   assert(ComputedEST != EST_None &&
210          "Shouldn't collect exceptions when throw-all is guaranteed.");
211   ComputedEST = EST_Dynamic;
212   // Record the exceptions in this function's exception specification.
213   for (const auto &E : Proto->exceptions())
214     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
215       Exceptions.push_back(E);
216 }
217 
218 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
219   if (!E || ComputedEST == EST_MSAny)
220     return;
221 
222   // FIXME:
223   //
224   // C++0x [except.spec]p14:
225   //   [An] implicit exception-specification specifies the type-id T if and
226   // only if T is allowed by the exception-specification of a function directly
227   // invoked by f's implicit definition; f shall allow all exceptions if any
228   // function it directly invokes allows all exceptions, and f shall allow no
229   // exceptions if every function it directly invokes allows no exceptions.
230   //
231   // Note in particular that if an implicit exception-specification is generated
232   // for a function containing a throw-expression, that specification can still
233   // be noexcept(true).
234   //
235   // Note also that 'directly invoked' is not defined in the standard, and there
236   // is no indication that we should only consider potentially-evaluated calls.
237   //
238   // Ultimately we should implement the intent of the standard: the exception
239   // specification should be the set of exceptions which can be thrown by the
240   // implicit definition. For now, we assume that any non-nothrow expression can
241   // throw any exception.
242 
243   if (Self->canThrow(E))
244     ComputedEST = EST_None;
245 }
246 
247 bool
248 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
249                               SourceLocation EqualLoc) {
250   if (RequireCompleteType(Param->getLocation(), Param->getType(),
251                           diag::err_typecheck_decl_incomplete_type)) {
252     Param->setInvalidDecl();
253     return true;
254   }
255 
256   // C++ [dcl.fct.default]p5
257   //   A default argument expression is implicitly converted (clause
258   //   4) to the parameter type. The default argument expression has
259   //   the same semantic constraints as the initializer expression in
260   //   a declaration of a variable of the parameter type, using the
261   //   copy-initialization semantics (8.5).
262   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
263                                                                     Param);
264   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
265                                                            EqualLoc);
266   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
267   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
268   if (Result.isInvalid())
269     return true;
270   Arg = Result.getAs<Expr>();
271 
272   CheckCompletedExpr(Arg, EqualLoc);
273   Arg = MaybeCreateExprWithCleanups(Arg);
274 
275   // Okay: add the default argument to the parameter
276   Param->setDefaultArg(Arg);
277 
278   // We have already instantiated this parameter; provide each of the
279   // instantiations with the uninstantiated default argument.
280   UnparsedDefaultArgInstantiationsMap::iterator InstPos
281     = UnparsedDefaultArgInstantiations.find(Param);
282   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
283     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
284       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
285 
286     // We're done tracking this parameter's instantiations.
287     UnparsedDefaultArgInstantiations.erase(InstPos);
288   }
289 
290   return false;
291 }
292 
293 /// ActOnParamDefaultArgument - Check whether the default argument
294 /// provided for a function parameter is well-formed. If so, attach it
295 /// to the parameter declaration.
296 void
297 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
298                                 Expr *DefaultArg) {
299   if (!param || !DefaultArg)
300     return;
301 
302   ParmVarDecl *Param = cast<ParmVarDecl>(param);
303   UnparsedDefaultArgLocs.erase(Param);
304 
305   // Default arguments are only permitted in C++
306   if (!getLangOpts().CPlusPlus) {
307     Diag(EqualLoc, diag::err_param_default_argument)
308       << DefaultArg->getSourceRange();
309     Param->setInvalidDecl();
310     return;
311   }
312 
313   // Check for unexpanded parameter packs.
314   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
315     Param->setInvalidDecl();
316     return;
317   }
318 
319   // C++11 [dcl.fct.default]p3
320   //   A default argument expression [...] shall not be specified for a
321   //   parameter pack.
322   if (Param->isParameterPack()) {
323     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
324         << DefaultArg->getSourceRange();
325     return;
326   }
327 
328   // Check that the default argument is well-formed
329   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
330   if (DefaultArgChecker.Visit(DefaultArg)) {
331     Param->setInvalidDecl();
332     return;
333   }
334 
335   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
336 }
337 
338 /// ActOnParamUnparsedDefaultArgument - We've seen a default
339 /// argument for a function parameter, but we can't parse it yet
340 /// because we're inside a class definition. Note that this default
341 /// argument will be parsed later.
342 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
343                                              SourceLocation EqualLoc,
344                                              SourceLocation ArgLoc) {
345   if (!param)
346     return;
347 
348   ParmVarDecl *Param = cast<ParmVarDecl>(param);
349   Param->setUnparsedDefaultArg();
350   UnparsedDefaultArgLocs[Param] = ArgLoc;
351 }
352 
353 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
354 /// the default argument for the parameter param failed.
355 void Sema::ActOnParamDefaultArgumentError(Decl *param,
356                                           SourceLocation EqualLoc) {
357   if (!param)
358     return;
359 
360   ParmVarDecl *Param = cast<ParmVarDecl>(param);
361   Param->setInvalidDecl();
362   UnparsedDefaultArgLocs.erase(Param);
363   Param->setDefaultArg(new(Context)
364                        OpaqueValueExpr(EqualLoc,
365                                        Param->getType().getNonReferenceType(),
366                                        VK_RValue));
367 }
368 
369 /// CheckExtraCXXDefaultArguments - Check for any extra default
370 /// arguments in the declarator, which is not a function declaration
371 /// or definition and therefore is not permitted to have default
372 /// arguments. This routine should be invoked for every declarator
373 /// that is not a function declaration or definition.
374 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
375   // C++ [dcl.fct.default]p3
376   //   A default argument expression shall be specified only in the
377   //   parameter-declaration-clause of a function declaration or in a
378   //   template-parameter (14.1). It shall not be specified for a
379   //   parameter pack. If it is specified in a
380   //   parameter-declaration-clause, it shall not occur within a
381   //   declarator or abstract-declarator of a parameter-declaration.
382   bool MightBeFunction = D.isFunctionDeclarationContext();
383   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
384     DeclaratorChunk &chunk = D.getTypeObject(i);
385     if (chunk.Kind == DeclaratorChunk::Function) {
386       if (MightBeFunction) {
387         // This is a function declaration. It can have default arguments, but
388         // keep looking in case its return type is a function type with default
389         // arguments.
390         MightBeFunction = false;
391         continue;
392       }
393       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
394            ++argIdx) {
395         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
396         if (Param->hasUnparsedDefaultArg()) {
397           CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
398           SourceRange SR;
399           if (Toks->size() > 1)
400             SR = SourceRange((*Toks)[1].getLocation(),
401                              Toks->back().getLocation());
402           else
403             SR = UnparsedDefaultArgLocs[Param];
404           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
405             << SR;
406           delete Toks;
407           chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
408         } else if (Param->getDefaultArg()) {
409           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410             << Param->getDefaultArg()->getSourceRange();
411           Param->setDefaultArg(nullptr);
412         }
413       }
414     } else if (chunk.Kind != DeclaratorChunk::Paren) {
415       MightBeFunction = false;
416     }
417   }
418 }
419 
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421   for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422     const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423     if (!PVD->hasDefaultArg())
424       return false;
425     if (!PVD->hasInheritedDefaultArg())
426       return true;
427   }
428   return false;
429 }
430 
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
436                                 Scope *S) {
437   bool Invalid = false;
438 
439   // The declaration context corresponding to the scope is the semantic
440   // parent, unless this is a local function declaration, in which case
441   // it is that surrounding function.
442   DeclContext *ScopeDC = New->isLocalExternDecl()
443                              ? New->getLexicalDeclContext()
444                              : New->getDeclContext();
445 
446   // Find the previous declaration for the purpose of default arguments.
447   FunctionDecl *PrevForDefaultArgs = Old;
448   for (/**/; PrevForDefaultArgs;
449        // Don't bother looking back past the latest decl if this is a local
450        // extern declaration; nothing else could work.
451        PrevForDefaultArgs = New->isLocalExternDecl()
452                                 ? nullptr
453                                 : PrevForDefaultArgs->getPreviousDecl()) {
454     // Ignore hidden declarations.
455     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
456       continue;
457 
458     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459         !New->isCXXClassMember()) {
460       // Ignore default arguments of old decl if they are not in
461       // the same scope and this is not an out-of-line definition of
462       // a member function.
463       continue;
464     }
465 
466     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467       // If only one of these is a local function declaration, then they are
468       // declared in different scopes, even though isDeclInScope may think
469       // they're in the same scope. (If both are local, the scope check is
470       // sufficent, and if neither is local, then they are in the same scope.)
471       continue;
472     }
473 
474     // We found our guy.
475     break;
476   }
477 
478   // C++ [dcl.fct.default]p4:
479   //   For non-template functions, default arguments can be added in
480   //   later declarations of a function in the same
481   //   scope. Declarations in different scopes have completely
482   //   distinct sets of default arguments. That is, declarations in
483   //   inner scopes do not acquire default arguments from
484   //   declarations in outer scopes, and vice versa. In a given
485   //   function declaration, all parameters subsequent to a
486   //   parameter with a default argument shall have default
487   //   arguments supplied in this or previous declarations. A
488   //   default argument shall not be redefined by a later
489   //   declaration (not even to the same value).
490   //
491   // C++ [dcl.fct.default]p6:
492   //   Except for member functions of class templates, the default arguments
493   //   in a member function definition that appears outside of the class
494   //   definition are added to the set of default arguments provided by the
495   //   member function declaration in the class definition.
496   for (unsigned p = 0, NumParams = PrevForDefaultArgs
497                                        ? PrevForDefaultArgs->getNumParams()
498                                        : 0;
499        p < NumParams; ++p) {
500     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501     ParmVarDecl *NewParam = New->getParamDecl(p);
502 
503     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504     bool NewParamHasDfl = NewParam->hasDefaultArg();
505 
506     if (OldParamHasDfl && NewParamHasDfl) {
507       unsigned DiagDefaultParamID =
508         diag::err_param_default_argument_redefinition;
509 
510       // MSVC accepts that default parameters be redefined for member functions
511       // of template class. The new default parameter's value is ignored.
512       Invalid = true;
513       if (getLangOpts().MicrosoftExt) {
514         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515         if (MD && MD->getParent()->getDescribedClassTemplate()) {
516           // Merge the old default argument into the new parameter.
517           NewParam->setHasInheritedDefaultArg();
518           if (OldParam->hasUninstantiatedDefaultArg())
519             NewParam->setUninstantiatedDefaultArg(
520                                       OldParam->getUninstantiatedDefaultArg());
521           else
522             NewParam->setDefaultArg(OldParam->getInit());
523           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
524           Invalid = false;
525         }
526       }
527 
528       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529       // hint here. Alternatively, we could walk the type-source information
530       // for NewParam to find the last source location in the type... but it
531       // isn't worth the effort right now. This is the kind of test case that
532       // is hard to get right:
533       //   int f(int);
534       //   void g(int (*fp)(int) = f);
535       //   void g(int (*fp)(int) = &f);
536       Diag(NewParam->getLocation(), DiagDefaultParamID)
537         << NewParam->getDefaultArgRange();
538 
539       // Look for the function declaration where the default argument was
540       // actually written, which may be a declaration prior to Old.
541       for (auto Older = PrevForDefaultArgs;
542            OldParam->hasInheritedDefaultArg(); /**/) {
543         Older = Older->getPreviousDecl();
544         OldParam = Older->getParamDecl(p);
545       }
546 
547       Diag(OldParam->getLocation(), diag::note_previous_definition)
548         << OldParam->getDefaultArgRange();
549     } else if (OldParamHasDfl) {
550       // Merge the old default argument into the new parameter.
551       // It's important to use getInit() here;  getDefaultArg()
552       // strips off any top-level ExprWithCleanups.
553       NewParam->setHasInheritedDefaultArg();
554       if (OldParam->hasUnparsedDefaultArg())
555         NewParam->setUnparsedDefaultArg();
556       else if (OldParam->hasUninstantiatedDefaultArg())
557         NewParam->setUninstantiatedDefaultArg(
558                                       OldParam->getUninstantiatedDefaultArg());
559       else
560         NewParam->setDefaultArg(OldParam->getInit());
561     } else if (NewParamHasDfl) {
562       if (New->getDescribedFunctionTemplate()) {
563         // Paragraph 4, quoted above, only applies to non-template functions.
564         Diag(NewParam->getLocation(),
565              diag::err_param_default_argument_template_redecl)
566           << NewParam->getDefaultArgRange();
567         Diag(PrevForDefaultArgs->getLocation(),
568              diag::note_template_prev_declaration)
569             << false;
570       } else if (New->getTemplateSpecializationKind()
571                    != TSK_ImplicitInstantiation &&
572                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
573         // C++ [temp.expr.spec]p21:
574         //   Default function arguments shall not be specified in a declaration
575         //   or a definition for one of the following explicit specializations:
576         //     - the explicit specialization of a function template;
577         //     - the explicit specialization of a member function template;
578         //     - the explicit specialization of a member function of a class
579         //       template where the class template specialization to which the
580         //       member function specialization belongs is implicitly
581         //       instantiated.
582         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
583           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
584           << New->getDeclName()
585           << NewParam->getDefaultArgRange();
586       } else if (New->getDeclContext()->isDependentContext()) {
587         // C++ [dcl.fct.default]p6 (DR217):
588         //   Default arguments for a member function of a class template shall
589         //   be specified on the initial declaration of the member function
590         //   within the class template.
591         //
592         // Reading the tea leaves a bit in DR217 and its reference to DR205
593         // leads me to the conclusion that one cannot add default function
594         // arguments for an out-of-line definition of a member function of a
595         // dependent type.
596         int WhichKind = 2;
597         if (CXXRecordDecl *Record
598               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
599           if (Record->getDescribedClassTemplate())
600             WhichKind = 0;
601           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
602             WhichKind = 1;
603           else
604             WhichKind = 2;
605         }
606 
607         Diag(NewParam->getLocation(),
608              diag::err_param_default_argument_member_template_redecl)
609           << WhichKind
610           << NewParam->getDefaultArgRange();
611       }
612     }
613   }
614 
615   // DR1344: If a default argument is added outside a class definition and that
616   // default argument makes the function a special member function, the program
617   // is ill-formed. This can only happen for constructors.
618   if (isa<CXXConstructorDecl>(New) &&
619       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
620     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
621                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
622     if (NewSM != OldSM) {
623       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
624       assert(NewParam->hasDefaultArg());
625       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
626         << NewParam->getDefaultArgRange() << NewSM;
627       Diag(Old->getLocation(), diag::note_previous_declaration);
628     }
629   }
630 
631   const FunctionDecl *Def;
632   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
633   // template has a constexpr specifier then all its declarations shall
634   // contain the constexpr specifier.
635   if (New->isConstexpr() != Old->isConstexpr()) {
636     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
637       << New << New->isConstexpr();
638     Diag(Old->getLocation(), diag::note_previous_declaration);
639     Invalid = true;
640   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
641              Old->isDefined(Def)) {
642     // C++11 [dcl.fcn.spec]p4:
643     //   If the definition of a function appears in a translation unit before its
644     //   first declaration as inline, the program is ill-formed.
645     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
646     Diag(Def->getLocation(), diag::note_previous_definition);
647     Invalid = true;
648   }
649 
650   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
651   // argument expression, that declaration shall be a definition and shall be
652   // the only declaration of the function or function template in the
653   // translation unit.
654   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
655       functionDeclHasDefaultArgument(Old)) {
656     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
657     Diag(Old->getLocation(), diag::note_previous_declaration);
658     Invalid = true;
659   }
660 
661   if (CheckEquivalentExceptionSpec(Old, New))
662     Invalid = true;
663 
664   return Invalid;
665 }
666 
667 /// \brief Merge the exception specifications of two variable declarations.
668 ///
669 /// This is called when there's a redeclaration of a VarDecl. The function
670 /// checks if the redeclaration might have an exception specification and
671 /// validates compatibility and merges the specs if necessary.
672 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
673   // Shortcut if exceptions are disabled.
674   if (!getLangOpts().CXXExceptions)
675     return;
676 
677   assert(Context.hasSameType(New->getType(), Old->getType()) &&
678          "Should only be called if types are otherwise the same.");
679 
680   QualType NewType = New->getType();
681   QualType OldType = Old->getType();
682 
683   // We're only interested in pointers and references to functions, as well
684   // as pointers to member functions.
685   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
686     NewType = R->getPointeeType();
687     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
688   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
689     NewType = P->getPointeeType();
690     OldType = OldType->getAs<PointerType>()->getPointeeType();
691   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
692     NewType = M->getPointeeType();
693     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
694   }
695 
696   if (!NewType->isFunctionProtoType())
697     return;
698 
699   // There's lots of special cases for functions. For function pointers, system
700   // libraries are hopefully not as broken so that we don't need these
701   // workarounds.
702   if (CheckEquivalentExceptionSpec(
703         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
704         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
705     New->setInvalidDecl();
706   }
707 }
708 
709 /// CheckCXXDefaultArguments - Verify that the default arguments for a
710 /// function declaration are well-formed according to C++
711 /// [dcl.fct.default].
712 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
713   unsigned NumParams = FD->getNumParams();
714   unsigned p;
715 
716   // Find first parameter with a default argument
717   for (p = 0; p < NumParams; ++p) {
718     ParmVarDecl *Param = FD->getParamDecl(p);
719     if (Param->hasDefaultArg())
720       break;
721   }
722 
723   // C++11 [dcl.fct.default]p4:
724   //   In a given function declaration, each parameter subsequent to a parameter
725   //   with a default argument shall have a default argument supplied in this or
726   //   a previous declaration or shall be a function parameter pack. A default
727   //   argument shall not be redefined by a later declaration (not even to the
728   //   same value).
729   unsigned LastMissingDefaultArg = 0;
730   for (; p < NumParams; ++p) {
731     ParmVarDecl *Param = FD->getParamDecl(p);
732     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
733       if (Param->isInvalidDecl())
734         /* We already complained about this parameter. */;
735       else if (Param->getIdentifier())
736         Diag(Param->getLocation(),
737              diag::err_param_default_argument_missing_name)
738           << Param->getIdentifier();
739       else
740         Diag(Param->getLocation(),
741              diag::err_param_default_argument_missing);
742 
743       LastMissingDefaultArg = p;
744     }
745   }
746 
747   if (LastMissingDefaultArg > 0) {
748     // Some default arguments were missing. Clear out all of the
749     // default arguments up to (and including) the last missing
750     // default argument, so that we leave the function parameters
751     // in a semantically valid state.
752     for (p = 0; p <= LastMissingDefaultArg; ++p) {
753       ParmVarDecl *Param = FD->getParamDecl(p);
754       if (Param->hasDefaultArg()) {
755         Param->setDefaultArg(nullptr);
756       }
757     }
758   }
759 }
760 
761 // CheckConstexprParameterTypes - Check whether a function's parameter types
762 // are all literal types. If so, return true. If not, produce a suitable
763 // diagnostic and return false.
764 static bool CheckConstexprParameterTypes(Sema &SemaRef,
765                                          const FunctionDecl *FD) {
766   unsigned ArgIndex = 0;
767   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
768   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
769                                               e = FT->param_type_end();
770        i != e; ++i, ++ArgIndex) {
771     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
772     SourceLocation ParamLoc = PD->getLocation();
773     if (!(*i)->isDependentType() &&
774         SemaRef.RequireLiteralType(ParamLoc, *i,
775                                    diag::err_constexpr_non_literal_param,
776                                    ArgIndex+1, PD->getSourceRange(),
777                                    isa<CXXConstructorDecl>(FD)))
778       return false;
779   }
780   return true;
781 }
782 
783 /// \brief Get diagnostic %select index for tag kind for
784 /// record diagnostic message.
785 /// WARNING: Indexes apply to particular diagnostics only!
786 ///
787 /// \returns diagnostic %select index.
788 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
789   switch (Tag) {
790   case TTK_Struct: return 0;
791   case TTK_Interface: return 1;
792   case TTK_Class:  return 2;
793   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
794   }
795 }
796 
797 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
798 // the requirements of a constexpr function definition or a constexpr
799 // constructor definition. If so, return true. If not, produce appropriate
800 // diagnostics and return false.
801 //
802 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
803 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
804   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
805   if (MD && MD->isInstance()) {
806     // C++11 [dcl.constexpr]p4:
807     //  The definition of a constexpr constructor shall satisfy the following
808     //  constraints:
809     //  - the class shall not have any virtual base classes;
810     const CXXRecordDecl *RD = MD->getParent();
811     if (RD->getNumVBases()) {
812       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
813         << isa<CXXConstructorDecl>(NewFD)
814         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
815       for (const auto &I : RD->vbases())
816         Diag(I.getLocStart(),
817              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
818       return false;
819     }
820   }
821 
822   if (!isa<CXXConstructorDecl>(NewFD)) {
823     // C++11 [dcl.constexpr]p3:
824     //  The definition of a constexpr function shall satisfy the following
825     //  constraints:
826     // - it shall not be virtual;
827     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
828     if (Method && Method->isVirtual()) {
829       Method = Method->getCanonicalDecl();
830       Diag(Method->getLocation(), diag::err_constexpr_virtual);
831 
832       // If it's not obvious why this function is virtual, find an overridden
833       // function which uses the 'virtual' keyword.
834       const CXXMethodDecl *WrittenVirtual = Method;
835       while (!WrittenVirtual->isVirtualAsWritten())
836         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
837       if (WrittenVirtual != Method)
838         Diag(WrittenVirtual->getLocation(),
839              diag::note_overridden_virtual_function);
840       return false;
841     }
842 
843     // - its return type shall be a literal type;
844     QualType RT = NewFD->getReturnType();
845     if (!RT->isDependentType() &&
846         RequireLiteralType(NewFD->getLocation(), RT,
847                            diag::err_constexpr_non_literal_return))
848       return false;
849   }
850 
851   // - each of its parameter types shall be a literal type;
852   if (!CheckConstexprParameterTypes(*this, NewFD))
853     return false;
854 
855   return true;
856 }
857 
858 /// Check the given declaration statement is legal within a constexpr function
859 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
860 ///
861 /// \return true if the body is OK (maybe only as an extension), false if we
862 ///         have diagnosed a problem.
863 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
864                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
865   // C++11 [dcl.constexpr]p3 and p4:
866   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
867   //  contain only
868   for (const auto *DclIt : DS->decls()) {
869     switch (DclIt->getKind()) {
870     case Decl::StaticAssert:
871     case Decl::Using:
872     case Decl::UsingShadow:
873     case Decl::UsingDirective:
874     case Decl::UnresolvedUsingTypename:
875     case Decl::UnresolvedUsingValue:
876       //   - static_assert-declarations
877       //   - using-declarations,
878       //   - using-directives,
879       continue;
880 
881     case Decl::Typedef:
882     case Decl::TypeAlias: {
883       //   - typedef declarations and alias-declarations that do not define
884       //     classes or enumerations,
885       const auto *TN = cast<TypedefNameDecl>(DclIt);
886       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
887         // Don't allow variably-modified types in constexpr functions.
888         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
889         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
890           << TL.getSourceRange() << TL.getType()
891           << isa<CXXConstructorDecl>(Dcl);
892         return false;
893       }
894       continue;
895     }
896 
897     case Decl::Enum:
898     case Decl::CXXRecord:
899       // C++1y allows types to be defined, not just declared.
900       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
901         SemaRef.Diag(DS->getLocStart(),
902                      SemaRef.getLangOpts().CPlusPlus14
903                        ? diag::warn_cxx11_compat_constexpr_type_definition
904                        : diag::ext_constexpr_type_definition)
905           << isa<CXXConstructorDecl>(Dcl);
906       continue;
907 
908     case Decl::EnumConstant:
909     case Decl::IndirectField:
910     case Decl::ParmVar:
911       // These can only appear with other declarations which are banned in
912       // C++11 and permitted in C++1y, so ignore them.
913       continue;
914 
915     case Decl::Var: {
916       // C++1y [dcl.constexpr]p3 allows anything except:
917       //   a definition of a variable of non-literal type or of static or
918       //   thread storage duration or for which no initialization is performed.
919       const auto *VD = cast<VarDecl>(DclIt);
920       if (VD->isThisDeclarationADefinition()) {
921         if (VD->isStaticLocal()) {
922           SemaRef.Diag(VD->getLocation(),
923                        diag::err_constexpr_local_var_static)
924             << isa<CXXConstructorDecl>(Dcl)
925             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
926           return false;
927         }
928         if (!VD->getType()->isDependentType() &&
929             SemaRef.RequireLiteralType(
930               VD->getLocation(), VD->getType(),
931               diag::err_constexpr_local_var_non_literal_type,
932               isa<CXXConstructorDecl>(Dcl)))
933           return false;
934         if (!VD->getType()->isDependentType() &&
935             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
936           SemaRef.Diag(VD->getLocation(),
937                        diag::err_constexpr_local_var_no_init)
938             << isa<CXXConstructorDecl>(Dcl);
939           return false;
940         }
941       }
942       SemaRef.Diag(VD->getLocation(),
943                    SemaRef.getLangOpts().CPlusPlus14
944                     ? diag::warn_cxx11_compat_constexpr_local_var
945                     : diag::ext_constexpr_local_var)
946         << isa<CXXConstructorDecl>(Dcl);
947       continue;
948     }
949 
950     case Decl::NamespaceAlias:
951     case Decl::Function:
952       // These are disallowed in C++11 and permitted in C++1y. Allow them
953       // everywhere as an extension.
954       if (!Cxx1yLoc.isValid())
955         Cxx1yLoc = DS->getLocStart();
956       continue;
957 
958     default:
959       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
960         << isa<CXXConstructorDecl>(Dcl);
961       return false;
962     }
963   }
964 
965   return true;
966 }
967 
968 /// Check that the given field is initialized within a constexpr constructor.
969 ///
970 /// \param Dcl The constexpr constructor being checked.
971 /// \param Field The field being checked. This may be a member of an anonymous
972 ///        struct or union nested within the class being checked.
973 /// \param Inits All declarations, including anonymous struct/union members and
974 ///        indirect members, for which any initialization was provided.
975 /// \param Diagnosed Set to true if an error is produced.
976 static void CheckConstexprCtorInitializer(Sema &SemaRef,
977                                           const FunctionDecl *Dcl,
978                                           FieldDecl *Field,
979                                           llvm::SmallSet<Decl*, 16> &Inits,
980                                           bool &Diagnosed) {
981   if (Field->isInvalidDecl())
982     return;
983 
984   if (Field->isUnnamedBitfield())
985     return;
986 
987   // Anonymous unions with no variant members and empty anonymous structs do not
988   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
989   // indirect fields don't need initializing.
990   if (Field->isAnonymousStructOrUnion() &&
991       (Field->getType()->isUnionType()
992            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
993            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
994     return;
995 
996   if (!Inits.count(Field)) {
997     if (!Diagnosed) {
998       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
999       Diagnosed = true;
1000     }
1001     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1002   } else if (Field->isAnonymousStructOrUnion()) {
1003     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1004     for (auto *I : RD->fields())
1005       // If an anonymous union contains an anonymous struct of which any member
1006       // is initialized, all members must be initialized.
1007       if (!RD->isUnion() || Inits.count(I))
1008         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1009   }
1010 }
1011 
1012 /// Check the provided statement is allowed in a constexpr function
1013 /// definition.
1014 static bool
1015 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1016                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1017                            SourceLocation &Cxx1yLoc) {
1018   // - its function-body shall be [...] a compound-statement that contains only
1019   switch (S->getStmtClass()) {
1020   case Stmt::NullStmtClass:
1021     //   - null statements,
1022     return true;
1023 
1024   case Stmt::DeclStmtClass:
1025     //   - static_assert-declarations
1026     //   - using-declarations,
1027     //   - using-directives,
1028     //   - typedef declarations and alias-declarations that do not define
1029     //     classes or enumerations,
1030     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1031       return false;
1032     return true;
1033 
1034   case Stmt::ReturnStmtClass:
1035     //   - and exactly one return statement;
1036     if (isa<CXXConstructorDecl>(Dcl)) {
1037       // C++1y allows return statements in constexpr constructors.
1038       if (!Cxx1yLoc.isValid())
1039         Cxx1yLoc = S->getLocStart();
1040       return true;
1041     }
1042 
1043     ReturnStmts.push_back(S->getLocStart());
1044     return true;
1045 
1046   case Stmt::CompoundStmtClass: {
1047     // C++1y allows compound-statements.
1048     if (!Cxx1yLoc.isValid())
1049       Cxx1yLoc = S->getLocStart();
1050 
1051     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1052     for (auto *BodyIt : CompStmt->body()) {
1053       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1054                                       Cxx1yLoc))
1055         return false;
1056     }
1057     return true;
1058   }
1059 
1060   case Stmt::AttributedStmtClass:
1061     if (!Cxx1yLoc.isValid())
1062       Cxx1yLoc = S->getLocStart();
1063     return true;
1064 
1065   case Stmt::IfStmtClass: {
1066     // C++1y allows if-statements.
1067     if (!Cxx1yLoc.isValid())
1068       Cxx1yLoc = S->getLocStart();
1069 
1070     IfStmt *If = cast<IfStmt>(S);
1071     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1072                                     Cxx1yLoc))
1073       return false;
1074     if (If->getElse() &&
1075         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1076                                     Cxx1yLoc))
1077       return false;
1078     return true;
1079   }
1080 
1081   case Stmt::WhileStmtClass:
1082   case Stmt::DoStmtClass:
1083   case Stmt::ForStmtClass:
1084   case Stmt::CXXForRangeStmtClass:
1085   case Stmt::ContinueStmtClass:
1086     // C++1y allows all of these. We don't allow them as extensions in C++11,
1087     // because they don't make sense without variable mutation.
1088     if (!SemaRef.getLangOpts().CPlusPlus14)
1089       break;
1090     if (!Cxx1yLoc.isValid())
1091       Cxx1yLoc = S->getLocStart();
1092     for (Stmt *SubStmt : S->children())
1093       if (SubStmt &&
1094           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1095                                       Cxx1yLoc))
1096         return false;
1097     return true;
1098 
1099   case Stmt::SwitchStmtClass:
1100   case Stmt::CaseStmtClass:
1101   case Stmt::DefaultStmtClass:
1102   case Stmt::BreakStmtClass:
1103     // C++1y allows switch-statements, and since they don't need variable
1104     // mutation, we can reasonably allow them in C++11 as an extension.
1105     if (!Cxx1yLoc.isValid())
1106       Cxx1yLoc = S->getLocStart();
1107     for (Stmt *SubStmt : S->children())
1108       if (SubStmt &&
1109           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1110                                       Cxx1yLoc))
1111         return false;
1112     return true;
1113 
1114   default:
1115     if (!isa<Expr>(S))
1116       break;
1117 
1118     // C++1y allows expression-statements.
1119     if (!Cxx1yLoc.isValid())
1120       Cxx1yLoc = S->getLocStart();
1121     return true;
1122   }
1123 
1124   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1125     << isa<CXXConstructorDecl>(Dcl);
1126   return false;
1127 }
1128 
1129 /// Check the body for the given constexpr function declaration only contains
1130 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1131 ///
1132 /// \return true if the body is OK, false if we have diagnosed a problem.
1133 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1134   if (isa<CXXTryStmt>(Body)) {
1135     // C++11 [dcl.constexpr]p3:
1136     //  The definition of a constexpr function shall satisfy the following
1137     //  constraints: [...]
1138     // - its function-body shall be = delete, = default, or a
1139     //   compound-statement
1140     //
1141     // C++11 [dcl.constexpr]p4:
1142     //  In the definition of a constexpr constructor, [...]
1143     // - its function-body shall not be a function-try-block;
1144     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1145       << isa<CXXConstructorDecl>(Dcl);
1146     return false;
1147   }
1148 
1149   SmallVector<SourceLocation, 4> ReturnStmts;
1150 
1151   // - its function-body shall be [...] a compound-statement that contains only
1152   //   [... list of cases ...]
1153   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1154   SourceLocation Cxx1yLoc;
1155   for (auto *BodyIt : CompBody->body()) {
1156     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1157       return false;
1158   }
1159 
1160   if (Cxx1yLoc.isValid())
1161     Diag(Cxx1yLoc,
1162          getLangOpts().CPlusPlus14
1163            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1164            : diag::ext_constexpr_body_invalid_stmt)
1165       << isa<CXXConstructorDecl>(Dcl);
1166 
1167   if (const CXXConstructorDecl *Constructor
1168         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1169     const CXXRecordDecl *RD = Constructor->getParent();
1170     // DR1359:
1171     // - every non-variant non-static data member and base class sub-object
1172     //   shall be initialized;
1173     // DR1460:
1174     // - if the class is a union having variant members, exactly one of them
1175     //   shall be initialized;
1176     if (RD->isUnion()) {
1177       if (Constructor->getNumCtorInitializers() == 0 &&
1178           RD->hasVariantMembers()) {
1179         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1180         return false;
1181       }
1182     } else if (!Constructor->isDependentContext() &&
1183                !Constructor->isDelegatingConstructor()) {
1184       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1185 
1186       // Skip detailed checking if we have enough initializers, and we would
1187       // allow at most one initializer per member.
1188       bool AnyAnonStructUnionMembers = false;
1189       unsigned Fields = 0;
1190       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1191            E = RD->field_end(); I != E; ++I, ++Fields) {
1192         if (I->isAnonymousStructOrUnion()) {
1193           AnyAnonStructUnionMembers = true;
1194           break;
1195         }
1196       }
1197       // DR1460:
1198       // - if the class is a union-like class, but is not a union, for each of
1199       //   its anonymous union members having variant members, exactly one of
1200       //   them shall be initialized;
1201       if (AnyAnonStructUnionMembers ||
1202           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1203         // Check initialization of non-static data members. Base classes are
1204         // always initialized so do not need to be checked. Dependent bases
1205         // might not have initializers in the member initializer list.
1206         llvm::SmallSet<Decl*, 16> Inits;
1207         for (const auto *I: Constructor->inits()) {
1208           if (FieldDecl *FD = I->getMember())
1209             Inits.insert(FD);
1210           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1211             Inits.insert(ID->chain_begin(), ID->chain_end());
1212         }
1213 
1214         bool Diagnosed = false;
1215         for (auto *I : RD->fields())
1216           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1217         if (Diagnosed)
1218           return false;
1219       }
1220     }
1221   } else {
1222     if (ReturnStmts.empty()) {
1223       // C++1y doesn't require constexpr functions to contain a 'return'
1224       // statement. We still do, unless the return type might be void, because
1225       // otherwise if there's no return statement, the function cannot
1226       // be used in a core constant expression.
1227       bool OK = getLangOpts().CPlusPlus14 &&
1228                 (Dcl->getReturnType()->isVoidType() ||
1229                  Dcl->getReturnType()->isDependentType());
1230       Diag(Dcl->getLocation(),
1231            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1232               : diag::err_constexpr_body_no_return);
1233       return OK;
1234     }
1235     if (ReturnStmts.size() > 1) {
1236       Diag(ReturnStmts.back(),
1237            getLangOpts().CPlusPlus14
1238              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1239              : diag::ext_constexpr_body_multiple_return);
1240       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1241         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1242     }
1243   }
1244 
1245   // C++11 [dcl.constexpr]p5:
1246   //   if no function argument values exist such that the function invocation
1247   //   substitution would produce a constant expression, the program is
1248   //   ill-formed; no diagnostic required.
1249   // C++11 [dcl.constexpr]p3:
1250   //   - every constructor call and implicit conversion used in initializing the
1251   //     return value shall be one of those allowed in a constant expression.
1252   // C++11 [dcl.constexpr]p4:
1253   //   - every constructor involved in initializing non-static data members and
1254   //     base class sub-objects shall be a constexpr constructor.
1255   SmallVector<PartialDiagnosticAt, 8> Diags;
1256   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1257     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1258       << isa<CXXConstructorDecl>(Dcl);
1259     for (size_t I = 0, N = Diags.size(); I != N; ++I)
1260       Diag(Diags[I].first, Diags[I].second);
1261     // Don't return false here: we allow this for compatibility in
1262     // system headers.
1263   }
1264 
1265   return true;
1266 }
1267 
1268 /// isCurrentClassName - Determine whether the identifier II is the
1269 /// name of the class type currently being defined. In the case of
1270 /// nested classes, this will only return true if II is the name of
1271 /// the innermost class.
1272 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1273                               const CXXScopeSpec *SS) {
1274   assert(getLangOpts().CPlusPlus && "No class names in C!");
1275 
1276   CXXRecordDecl *CurDecl;
1277   if (SS && SS->isSet() && !SS->isInvalid()) {
1278     DeclContext *DC = computeDeclContext(*SS, true);
1279     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1280   } else
1281     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1282 
1283   if (CurDecl && CurDecl->getIdentifier())
1284     return &II == CurDecl->getIdentifier();
1285   return false;
1286 }
1287 
1288 /// \brief Determine whether the identifier II is a typo for the name of
1289 /// the class type currently being defined. If so, update it to the identifier
1290 /// that should have been used.
1291 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1292   assert(getLangOpts().CPlusPlus && "No class names in C!");
1293 
1294   if (!getLangOpts().SpellChecking)
1295     return false;
1296 
1297   CXXRecordDecl *CurDecl;
1298   if (SS && SS->isSet() && !SS->isInvalid()) {
1299     DeclContext *DC = computeDeclContext(*SS, true);
1300     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1301   } else
1302     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1303 
1304   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1305       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1306           < II->getLength()) {
1307     II = CurDecl->getIdentifier();
1308     return true;
1309   }
1310 
1311   return false;
1312 }
1313 
1314 /// \brief Determine whether the given class is a base class of the given
1315 /// class, including looking at dependent bases.
1316 static bool findCircularInheritance(const CXXRecordDecl *Class,
1317                                     const CXXRecordDecl *Current) {
1318   SmallVector<const CXXRecordDecl*, 8> Queue;
1319 
1320   Class = Class->getCanonicalDecl();
1321   while (true) {
1322     for (const auto &I : Current->bases()) {
1323       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
1324       if (!Base)
1325         continue;
1326 
1327       Base = Base->getDefinition();
1328       if (!Base)
1329         continue;
1330 
1331       if (Base->getCanonicalDecl() == Class)
1332         return true;
1333 
1334       Queue.push_back(Base);
1335     }
1336 
1337     if (Queue.empty())
1338       return false;
1339 
1340     Current = Queue.pop_back_val();
1341   }
1342 
1343   return false;
1344 }
1345 
1346 /// \brief Check the validity of a C++ base class specifier.
1347 ///
1348 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1349 /// and returns NULL otherwise.
1350 CXXBaseSpecifier *
1351 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1352                          SourceRange SpecifierRange,
1353                          bool Virtual, AccessSpecifier Access,
1354                          TypeSourceInfo *TInfo,
1355                          SourceLocation EllipsisLoc) {
1356   QualType BaseType = TInfo->getType();
1357 
1358   // C++ [class.union]p1:
1359   //   A union shall not have base classes.
1360   if (Class->isUnion()) {
1361     Diag(Class->getLocation(), diag::err_base_clause_on_union)
1362       << SpecifierRange;
1363     return nullptr;
1364   }
1365 
1366   if (EllipsisLoc.isValid() &&
1367       !TInfo->getType()->containsUnexpandedParameterPack()) {
1368     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1369       << TInfo->getTypeLoc().getSourceRange();
1370     EllipsisLoc = SourceLocation();
1371   }
1372 
1373   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1374 
1375   if (BaseType->isDependentType()) {
1376     // Make sure that we don't have circular inheritance among our dependent
1377     // bases. For non-dependent bases, the check for completeness below handles
1378     // this.
1379     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1380       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1381           ((BaseDecl = BaseDecl->getDefinition()) &&
1382            findCircularInheritance(Class, BaseDecl))) {
1383         Diag(BaseLoc, diag::err_circular_inheritance)
1384           << BaseType << Context.getTypeDeclType(Class);
1385 
1386         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1387           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1388             << BaseType;
1389 
1390         return nullptr;
1391       }
1392     }
1393 
1394     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1395                                           Class->getTagKind() == TTK_Class,
1396                                           Access, TInfo, EllipsisLoc);
1397   }
1398 
1399   // Base specifiers must be record types.
1400   if (!BaseType->isRecordType()) {
1401     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1402     return nullptr;
1403   }
1404 
1405   // C++ [class.union]p1:
1406   //   A union shall not be used as a base class.
1407   if (BaseType->isUnionType()) {
1408     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1409     return nullptr;
1410   }
1411 
1412   // For the MS ABI, propagate DLL attributes to base class templates.
1413   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1414     if (Attr *ClassAttr = getDLLAttr(Class)) {
1415       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1416               BaseType->getAsCXXRecordDecl())) {
1417         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
1418                                             BaseLoc);
1419       }
1420     }
1421   }
1422 
1423   // C++ [class.derived]p2:
1424   //   The class-name in a base-specifier shall not be an incompletely
1425   //   defined class.
1426   if (RequireCompleteType(BaseLoc, BaseType,
1427                           diag::err_incomplete_base_class, SpecifierRange)) {
1428     Class->setInvalidDecl();
1429     return nullptr;
1430   }
1431 
1432   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1433   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1434   assert(BaseDecl && "Record type has no declaration");
1435   BaseDecl = BaseDecl->getDefinition();
1436   assert(BaseDecl && "Base type is not incomplete, but has no definition");
1437   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1438   assert(CXXBaseDecl && "Base type is not a C++ type");
1439 
1440   // A class which contains a flexible array member is not suitable for use as a
1441   // base class:
1442   //   - If the layout determines that a base comes before another base,
1443   //     the flexible array member would index into the subsequent base.
1444   //   - If the layout determines that base comes before the derived class,
1445   //     the flexible array member would index into the derived class.
1446   if (CXXBaseDecl->hasFlexibleArrayMember()) {
1447     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1448       << CXXBaseDecl->getDeclName();
1449     return nullptr;
1450   }
1451 
1452   // C++ [class]p3:
1453   //   If a class is marked final and it appears as a base-type-specifier in
1454   //   base-clause, the program is ill-formed.
1455   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1456     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1457       << CXXBaseDecl->getDeclName()
1458       << FA->isSpelledAsSealed();
1459     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1460         << CXXBaseDecl->getDeclName() << FA->getRange();
1461     return nullptr;
1462   }
1463 
1464   if (BaseDecl->isInvalidDecl())
1465     Class->setInvalidDecl();
1466 
1467   // Create the base specifier.
1468   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1469                                         Class->getTagKind() == TTK_Class,
1470                                         Access, TInfo, EllipsisLoc);
1471 }
1472 
1473 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1474 /// one entry in the base class list of a class specifier, for
1475 /// example:
1476 ///    class foo : public bar, virtual private baz {
1477 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1478 BaseResult
1479 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1480                          ParsedAttributes &Attributes,
1481                          bool Virtual, AccessSpecifier Access,
1482                          ParsedType basetype, SourceLocation BaseLoc,
1483                          SourceLocation EllipsisLoc) {
1484   if (!classdecl)
1485     return true;
1486 
1487   AdjustDeclIfTemplate(classdecl);
1488   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1489   if (!Class)
1490     return true;
1491 
1492   // We haven't yet attached the base specifiers.
1493   Class->setIsParsingBaseSpecifiers();
1494 
1495   // We do not support any C++11 attributes on base-specifiers yet.
1496   // Diagnose any attributes we see.
1497   if (!Attributes.empty()) {
1498     for (AttributeList *Attr = Attributes.getList(); Attr;
1499          Attr = Attr->getNext()) {
1500       if (Attr->isInvalid() ||
1501           Attr->getKind() == AttributeList::IgnoredAttribute)
1502         continue;
1503       Diag(Attr->getLoc(),
1504            Attr->getKind() == AttributeList::UnknownAttribute
1505              ? diag::warn_unknown_attribute_ignored
1506              : diag::err_base_specifier_attribute)
1507         << Attr->getName();
1508     }
1509   }
1510 
1511   TypeSourceInfo *TInfo = nullptr;
1512   GetTypeFromParser(basetype, &TInfo);
1513 
1514   if (EllipsisLoc.isInvalid() &&
1515       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1516                                       UPPC_BaseType))
1517     return true;
1518 
1519   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1520                                                       Virtual, Access, TInfo,
1521                                                       EllipsisLoc))
1522     return BaseSpec;
1523   else
1524     Class->setInvalidDecl();
1525 
1526   return true;
1527 }
1528 
1529 /// Use small set to collect indirect bases.  As this is only used
1530 /// locally, there's no need to abstract the small size parameter.
1531 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
1532 
1533 /// \brief Recursively add the bases of Type.  Don't add Type itself.
1534 static void
1535 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
1536                   const QualType &Type)
1537 {
1538   // Even though the incoming type is a base, it might not be
1539   // a class -- it could be a template parm, for instance.
1540   if (auto Rec = Type->getAs<RecordType>()) {
1541     auto Decl = Rec->getAsCXXRecordDecl();
1542 
1543     // Iterate over its bases.
1544     for (const auto &BaseSpec : Decl->bases()) {
1545       QualType Base = Context.getCanonicalType(BaseSpec.getType())
1546         .getUnqualifiedType();
1547       if (Set.insert(Base).second)
1548         // If we've not already seen it, recurse.
1549         NoteIndirectBases(Context, Set, Base);
1550     }
1551   }
1552 }
1553 
1554 /// \brief Performs the actual work of attaching the given base class
1555 /// specifiers to a C++ class.
1556 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1557                                 unsigned NumBases) {
1558  if (NumBases == 0)
1559     return false;
1560 
1561   // Used to keep track of which base types we have already seen, so
1562   // that we can properly diagnose redundant direct base types. Note
1563   // that the key is always the unqualified canonical type of the base
1564   // class.
1565   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1566 
1567   // Used to track indirect bases so we can see if a direct base is
1568   // ambiguous.
1569   IndirectBaseSet IndirectBaseTypes;
1570 
1571   // Copy non-redundant base specifiers into permanent storage.
1572   unsigned NumGoodBases = 0;
1573   bool Invalid = false;
1574   for (unsigned idx = 0; idx < NumBases; ++idx) {
1575     QualType NewBaseType
1576       = Context.getCanonicalType(Bases[idx]->getType());
1577     NewBaseType = NewBaseType.getLocalUnqualifiedType();
1578 
1579     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1580     if (KnownBase) {
1581       // C++ [class.mi]p3:
1582       //   A class shall not be specified as a direct base class of a
1583       //   derived class more than once.
1584       Diag(Bases[idx]->getLocStart(),
1585            diag::err_duplicate_base_class)
1586         << KnownBase->getType()
1587         << Bases[idx]->getSourceRange();
1588 
1589       // Delete the duplicate base class specifier; we're going to
1590       // overwrite its pointer later.
1591       Context.Deallocate(Bases[idx]);
1592 
1593       Invalid = true;
1594     } else {
1595       // Okay, add this new base class.
1596       KnownBase = Bases[idx];
1597       Bases[NumGoodBases++] = Bases[idx];
1598 
1599       // Note this base's direct & indirect bases, if there could be ambiguity.
1600       if (NumBases > 1)
1601         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
1602 
1603       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1604         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1605         if (Class->isInterface() &&
1606               (!RD->isInterface() ||
1607                KnownBase->getAccessSpecifier() != AS_public)) {
1608           // The Microsoft extension __interface does not permit bases that
1609           // are not themselves public interfaces.
1610           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1611             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1612             << RD->getSourceRange();
1613           Invalid = true;
1614         }
1615         if (RD->hasAttr<WeakAttr>())
1616           Class->addAttr(WeakAttr::CreateImplicit(Context));
1617       }
1618     }
1619   }
1620 
1621   // Attach the remaining base class specifiers to the derived class.
1622   Class->setBases(Bases, NumGoodBases);
1623 
1624   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
1625     // Check whether this direct base is inaccessible due to ambiguity.
1626     QualType BaseType = Bases[idx]->getType();
1627     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
1628       .getUnqualifiedType();
1629 
1630     if (IndirectBaseTypes.count(CanonicalBase)) {
1631       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1632                          /*DetectVirtual=*/true);
1633       bool found
1634         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
1635       assert(found);
1636       (void)found;
1637 
1638       if (Paths.isAmbiguous(CanonicalBase))
1639         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
1640           << BaseType << getAmbiguousPathsDisplayString(Paths)
1641           << Bases[idx]->getSourceRange();
1642       else
1643         assert(Bases[idx]->isVirtual());
1644     }
1645 
1646     // Delete the base class specifier, since its data has been copied
1647     // into the CXXRecordDecl.
1648     Context.Deallocate(Bases[idx]);
1649   }
1650 
1651   return Invalid;
1652 }
1653 
1654 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1655 /// class, after checking whether there are any duplicate base
1656 /// classes.
1657 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1658                                unsigned NumBases) {
1659   if (!ClassDecl || !Bases || !NumBases)
1660     return;
1661 
1662   AdjustDeclIfTemplate(ClassDecl);
1663   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1664 }
1665 
1666 /// \brief Determine whether the type \p Derived is a C++ class that is
1667 /// derived from the type \p Base.
1668 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1669   if (!getLangOpts().CPlusPlus)
1670     return false;
1671 
1672   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1673   if (!DerivedRD)
1674     return false;
1675 
1676   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1677   if (!BaseRD)
1678     return false;
1679 
1680   // If either the base or the derived type is invalid, don't try to
1681   // check whether one is derived from the other.
1682   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1683     return false;
1684 
1685   // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1686   return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1687 }
1688 
1689 /// \brief Determine whether the type \p Derived is a C++ class that is
1690 /// derived from the type \p Base.
1691 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1692   if (!getLangOpts().CPlusPlus)
1693     return false;
1694 
1695   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1696   if (!DerivedRD)
1697     return false;
1698 
1699   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1700   if (!BaseRD)
1701     return false;
1702 
1703   return DerivedRD->isDerivedFrom(BaseRD, Paths);
1704 }
1705 
1706 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1707                               CXXCastPath &BasePathArray) {
1708   assert(BasePathArray.empty() && "Base path array must be empty!");
1709   assert(Paths.isRecordingPaths() && "Must record paths!");
1710 
1711   const CXXBasePath &Path = Paths.front();
1712 
1713   // We first go backward and check if we have a virtual base.
1714   // FIXME: It would be better if CXXBasePath had the base specifier for
1715   // the nearest virtual base.
1716   unsigned Start = 0;
1717   for (unsigned I = Path.size(); I != 0; --I) {
1718     if (Path[I - 1].Base->isVirtual()) {
1719       Start = I - 1;
1720       break;
1721     }
1722   }
1723 
1724   // Now add all bases.
1725   for (unsigned I = Start, E = Path.size(); I != E; ++I)
1726     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1727 }
1728 
1729 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1730 /// conversion (where Derived and Base are class types) is
1731 /// well-formed, meaning that the conversion is unambiguous (and
1732 /// that all of the base classes are accessible). Returns true
1733 /// and emits a diagnostic if the code is ill-formed, returns false
1734 /// otherwise. Loc is the location where this routine should point to
1735 /// if there is an error, and Range is the source range to highlight
1736 /// if there is an error.
1737 bool
1738 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1739                                    unsigned InaccessibleBaseID,
1740                                    unsigned AmbigiousBaseConvID,
1741                                    SourceLocation Loc, SourceRange Range,
1742                                    DeclarationName Name,
1743                                    CXXCastPath *BasePath) {
1744   // First, determine whether the path from Derived to Base is
1745   // ambiguous. This is slightly more expensive than checking whether
1746   // the Derived to Base conversion exists, because here we need to
1747   // explore multiple paths to determine if there is an ambiguity.
1748   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1749                      /*DetectVirtual=*/false);
1750   bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1751   assert(DerivationOkay &&
1752          "Can only be used with a derived-to-base conversion");
1753   (void)DerivationOkay;
1754 
1755   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1756     if (InaccessibleBaseID) {
1757       // Check that the base class can be accessed.
1758       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1759                                    InaccessibleBaseID)) {
1760         case AR_inaccessible:
1761           return true;
1762         case AR_accessible:
1763         case AR_dependent:
1764         case AR_delayed:
1765           break;
1766       }
1767     }
1768 
1769     // Build a base path if necessary.
1770     if (BasePath)
1771       BuildBasePathArray(Paths, *BasePath);
1772     return false;
1773   }
1774 
1775   if (AmbigiousBaseConvID) {
1776     // We know that the derived-to-base conversion is ambiguous, and
1777     // we're going to produce a diagnostic. Perform the derived-to-base
1778     // search just one more time to compute all of the possible paths so
1779     // that we can print them out. This is more expensive than any of
1780     // the previous derived-to-base checks we've done, but at this point
1781     // performance isn't as much of an issue.
1782     Paths.clear();
1783     Paths.setRecordingPaths(true);
1784     bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1785     assert(StillOkay && "Can only be used with a derived-to-base conversion");
1786     (void)StillOkay;
1787 
1788     // Build up a textual representation of the ambiguous paths, e.g.,
1789     // D -> B -> A, that will be used to illustrate the ambiguous
1790     // conversions in the diagnostic. We only print one of the paths
1791     // to each base class subobject.
1792     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1793 
1794     Diag(Loc, AmbigiousBaseConvID)
1795     << Derived << Base << PathDisplayStr << Range << Name;
1796   }
1797   return true;
1798 }
1799 
1800 bool
1801 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1802                                    SourceLocation Loc, SourceRange Range,
1803                                    CXXCastPath *BasePath,
1804                                    bool IgnoreAccess) {
1805   return CheckDerivedToBaseConversion(Derived, Base,
1806                                       IgnoreAccess ? 0
1807                                        : diag::err_upcast_to_inaccessible_base,
1808                                       diag::err_ambiguous_derived_to_base_conv,
1809                                       Loc, Range, DeclarationName(),
1810                                       BasePath);
1811 }
1812 
1813 
1814 /// @brief Builds a string representing ambiguous paths from a
1815 /// specific derived class to different subobjects of the same base
1816 /// class.
1817 ///
1818 /// This function builds a string that can be used in error messages
1819 /// to show the different paths that one can take through the
1820 /// inheritance hierarchy to go from the derived class to different
1821 /// subobjects of a base class. The result looks something like this:
1822 /// @code
1823 /// struct D -> struct B -> struct A
1824 /// struct D -> struct C -> struct A
1825 /// @endcode
1826 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1827   std::string PathDisplayStr;
1828   std::set<unsigned> DisplayedPaths;
1829   for (CXXBasePaths::paths_iterator Path = Paths.begin();
1830        Path != Paths.end(); ++Path) {
1831     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1832       // We haven't displayed a path to this particular base
1833       // class subobject yet.
1834       PathDisplayStr += "\n    ";
1835       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1836       for (CXXBasePath::const_iterator Element = Path->begin();
1837            Element != Path->end(); ++Element)
1838         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1839     }
1840   }
1841 
1842   return PathDisplayStr;
1843 }
1844 
1845 //===----------------------------------------------------------------------===//
1846 // C++ class member Handling
1847 //===----------------------------------------------------------------------===//
1848 
1849 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1850 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1851                                 SourceLocation ASLoc,
1852                                 SourceLocation ColonLoc,
1853                                 AttributeList *Attrs) {
1854   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1855   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1856                                                   ASLoc, ColonLoc);
1857   CurContext->addHiddenDecl(ASDecl);
1858   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1859 }
1860 
1861 /// CheckOverrideControl - Check C++11 override control semantics.
1862 void Sema::CheckOverrideControl(NamedDecl *D) {
1863   if (D->isInvalidDecl())
1864     return;
1865 
1866   // We only care about "override" and "final" declarations.
1867   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1868     return;
1869 
1870   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1871 
1872   // We can't check dependent instance methods.
1873   if (MD && MD->isInstance() &&
1874       (MD->getParent()->hasAnyDependentBases() ||
1875        MD->getType()->isDependentType()))
1876     return;
1877 
1878   if (MD && !MD->isVirtual()) {
1879     // If we have a non-virtual method, check if if hides a virtual method.
1880     // (In that case, it's most likely the method has the wrong type.)
1881     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1882     FindHiddenVirtualMethods(MD, OverloadedMethods);
1883 
1884     if (!OverloadedMethods.empty()) {
1885       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1886         Diag(OA->getLocation(),
1887              diag::override_keyword_hides_virtual_member_function)
1888           << "override" << (OverloadedMethods.size() > 1);
1889       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1890         Diag(FA->getLocation(),
1891              diag::override_keyword_hides_virtual_member_function)
1892           << (FA->isSpelledAsSealed() ? "sealed" : "final")
1893           << (OverloadedMethods.size() > 1);
1894       }
1895       NoteHiddenVirtualMethods(MD, OverloadedMethods);
1896       MD->setInvalidDecl();
1897       return;
1898     }
1899     // Fall through into the general case diagnostic.
1900     // FIXME: We might want to attempt typo correction here.
1901   }
1902 
1903   if (!MD || !MD->isVirtual()) {
1904     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1905       Diag(OA->getLocation(),
1906            diag::override_keyword_only_allowed_on_virtual_member_functions)
1907         << "override" << FixItHint::CreateRemoval(OA->getLocation());
1908       D->dropAttr<OverrideAttr>();
1909     }
1910     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1911       Diag(FA->getLocation(),
1912            diag::override_keyword_only_allowed_on_virtual_member_functions)
1913         << (FA->isSpelledAsSealed() ? "sealed" : "final")
1914         << FixItHint::CreateRemoval(FA->getLocation());
1915       D->dropAttr<FinalAttr>();
1916     }
1917     return;
1918   }
1919 
1920   // C++11 [class.virtual]p5:
1921   //   If a function is marked with the virt-specifier override and
1922   //   does not override a member function of a base class, the program is
1923   //   ill-formed.
1924   bool HasOverriddenMethods =
1925     MD->begin_overridden_methods() != MD->end_overridden_methods();
1926   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1927     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1928       << MD->getDeclName();
1929 }
1930 
1931 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1932   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1933     return;
1934   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1935   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1936       isa<CXXDestructorDecl>(MD))
1937     return;
1938 
1939   SourceLocation Loc = MD->getLocation();
1940   SourceLocation SpellingLoc = Loc;
1941   if (getSourceManager().isMacroArgExpansion(Loc))
1942     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1943   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1944   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1945       return;
1946 
1947   if (MD->size_overridden_methods() > 0) {
1948     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1949       << MD->getDeclName();
1950     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1951     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1952   }
1953 }
1954 
1955 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1956 /// function overrides a virtual member function marked 'final', according to
1957 /// C++11 [class.virtual]p4.
1958 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1959                                                   const CXXMethodDecl *Old) {
1960   FinalAttr *FA = Old->getAttr<FinalAttr>();
1961   if (!FA)
1962     return false;
1963 
1964   Diag(New->getLocation(), diag::err_final_function_overridden)
1965     << New->getDeclName()
1966     << FA->isSpelledAsSealed();
1967   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1968   return true;
1969 }
1970 
1971 static bool InitializationHasSideEffects(const FieldDecl &FD) {
1972   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1973   // FIXME: Destruction of ObjC lifetime types has side-effects.
1974   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1975     return !RD->isCompleteDefinition() ||
1976            !RD->hasTrivialDefaultConstructor() ||
1977            !RD->hasTrivialDestructor();
1978   return false;
1979 }
1980 
1981 static AttributeList *getMSPropertyAttr(AttributeList *list) {
1982   for (AttributeList *it = list; it != nullptr; it = it->getNext())
1983     if (it->isDeclspecPropertyAttribute())
1984       return it;
1985   return nullptr;
1986 }
1987 
1988 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1989 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1990 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1991 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1992 /// present (but parsing it has been deferred).
1993 NamedDecl *
1994 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1995                                MultiTemplateParamsArg TemplateParameterLists,
1996                                Expr *BW, const VirtSpecifiers &VS,
1997                                InClassInitStyle InitStyle) {
1998   const DeclSpec &DS = D.getDeclSpec();
1999   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2000   DeclarationName Name = NameInfo.getName();
2001   SourceLocation Loc = NameInfo.getLoc();
2002 
2003   // For anonymous bitfields, the location should point to the type.
2004   if (Loc.isInvalid())
2005     Loc = D.getLocStart();
2006 
2007   Expr *BitWidth = static_cast<Expr*>(BW);
2008 
2009   assert(isa<CXXRecordDecl>(CurContext));
2010   assert(!DS.isFriendSpecified());
2011 
2012   bool isFunc = D.isDeclarationOfFunction();
2013 
2014   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2015     // The Microsoft extension __interface only permits public member functions
2016     // and prohibits constructors, destructors, operators, non-public member
2017     // functions, static methods and data members.
2018     unsigned InvalidDecl;
2019     bool ShowDeclName = true;
2020     if (!isFunc)
2021       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2022     else if (AS != AS_public)
2023       InvalidDecl = 2;
2024     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2025       InvalidDecl = 3;
2026     else switch (Name.getNameKind()) {
2027       case DeclarationName::CXXConstructorName:
2028         InvalidDecl = 4;
2029         ShowDeclName = false;
2030         break;
2031 
2032       case DeclarationName::CXXDestructorName:
2033         InvalidDecl = 5;
2034         ShowDeclName = false;
2035         break;
2036 
2037       case DeclarationName::CXXOperatorName:
2038       case DeclarationName::CXXConversionFunctionName:
2039         InvalidDecl = 6;
2040         break;
2041 
2042       default:
2043         InvalidDecl = 0;
2044         break;
2045     }
2046 
2047     if (InvalidDecl) {
2048       if (ShowDeclName)
2049         Diag(Loc, diag::err_invalid_member_in_interface)
2050           << (InvalidDecl-1) << Name;
2051       else
2052         Diag(Loc, diag::err_invalid_member_in_interface)
2053           << (InvalidDecl-1) << "";
2054       return nullptr;
2055     }
2056   }
2057 
2058   // C++ 9.2p6: A member shall not be declared to have automatic storage
2059   // duration (auto, register) or with the extern storage-class-specifier.
2060   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2061   // data members and cannot be applied to names declared const or static,
2062   // and cannot be applied to reference members.
2063   switch (DS.getStorageClassSpec()) {
2064   case DeclSpec::SCS_unspecified:
2065   case DeclSpec::SCS_typedef:
2066   case DeclSpec::SCS_static:
2067     break;
2068   case DeclSpec::SCS_mutable:
2069     if (isFunc) {
2070       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2071 
2072       // FIXME: It would be nicer if the keyword was ignored only for this
2073       // declarator. Otherwise we could get follow-up errors.
2074       D.getMutableDeclSpec().ClearStorageClassSpecs();
2075     }
2076     break;
2077   default:
2078     Diag(DS.getStorageClassSpecLoc(),
2079          diag::err_storageclass_invalid_for_member);
2080     D.getMutableDeclSpec().ClearStorageClassSpecs();
2081     break;
2082   }
2083 
2084   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2085                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2086                       !isFunc);
2087 
2088   if (DS.isConstexprSpecified() && isInstField) {
2089     SemaDiagnosticBuilder B =
2090         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2091     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2092     if (InitStyle == ICIS_NoInit) {
2093       B << 0 << 0;
2094       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2095         B << FixItHint::CreateRemoval(ConstexprLoc);
2096       else {
2097         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2098         D.getMutableDeclSpec().ClearConstexprSpec();
2099         const char *PrevSpec;
2100         unsigned DiagID;
2101         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2102             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2103         (void)Failed;
2104         assert(!Failed && "Making a constexpr member const shouldn't fail");
2105       }
2106     } else {
2107       B << 1;
2108       const char *PrevSpec;
2109       unsigned DiagID;
2110       if (D.getMutableDeclSpec().SetStorageClassSpec(
2111           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2112           Context.getPrintingPolicy())) {
2113         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2114                "This is the only DeclSpec that should fail to be applied");
2115         B << 1;
2116       } else {
2117         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2118         isInstField = false;
2119       }
2120     }
2121   }
2122 
2123   NamedDecl *Member;
2124   if (isInstField) {
2125     CXXScopeSpec &SS = D.getCXXScopeSpec();
2126 
2127     // Data members must have identifiers for names.
2128     if (!Name.isIdentifier()) {
2129       Diag(Loc, diag::err_bad_variable_name)
2130         << Name;
2131       return nullptr;
2132     }
2133 
2134     IdentifierInfo *II = Name.getAsIdentifierInfo();
2135 
2136     // Member field could not be with "template" keyword.
2137     // So TemplateParameterLists should be empty in this case.
2138     if (TemplateParameterLists.size()) {
2139       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2140       if (TemplateParams->size()) {
2141         // There is no such thing as a member field template.
2142         Diag(D.getIdentifierLoc(), diag::err_template_member)
2143             << II
2144             << SourceRange(TemplateParams->getTemplateLoc(),
2145                 TemplateParams->getRAngleLoc());
2146       } else {
2147         // There is an extraneous 'template<>' for this member.
2148         Diag(TemplateParams->getTemplateLoc(),
2149             diag::err_template_member_noparams)
2150             << II
2151             << SourceRange(TemplateParams->getTemplateLoc(),
2152                 TemplateParams->getRAngleLoc());
2153       }
2154       return nullptr;
2155     }
2156 
2157     if (SS.isSet() && !SS.isInvalid()) {
2158       // The user provided a superfluous scope specifier inside a class
2159       // definition:
2160       //
2161       // class X {
2162       //   int X::member;
2163       // };
2164       if (DeclContext *DC = computeDeclContext(SS, false))
2165         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2166       else
2167         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2168           << Name << SS.getRange();
2169 
2170       SS.clear();
2171     }
2172 
2173     AttributeList *MSPropertyAttr =
2174       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2175     if (MSPropertyAttr) {
2176       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2177                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2178       if (!Member)
2179         return nullptr;
2180       isInstField = false;
2181     } else {
2182       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2183                                 BitWidth, InitStyle, AS);
2184       assert(Member && "HandleField never returns null");
2185     }
2186   } else {
2187     Member = HandleDeclarator(S, D, TemplateParameterLists);
2188     if (!Member)
2189       return nullptr;
2190 
2191     // Non-instance-fields can't have a bitfield.
2192     if (BitWidth) {
2193       if (Member->isInvalidDecl()) {
2194         // don't emit another diagnostic.
2195       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2196         // C++ 9.6p3: A bit-field shall not be a static member.
2197         // "static member 'A' cannot be a bit-field"
2198         Diag(Loc, diag::err_static_not_bitfield)
2199           << Name << BitWidth->getSourceRange();
2200       } else if (isa<TypedefDecl>(Member)) {
2201         // "typedef member 'x' cannot be a bit-field"
2202         Diag(Loc, diag::err_typedef_not_bitfield)
2203           << Name << BitWidth->getSourceRange();
2204       } else {
2205         // A function typedef ("typedef int f(); f a;").
2206         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2207         Diag(Loc, diag::err_not_integral_type_bitfield)
2208           << Name << cast<ValueDecl>(Member)->getType()
2209           << BitWidth->getSourceRange();
2210       }
2211 
2212       BitWidth = nullptr;
2213       Member->setInvalidDecl();
2214     }
2215 
2216     Member->setAccess(AS);
2217 
2218     // If we have declared a member function template or static data member
2219     // template, set the access of the templated declaration as well.
2220     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2221       FunTmpl->getTemplatedDecl()->setAccess(AS);
2222     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2223       VarTmpl->getTemplatedDecl()->setAccess(AS);
2224   }
2225 
2226   if (VS.isOverrideSpecified())
2227     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
2228   if (VS.isFinalSpecified())
2229     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2230                                             VS.isFinalSpelledSealed()));
2231 
2232   if (VS.getLastLocation().isValid()) {
2233     // Update the end location of a method that has a virt-specifiers.
2234     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2235       MD->setRangeEnd(VS.getLastLocation());
2236   }
2237 
2238   CheckOverrideControl(Member);
2239 
2240   assert((Name || isInstField) && "No identifier for non-field ?");
2241 
2242   if (isInstField) {
2243     FieldDecl *FD = cast<FieldDecl>(Member);
2244     FieldCollector->Add(FD);
2245 
2246     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
2247       // Remember all explicit private FieldDecls that have a name, no side
2248       // effects and are not part of a dependent type declaration.
2249       if (!FD->isImplicit() && FD->getDeclName() &&
2250           FD->getAccess() == AS_private &&
2251           !FD->hasAttr<UnusedAttr>() &&
2252           !FD->getParent()->isDependentContext() &&
2253           !InitializationHasSideEffects(*FD))
2254         UnusedPrivateFields.insert(FD);
2255     }
2256   }
2257 
2258   return Member;
2259 }
2260 
2261 namespace {
2262   class UninitializedFieldVisitor
2263       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2264     Sema &S;
2265     // List of Decls to generate a warning on.  Also remove Decls that become
2266     // initialized.
2267     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2268     // List of base classes of the record.  Classes are removed after their
2269     // initializers.
2270     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
2271     // Vector of decls to be removed from the Decl set prior to visiting the
2272     // nodes.  These Decls may have been initialized in the prior initializer.
2273     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
2274     // If non-null, add a note to the warning pointing back to the constructor.
2275     const CXXConstructorDecl *Constructor;
2276     // Variables to hold state when processing an initializer list.  When
2277     // InitList is true, special case initialization of FieldDecls matching
2278     // InitListFieldDecl.
2279     bool InitList;
2280     FieldDecl *InitListFieldDecl;
2281     llvm::SmallVector<unsigned, 4> InitFieldIndex;
2282 
2283   public:
2284     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2285     UninitializedFieldVisitor(Sema &S,
2286                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
2287                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
2288       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
2289         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
2290 
2291     // Returns true if the use of ME is not an uninitialized use.
2292     bool IsInitListMemberExprInitialized(MemberExpr *ME,
2293                                          bool CheckReferenceOnly) {
2294       llvm::SmallVector<FieldDecl*, 4> Fields;
2295       bool ReferenceField = false;
2296       while (ME) {
2297         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2298         if (!FD)
2299           return false;
2300         Fields.push_back(FD);
2301         if (FD->getType()->isReferenceType())
2302           ReferenceField = true;
2303         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2304       }
2305 
2306       // Binding a reference to an unintialized field is not an
2307       // uninitialized use.
2308       if (CheckReferenceOnly && !ReferenceField)
2309         return true;
2310 
2311       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2312       // Discard the first field since it is the field decl that is being
2313       // initialized.
2314       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2315         UsedFieldIndex.push_back((*I)->getFieldIndex());
2316       }
2317 
2318       for (auto UsedIter = UsedFieldIndex.begin(),
2319                 UsedEnd = UsedFieldIndex.end(),
2320                 OrigIter = InitFieldIndex.begin(),
2321                 OrigEnd = InitFieldIndex.end();
2322            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2323         if (*UsedIter < *OrigIter)
2324           return true;
2325         if (*UsedIter > *OrigIter)
2326           break;
2327       }
2328 
2329       return false;
2330     }
2331 
2332     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2333                           bool AddressOf) {
2334       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2335         return;
2336 
2337       // FieldME is the inner-most MemberExpr that is not an anonymous struct
2338       // or union.
2339       MemberExpr *FieldME = ME;
2340 
2341       bool AllPODFields = FieldME->getType().isPODType(S.Context);
2342 
2343       Expr *Base = ME;
2344       while (MemberExpr *SubME =
2345                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
2346 
2347         if (isa<VarDecl>(SubME->getMemberDecl()))
2348           return;
2349 
2350         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
2351           if (!FD->isAnonymousStructOrUnion())
2352             FieldME = SubME;
2353 
2354         if (!FieldME->getType().isPODType(S.Context))
2355           AllPODFields = false;
2356 
2357         Base = SubME->getBase();
2358       }
2359 
2360       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
2361         return;
2362 
2363       if (AddressOf && AllPODFields)
2364         return;
2365 
2366       ValueDecl* FoundVD = FieldME->getMemberDecl();
2367 
2368       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
2369         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
2370           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
2371         }
2372 
2373         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
2374           QualType T = BaseCast->getType();
2375           if (T->isPointerType() &&
2376               BaseClasses.count(T->getPointeeType())) {
2377             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
2378                 << T->getPointeeType() << FoundVD;
2379           }
2380         }
2381       }
2382 
2383       if (!Decls.count(FoundVD))
2384         return;
2385 
2386       const bool IsReference = FoundVD->getType()->isReferenceType();
2387 
2388       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2389         // Special checking for initializer lists.
2390         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2391           return;
2392         }
2393       } else {
2394         // Prevent double warnings on use of unbounded references.
2395         if (CheckReferenceOnly && !IsReference)
2396           return;
2397       }
2398 
2399       unsigned diag = IsReference
2400           ? diag::warn_reference_field_is_uninit
2401           : diag::warn_field_is_uninit;
2402       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2403       if (Constructor)
2404         S.Diag(Constructor->getLocation(),
2405                diag::note_uninit_in_this_constructor)
2406           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2407 
2408     }
2409 
2410     void HandleValue(Expr *E, bool AddressOf) {
2411       E = E->IgnoreParens();
2412 
2413       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2414         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2415                          AddressOf /*AddressOf*/);
2416         return;
2417       }
2418 
2419       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2420         Visit(CO->getCond());
2421         HandleValue(CO->getTrueExpr(), AddressOf);
2422         HandleValue(CO->getFalseExpr(), AddressOf);
2423         return;
2424       }
2425 
2426       if (BinaryConditionalOperator *BCO =
2427               dyn_cast<BinaryConditionalOperator>(E)) {
2428         Visit(BCO->getCond());
2429         HandleValue(BCO->getFalseExpr(), AddressOf);
2430         return;
2431       }
2432 
2433       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2434         HandleValue(OVE->getSourceExpr(), AddressOf);
2435         return;
2436       }
2437 
2438       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2439         switch (BO->getOpcode()) {
2440         default:
2441           break;
2442         case(BO_PtrMemD):
2443         case(BO_PtrMemI):
2444           HandleValue(BO->getLHS(), AddressOf);
2445           Visit(BO->getRHS());
2446           return;
2447         case(BO_Comma):
2448           Visit(BO->getLHS());
2449           HandleValue(BO->getRHS(), AddressOf);
2450           return;
2451         }
2452       }
2453 
2454       Visit(E);
2455     }
2456 
2457     void CheckInitListExpr(InitListExpr *ILE) {
2458       InitFieldIndex.push_back(0);
2459       for (auto Child : ILE->children()) {
2460         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2461           CheckInitListExpr(SubList);
2462         } else {
2463           Visit(Child);
2464         }
2465         ++InitFieldIndex.back();
2466       }
2467       InitFieldIndex.pop_back();
2468     }
2469 
2470     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2471                           FieldDecl *Field, const Type *BaseClass) {
2472       // Remove Decls that may have been initialized in the previous
2473       // initializer.
2474       for (ValueDecl* VD : DeclsToRemove)
2475         Decls.erase(VD);
2476       DeclsToRemove.clear();
2477 
2478       Constructor = FieldConstructor;
2479       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2480 
2481       if (ILE && Field) {
2482         InitList = true;
2483         InitListFieldDecl = Field;
2484         InitFieldIndex.clear();
2485         CheckInitListExpr(ILE);
2486       } else {
2487         InitList = false;
2488         Visit(E);
2489       }
2490 
2491       if (Field)
2492         Decls.erase(Field);
2493       if (BaseClass)
2494         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
2495     }
2496 
2497     void VisitMemberExpr(MemberExpr *ME) {
2498       // All uses of unbounded reference fields will warn.
2499       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
2500     }
2501 
2502     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2503       if (E->getCastKind() == CK_LValueToRValue) {
2504         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2505         return;
2506       }
2507 
2508       Inherited::VisitImplicitCastExpr(E);
2509     }
2510 
2511     void VisitCXXConstructExpr(CXXConstructExpr *E) {
2512       if (E->getConstructor()->isCopyConstructor()) {
2513         Expr *ArgExpr = E->getArg(0);
2514         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2515           if (ILE->getNumInits() == 1)
2516             ArgExpr = ILE->getInit(0);
2517         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
2518           if (ICE->getCastKind() == CK_NoOp)
2519             ArgExpr = ICE->getSubExpr();
2520         HandleValue(ArgExpr, false /*AddressOf*/);
2521         return;
2522       }
2523       Inherited::VisitCXXConstructExpr(E);
2524     }
2525 
2526     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2527       Expr *Callee = E->getCallee();
2528       if (isa<MemberExpr>(Callee)) {
2529         HandleValue(Callee, false /*AddressOf*/);
2530         for (auto Arg : E->arguments())
2531           Visit(Arg);
2532         return;
2533       }
2534 
2535       Inherited::VisitCXXMemberCallExpr(E);
2536     }
2537 
2538     void VisitCallExpr(CallExpr *E) {
2539       // Treat std::move as a use.
2540       if (E->getNumArgs() == 1) {
2541         if (FunctionDecl *FD = E->getDirectCallee()) {
2542           if (FD->isInStdNamespace() && FD->getIdentifier() &&
2543               FD->getIdentifier()->isStr("move")) {
2544             HandleValue(E->getArg(0), false /*AddressOf*/);
2545             return;
2546           }
2547         }
2548       }
2549 
2550       Inherited::VisitCallExpr(E);
2551     }
2552 
2553     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2554       Expr *Callee = E->getCallee();
2555 
2556       if (isa<UnresolvedLookupExpr>(Callee))
2557         return Inherited::VisitCXXOperatorCallExpr(E);
2558 
2559       Visit(Callee);
2560       for (auto Arg : E->arguments())
2561         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2562     }
2563 
2564     void VisitBinaryOperator(BinaryOperator *E) {
2565       // If a field assignment is detected, remove the field from the
2566       // uninitiailized field set.
2567       if (E->getOpcode() == BO_Assign)
2568         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2569           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2570             if (!FD->getType()->isReferenceType())
2571               DeclsToRemove.push_back(FD);
2572 
2573       if (E->isCompoundAssignmentOp()) {
2574         HandleValue(E->getLHS(), false /*AddressOf*/);
2575         Visit(E->getRHS());
2576         return;
2577       }
2578 
2579       Inherited::VisitBinaryOperator(E);
2580     }
2581 
2582     void VisitUnaryOperator(UnaryOperator *E) {
2583       if (E->isIncrementDecrementOp()) {
2584         HandleValue(E->getSubExpr(), false /*AddressOf*/);
2585         return;
2586       }
2587       if (E->getOpcode() == UO_AddrOf) {
2588         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2589           HandleValue(ME->getBase(), true /*AddressOf*/);
2590           return;
2591         }
2592       }
2593 
2594       Inherited::VisitUnaryOperator(E);
2595     }
2596   };
2597 
2598   // Diagnose value-uses of fields to initialize themselves, e.g.
2599   //   foo(foo)
2600   // where foo is not also a parameter to the constructor.
2601   // Also diagnose across field uninitialized use such as
2602   //   x(y), y(x)
2603   // TODO: implement -Wuninitialized and fold this into that framework.
2604   static void DiagnoseUninitializedFields(
2605       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2606 
2607     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2608                                            Constructor->getLocation())) {
2609       return;
2610     }
2611 
2612     if (Constructor->isInvalidDecl())
2613       return;
2614 
2615     const CXXRecordDecl *RD = Constructor->getParent();
2616 
2617     if (RD->getDescribedClassTemplate())
2618       return;
2619 
2620     // Holds fields that are uninitialized.
2621     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2622 
2623     // At the beginning, all fields are uninitialized.
2624     for (auto *I : RD->decls()) {
2625       if (auto *FD = dyn_cast<FieldDecl>(I)) {
2626         UninitializedFields.insert(FD);
2627       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
2628         UninitializedFields.insert(IFD->getAnonField());
2629       }
2630     }
2631 
2632     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
2633     for (auto I : RD->bases())
2634       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
2635 
2636     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2637       return;
2638 
2639     UninitializedFieldVisitor UninitializedChecker(SemaRef,
2640                                                    UninitializedFields,
2641                                                    UninitializedBaseClasses);
2642 
2643     for (const auto *FieldInit : Constructor->inits()) {
2644       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
2645         break;
2646 
2647       Expr *InitExpr = FieldInit->getInit();
2648       if (!InitExpr)
2649         continue;
2650 
2651       if (CXXDefaultInitExpr *Default =
2652               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2653         InitExpr = Default->getExpr();
2654         if (!InitExpr)
2655           continue;
2656         // In class initializers will point to the constructor.
2657         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2658                                               FieldInit->getAnyMember(),
2659                                               FieldInit->getBaseClass());
2660       } else {
2661         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2662                                               FieldInit->getAnyMember(),
2663                                               FieldInit->getBaseClass());
2664       }
2665     }
2666   }
2667 } // namespace
2668 
2669 /// \brief Enter a new C++ default initializer scope. After calling this, the
2670 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2671 /// parsing or instantiating the initializer failed.
2672 void Sema::ActOnStartCXXInClassMemberInitializer() {
2673   // Create a synthetic function scope to represent the call to the constructor
2674   // that notionally surrounds a use of this initializer.
2675   PushFunctionScope();
2676 }
2677 
2678 /// \brief This is invoked after parsing an in-class initializer for a
2679 /// non-static C++ class member, and after instantiating an in-class initializer
2680 /// in a class template. Such actions are deferred until the class is complete.
2681 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2682                                                   SourceLocation InitLoc,
2683                                                   Expr *InitExpr) {
2684   // Pop the notional constructor scope we created earlier.
2685   PopFunctionScopeInfo(nullptr, D);
2686 
2687   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2688   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
2689          "must set init style when field is created");
2690 
2691   if (!InitExpr) {
2692     D->setInvalidDecl();
2693     if (FD)
2694       FD->removeInClassInitializer();
2695     return;
2696   }
2697 
2698   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2699     FD->setInvalidDecl();
2700     FD->removeInClassInitializer();
2701     return;
2702   }
2703 
2704   ExprResult Init = InitExpr;
2705   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2706     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2707     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2708         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2709         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2710     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2711     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2712     if (Init.isInvalid()) {
2713       FD->setInvalidDecl();
2714       return;
2715     }
2716   }
2717 
2718   // C++11 [class.base.init]p7:
2719   //   The initialization of each base and member constitutes a
2720   //   full-expression.
2721   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
2722   if (Init.isInvalid()) {
2723     FD->setInvalidDecl();
2724     return;
2725   }
2726 
2727   InitExpr = Init.get();
2728 
2729   FD->setInClassInitializer(InitExpr);
2730 }
2731 
2732 /// \brief Find the direct and/or virtual base specifiers that
2733 /// correspond to the given base type, for use in base initialization
2734 /// within a constructor.
2735 static bool FindBaseInitializer(Sema &SemaRef,
2736                                 CXXRecordDecl *ClassDecl,
2737                                 QualType BaseType,
2738                                 const CXXBaseSpecifier *&DirectBaseSpec,
2739                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
2740   // First, check for a direct base class.
2741   DirectBaseSpec = nullptr;
2742   for (const auto &Base : ClassDecl->bases()) {
2743     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
2744       // We found a direct base of this type. That's what we're
2745       // initializing.
2746       DirectBaseSpec = &Base;
2747       break;
2748     }
2749   }
2750 
2751   // Check for a virtual base class.
2752   // FIXME: We might be able to short-circuit this if we know in advance that
2753   // there are no virtual bases.
2754   VirtualBaseSpec = nullptr;
2755   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2756     // We haven't found a base yet; search the class hierarchy for a
2757     // virtual base class.
2758     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2759                        /*DetectVirtual=*/false);
2760     if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2761                               BaseType, Paths)) {
2762       for (CXXBasePaths::paths_iterator Path = Paths.begin();
2763            Path != Paths.end(); ++Path) {
2764         if (Path->back().Base->isVirtual()) {
2765           VirtualBaseSpec = Path->back().Base;
2766           break;
2767         }
2768       }
2769     }
2770   }
2771 
2772   return DirectBaseSpec || VirtualBaseSpec;
2773 }
2774 
2775 /// \brief Handle a C++ member initializer using braced-init-list syntax.
2776 MemInitResult
2777 Sema::ActOnMemInitializer(Decl *ConstructorD,
2778                           Scope *S,
2779                           CXXScopeSpec &SS,
2780                           IdentifierInfo *MemberOrBase,
2781                           ParsedType TemplateTypeTy,
2782                           const DeclSpec &DS,
2783                           SourceLocation IdLoc,
2784                           Expr *InitList,
2785                           SourceLocation EllipsisLoc) {
2786   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2787                              DS, IdLoc, InitList,
2788                              EllipsisLoc);
2789 }
2790 
2791 /// \brief Handle a C++ member initializer using parentheses syntax.
2792 MemInitResult
2793 Sema::ActOnMemInitializer(Decl *ConstructorD,
2794                           Scope *S,
2795                           CXXScopeSpec &SS,
2796                           IdentifierInfo *MemberOrBase,
2797                           ParsedType TemplateTypeTy,
2798                           const DeclSpec &DS,
2799                           SourceLocation IdLoc,
2800                           SourceLocation LParenLoc,
2801                           ArrayRef<Expr *> Args,
2802                           SourceLocation RParenLoc,
2803                           SourceLocation EllipsisLoc) {
2804   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2805                                            Args, RParenLoc);
2806   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2807                              DS, IdLoc, List, EllipsisLoc);
2808 }
2809 
2810 namespace {
2811 
2812 // Callback to only accept typo corrections that can be a valid C++ member
2813 // intializer: either a non-static field member or a base class.
2814 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2815 public:
2816   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2817       : ClassDecl(ClassDecl) {}
2818 
2819   bool ValidateCandidate(const TypoCorrection &candidate) override {
2820     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2821       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2822         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2823       return isa<TypeDecl>(ND);
2824     }
2825     return false;
2826   }
2827 
2828 private:
2829   CXXRecordDecl *ClassDecl;
2830 };
2831 
2832 }
2833 
2834 /// \brief Handle a C++ member initializer.
2835 MemInitResult
2836 Sema::BuildMemInitializer(Decl *ConstructorD,
2837                           Scope *S,
2838                           CXXScopeSpec &SS,
2839                           IdentifierInfo *MemberOrBase,
2840                           ParsedType TemplateTypeTy,
2841                           const DeclSpec &DS,
2842                           SourceLocation IdLoc,
2843                           Expr *Init,
2844                           SourceLocation EllipsisLoc) {
2845   ExprResult Res = CorrectDelayedTyposInExpr(Init);
2846   if (!Res.isUsable())
2847     return true;
2848   Init = Res.get();
2849 
2850   if (!ConstructorD)
2851     return true;
2852 
2853   AdjustDeclIfTemplate(ConstructorD);
2854 
2855   CXXConstructorDecl *Constructor
2856     = dyn_cast<CXXConstructorDecl>(ConstructorD);
2857   if (!Constructor) {
2858     // The user wrote a constructor initializer on a function that is
2859     // not a C++ constructor. Ignore the error for now, because we may
2860     // have more member initializers coming; we'll diagnose it just
2861     // once in ActOnMemInitializers.
2862     return true;
2863   }
2864 
2865   CXXRecordDecl *ClassDecl = Constructor->getParent();
2866 
2867   // C++ [class.base.init]p2:
2868   //   Names in a mem-initializer-id are looked up in the scope of the
2869   //   constructor's class and, if not found in that scope, are looked
2870   //   up in the scope containing the constructor's definition.
2871   //   [Note: if the constructor's class contains a member with the
2872   //   same name as a direct or virtual base class of the class, a
2873   //   mem-initializer-id naming the member or base class and composed
2874   //   of a single identifier refers to the class member. A
2875   //   mem-initializer-id for the hidden base class may be specified
2876   //   using a qualified name. ]
2877   if (!SS.getScopeRep() && !TemplateTypeTy) {
2878     // Look for a member, first.
2879     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
2880     if (!Result.empty()) {
2881       ValueDecl *Member;
2882       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2883           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2884         if (EllipsisLoc.isValid())
2885           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2886             << MemberOrBase
2887             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2888 
2889         return BuildMemberInitializer(Member, Init, IdLoc);
2890       }
2891     }
2892   }
2893   // It didn't name a member, so see if it names a class.
2894   QualType BaseType;
2895   TypeSourceInfo *TInfo = nullptr;
2896 
2897   if (TemplateTypeTy) {
2898     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2899   } else if (DS.getTypeSpecType() == TST_decltype) {
2900     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2901   } else {
2902     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2903     LookupParsedName(R, S, &SS);
2904 
2905     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2906     if (!TyD) {
2907       if (R.isAmbiguous()) return true;
2908 
2909       // We don't want access-control diagnostics here.
2910       R.suppressDiagnostics();
2911 
2912       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2913         bool NotUnknownSpecialization = false;
2914         DeclContext *DC = computeDeclContext(SS, false);
2915         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2916           NotUnknownSpecialization = !Record->hasAnyDependentBases();
2917 
2918         if (!NotUnknownSpecialization) {
2919           // When the scope specifier can refer to a member of an unknown
2920           // specialization, we take it as a type name.
2921           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2922                                        SS.getWithLocInContext(Context),
2923                                        *MemberOrBase, IdLoc);
2924           if (BaseType.isNull())
2925             return true;
2926 
2927           R.clear();
2928           R.setLookupName(MemberOrBase);
2929         }
2930       }
2931 
2932       // If no results were found, try to correct typos.
2933       TypoCorrection Corr;
2934       if (R.empty() && BaseType.isNull() &&
2935           (Corr = CorrectTypo(
2936                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2937                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2938                CTK_ErrorRecovery, ClassDecl))) {
2939         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2940           // We have found a non-static data member with a similar
2941           // name to what was typed; complain and initialize that
2942           // member.
2943           diagnoseTypo(Corr,
2944                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
2945                          << MemberOrBase << true);
2946           return BuildMemberInitializer(Member, Init, IdLoc);
2947         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2948           const CXXBaseSpecifier *DirectBaseSpec;
2949           const CXXBaseSpecifier *VirtualBaseSpec;
2950           if (FindBaseInitializer(*this, ClassDecl,
2951                                   Context.getTypeDeclType(Type),
2952                                   DirectBaseSpec, VirtualBaseSpec)) {
2953             // We have found a direct or virtual base class with a
2954             // similar name to what was typed; complain and initialize
2955             // that base class.
2956             diagnoseTypo(Corr,
2957                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
2958                            << MemberOrBase << false,
2959                          PDiag() /*Suppress note, we provide our own.*/);
2960 
2961             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2962                                                               : VirtualBaseSpec;
2963             Diag(BaseSpec->getLocStart(),
2964                  diag::note_base_class_specified_here)
2965               << BaseSpec->getType()
2966               << BaseSpec->getSourceRange();
2967 
2968             TyD = Type;
2969           }
2970         }
2971       }
2972 
2973       if (!TyD && BaseType.isNull()) {
2974         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2975           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2976         return true;
2977       }
2978     }
2979 
2980     if (BaseType.isNull()) {
2981       BaseType = Context.getTypeDeclType(TyD);
2982       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
2983       if (SS.isSet())
2984         // FIXME: preserve source range information
2985         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2986                                              BaseType);
2987     }
2988   }
2989 
2990   if (!TInfo)
2991     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2992 
2993   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2994 }
2995 
2996 /// Checks a member initializer expression for cases where reference (or
2997 /// pointer) members are bound to by-value parameters (or their addresses).
2998 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2999                                                Expr *Init,
3000                                                SourceLocation IdLoc) {
3001   QualType MemberTy = Member->getType();
3002 
3003   // We only handle pointers and references currently.
3004   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3005   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3006     return;
3007 
3008   const bool IsPointer = MemberTy->isPointerType();
3009   if (IsPointer) {
3010     if (const UnaryOperator *Op
3011           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3012       // The only case we're worried about with pointers requires taking the
3013       // address.
3014       if (Op->getOpcode() != UO_AddrOf)
3015         return;
3016 
3017       Init = Op->getSubExpr();
3018     } else {
3019       // We only handle address-of expression initializers for pointers.
3020       return;
3021     }
3022   }
3023 
3024   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3025     // We only warn when referring to a non-reference parameter declaration.
3026     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3027     if (!Parameter || Parameter->getType()->isReferenceType())
3028       return;
3029 
3030     S.Diag(Init->getExprLoc(),
3031            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3032                      : diag::warn_bind_ref_member_to_parameter)
3033       << Member << Parameter << Init->getSourceRange();
3034   } else {
3035     // Other initializers are fine.
3036     return;
3037   }
3038 
3039   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3040     << (unsigned)IsPointer;
3041 }
3042 
3043 MemInitResult
3044 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3045                              SourceLocation IdLoc) {
3046   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3047   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3048   assert((DirectMember || IndirectMember) &&
3049          "Member must be a FieldDecl or IndirectFieldDecl");
3050 
3051   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3052     return true;
3053 
3054   if (Member->isInvalidDecl())
3055     return true;
3056 
3057   MultiExprArg Args;
3058   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3059     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3060   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3061     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3062   } else {
3063     // Template instantiation doesn't reconstruct ParenListExprs for us.
3064     Args = Init;
3065   }
3066 
3067   SourceRange InitRange = Init->getSourceRange();
3068 
3069   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3070     // Can't check initialization for a member of dependent type or when
3071     // any of the arguments are type-dependent expressions.
3072     DiscardCleanupsInEvaluationContext();
3073   } else {
3074     bool InitList = false;
3075     if (isa<InitListExpr>(Init)) {
3076       InitList = true;
3077       Args = Init;
3078     }
3079 
3080     // Initialize the member.
3081     InitializedEntity MemberEntity =
3082       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3083                    : InitializedEntity::InitializeMember(IndirectMember,
3084                                                          nullptr);
3085     InitializationKind Kind =
3086       InitList ? InitializationKind::CreateDirectList(IdLoc)
3087                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3088                                                   InitRange.getEnd());
3089 
3090     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3091     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3092                                             nullptr);
3093     if (MemberInit.isInvalid())
3094       return true;
3095 
3096     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3097 
3098     // C++11 [class.base.init]p7:
3099     //   The initialization of each base and member constitutes a
3100     //   full-expression.
3101     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3102     if (MemberInit.isInvalid())
3103       return true;
3104 
3105     Init = MemberInit.get();
3106   }
3107 
3108   if (DirectMember) {
3109     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3110                                             InitRange.getBegin(), Init,
3111                                             InitRange.getEnd());
3112   } else {
3113     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3114                                             InitRange.getBegin(), Init,
3115                                             InitRange.getEnd());
3116   }
3117 }
3118 
3119 MemInitResult
3120 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3121                                  CXXRecordDecl *ClassDecl) {
3122   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3123   if (!LangOpts.CPlusPlus11)
3124     return Diag(NameLoc, diag::err_delegating_ctor)
3125       << TInfo->getTypeLoc().getLocalSourceRange();
3126   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3127 
3128   bool InitList = true;
3129   MultiExprArg Args = Init;
3130   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3131     InitList = false;
3132     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3133   }
3134 
3135   SourceRange InitRange = Init->getSourceRange();
3136   // Initialize the object.
3137   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3138                                      QualType(ClassDecl->getTypeForDecl(), 0));
3139   InitializationKind Kind =
3140     InitList ? InitializationKind::CreateDirectList(NameLoc)
3141              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3142                                                 InitRange.getEnd());
3143   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3144   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3145                                               Args, nullptr);
3146   if (DelegationInit.isInvalid())
3147     return true;
3148 
3149   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3150          "Delegating constructor with no target?");
3151 
3152   // C++11 [class.base.init]p7:
3153   //   The initialization of each base and member constitutes a
3154   //   full-expression.
3155   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3156                                        InitRange.getBegin());
3157   if (DelegationInit.isInvalid())
3158     return true;
3159 
3160   // If we are in a dependent context, template instantiation will
3161   // perform this type-checking again. Just save the arguments that we
3162   // received in a ParenListExpr.
3163   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3164   // of the information that we have about the base
3165   // initializer. However, deconstructing the ASTs is a dicey process,
3166   // and this approach is far more likely to get the corner cases right.
3167   if (CurContext->isDependentContext())
3168     DelegationInit = Init;
3169 
3170   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3171                                           DelegationInit.getAs<Expr>(),
3172                                           InitRange.getEnd());
3173 }
3174 
3175 MemInitResult
3176 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3177                            Expr *Init, CXXRecordDecl *ClassDecl,
3178                            SourceLocation EllipsisLoc) {
3179   SourceLocation BaseLoc
3180     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3181 
3182   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3183     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3184              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3185 
3186   // C++ [class.base.init]p2:
3187   //   [...] Unless the mem-initializer-id names a nonstatic data
3188   //   member of the constructor's class or a direct or virtual base
3189   //   of that class, the mem-initializer is ill-formed. A
3190   //   mem-initializer-list can initialize a base class using any
3191   //   name that denotes that base class type.
3192   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3193 
3194   SourceRange InitRange = Init->getSourceRange();
3195   if (EllipsisLoc.isValid()) {
3196     // This is a pack expansion.
3197     if (!BaseType->containsUnexpandedParameterPack())  {
3198       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3199         << SourceRange(BaseLoc, InitRange.getEnd());
3200 
3201       EllipsisLoc = SourceLocation();
3202     }
3203   } else {
3204     // Check for any unexpanded parameter packs.
3205     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3206       return true;
3207 
3208     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3209       return true;
3210   }
3211 
3212   // Check for direct and virtual base classes.
3213   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3214   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3215   if (!Dependent) {
3216     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3217                                        BaseType))
3218       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3219 
3220     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3221                         VirtualBaseSpec);
3222 
3223     // C++ [base.class.init]p2:
3224     // Unless the mem-initializer-id names a nonstatic data member of the
3225     // constructor's class or a direct or virtual base of that class, the
3226     // mem-initializer is ill-formed.
3227     if (!DirectBaseSpec && !VirtualBaseSpec) {
3228       // If the class has any dependent bases, then it's possible that
3229       // one of those types will resolve to the same type as
3230       // BaseType. Therefore, just treat this as a dependent base
3231       // class initialization.  FIXME: Should we try to check the
3232       // initialization anyway? It seems odd.
3233       if (ClassDecl->hasAnyDependentBases())
3234         Dependent = true;
3235       else
3236         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3237           << BaseType << Context.getTypeDeclType(ClassDecl)
3238           << BaseTInfo->getTypeLoc().getLocalSourceRange();
3239     }
3240   }
3241 
3242   if (Dependent) {
3243     DiscardCleanupsInEvaluationContext();
3244 
3245     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3246                                             /*IsVirtual=*/false,
3247                                             InitRange.getBegin(), Init,
3248                                             InitRange.getEnd(), EllipsisLoc);
3249   }
3250 
3251   // C++ [base.class.init]p2:
3252   //   If a mem-initializer-id is ambiguous because it designates both
3253   //   a direct non-virtual base class and an inherited virtual base
3254   //   class, the mem-initializer is ill-formed.
3255   if (DirectBaseSpec && VirtualBaseSpec)
3256     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
3257       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3258 
3259   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
3260   if (!BaseSpec)
3261     BaseSpec = VirtualBaseSpec;
3262 
3263   // Initialize the base.
3264   bool InitList = true;
3265   MultiExprArg Args = Init;
3266   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3267     InitList = false;
3268     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3269   }
3270 
3271   InitializedEntity BaseEntity =
3272     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3273   InitializationKind Kind =
3274     InitList ? InitializationKind::CreateDirectList(BaseLoc)
3275              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3276                                                 InitRange.getEnd());
3277   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
3278   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
3279   if (BaseInit.isInvalid())
3280     return true;
3281 
3282   // C++11 [class.base.init]p7:
3283   //   The initialization of each base and member constitutes a
3284   //   full-expression.
3285   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
3286   if (BaseInit.isInvalid())
3287     return true;
3288 
3289   // If we are in a dependent context, template instantiation will
3290   // perform this type-checking again. Just save the arguments that we
3291   // received in a ParenListExpr.
3292   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3293   // of the information that we have about the base
3294   // initializer. However, deconstructing the ASTs is a dicey process,
3295   // and this approach is far more likely to get the corner cases right.
3296   if (CurContext->isDependentContext())
3297     BaseInit = Init;
3298 
3299   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3300                                           BaseSpec->isVirtual(),
3301                                           InitRange.getBegin(),
3302                                           BaseInit.getAs<Expr>(),
3303                                           InitRange.getEnd(), EllipsisLoc);
3304 }
3305 
3306 // Create a static_cast\<T&&>(expr).
3307 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3308   if (T.isNull()) T = E->getType();
3309   QualType TargetType = SemaRef.BuildReferenceType(
3310       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
3311   SourceLocation ExprLoc = E->getLocStart();
3312   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3313       TargetType, ExprLoc);
3314 
3315   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3316                                    SourceRange(ExprLoc, ExprLoc),
3317                                    E->getSourceRange()).get();
3318 }
3319 
3320 /// ImplicitInitializerKind - How an implicit base or member initializer should
3321 /// initialize its base or member.
3322 enum ImplicitInitializerKind {
3323   IIK_Default,
3324   IIK_Copy,
3325   IIK_Move,
3326   IIK_Inherit
3327 };
3328 
3329 static bool
3330 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3331                              ImplicitInitializerKind ImplicitInitKind,
3332                              CXXBaseSpecifier *BaseSpec,
3333                              bool IsInheritedVirtualBase,
3334                              CXXCtorInitializer *&CXXBaseInit) {
3335   InitializedEntity InitEntity
3336     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3337                                         IsInheritedVirtualBase);
3338 
3339   ExprResult BaseInit;
3340 
3341   switch (ImplicitInitKind) {
3342   case IIK_Inherit: {
3343     const CXXRecordDecl *Inherited =
3344         Constructor->getInheritedConstructor()->getParent();
3345     const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3346     if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3347       // C++11 [class.inhctor]p8:
3348       //   Each expression in the expression-list is of the form
3349       //   static_cast<T&&>(p), where p is the name of the corresponding
3350       //   constructor parameter and T is the declared type of p.
3351       SmallVector<Expr*, 16> Args;
3352       for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3353         ParmVarDecl *PD = Constructor->getParamDecl(I);
3354         ExprResult ArgExpr =
3355             SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3356                                      VK_LValue, SourceLocation());
3357         if (ArgExpr.isInvalid())
3358           return true;
3359         Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
3360       }
3361 
3362       InitializationKind InitKind = InitializationKind::CreateDirect(
3363           Constructor->getLocation(), SourceLocation(), SourceLocation());
3364       InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3365       BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3366       break;
3367     }
3368   }
3369   // Fall through.
3370   case IIK_Default: {
3371     InitializationKind InitKind
3372       = InitializationKind::CreateDefault(Constructor->getLocation());
3373     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3374     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3375     break;
3376   }
3377 
3378   case IIK_Move:
3379   case IIK_Copy: {
3380     bool Moving = ImplicitInitKind == IIK_Move;
3381     ParmVarDecl *Param = Constructor->getParamDecl(0);
3382     QualType ParamType = Param->getType().getNonReferenceType();
3383 
3384     Expr *CopyCtorArg =
3385       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3386                           SourceLocation(), Param, false,
3387                           Constructor->getLocation(), ParamType,
3388                           VK_LValue, nullptr);
3389 
3390     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3391 
3392     // Cast to the base class to avoid ambiguities.
3393     QualType ArgTy =
3394       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3395                                        ParamType.getQualifiers());
3396 
3397     if (Moving) {
3398       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3399     }
3400 
3401     CXXCastPath BasePath;
3402     BasePath.push_back(BaseSpec);
3403     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3404                                             CK_UncheckedDerivedToBase,
3405                                             Moving ? VK_XValue : VK_LValue,
3406                                             &BasePath).get();
3407 
3408     InitializationKind InitKind
3409       = InitializationKind::CreateDirect(Constructor->getLocation(),
3410                                          SourceLocation(), SourceLocation());
3411     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3412     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3413     break;
3414   }
3415   }
3416 
3417   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3418   if (BaseInit.isInvalid())
3419     return true;
3420 
3421   CXXBaseInit =
3422     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3423                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3424                                                         SourceLocation()),
3425                                              BaseSpec->isVirtual(),
3426                                              SourceLocation(),
3427                                              BaseInit.getAs<Expr>(),
3428                                              SourceLocation(),
3429                                              SourceLocation());
3430 
3431   return false;
3432 }
3433 
3434 static bool RefersToRValueRef(Expr *MemRef) {
3435   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3436   return Referenced->getType()->isRValueReferenceType();
3437 }
3438 
3439 static bool
3440 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3441                                ImplicitInitializerKind ImplicitInitKind,
3442                                FieldDecl *Field, IndirectFieldDecl *Indirect,
3443                                CXXCtorInitializer *&CXXMemberInit) {
3444   if (Field->isInvalidDecl())
3445     return true;
3446 
3447   SourceLocation Loc = Constructor->getLocation();
3448 
3449   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3450     bool Moving = ImplicitInitKind == IIK_Move;
3451     ParmVarDecl *Param = Constructor->getParamDecl(0);
3452     QualType ParamType = Param->getType().getNonReferenceType();
3453 
3454     // Suppress copying zero-width bitfields.
3455     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3456       return false;
3457 
3458     Expr *MemberExprBase =
3459       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3460                           SourceLocation(), Param, false,
3461                           Loc, ParamType, VK_LValue, nullptr);
3462 
3463     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3464 
3465     if (Moving) {
3466       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3467     }
3468 
3469     // Build a reference to this field within the parameter.
3470     CXXScopeSpec SS;
3471     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3472                               Sema::LookupMemberName);
3473     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3474                                   : cast<ValueDecl>(Field), AS_public);
3475     MemberLookup.resolveKind();
3476     ExprResult CtorArg
3477       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3478                                          ParamType, Loc,
3479                                          /*IsArrow=*/false,
3480                                          SS,
3481                                          /*TemplateKWLoc=*/SourceLocation(),
3482                                          /*FirstQualifierInScope=*/nullptr,
3483                                          MemberLookup,
3484                                          /*TemplateArgs=*/nullptr);
3485     if (CtorArg.isInvalid())
3486       return true;
3487 
3488     // C++11 [class.copy]p15:
3489     //   - if a member m has rvalue reference type T&&, it is direct-initialized
3490     //     with static_cast<T&&>(x.m);
3491     if (RefersToRValueRef(CtorArg.get())) {
3492       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3493     }
3494 
3495     // When the field we are copying is an array, create index variables for
3496     // each dimension of the array. We use these index variables to subscript
3497     // the source array, and other clients (e.g., CodeGen) will perform the
3498     // necessary iteration with these index variables.
3499     SmallVector<VarDecl *, 4> IndexVariables;
3500     QualType BaseType = Field->getType();
3501     QualType SizeType = SemaRef.Context.getSizeType();
3502     bool InitializingArray = false;
3503     while (const ConstantArrayType *Array
3504                           = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3505       InitializingArray = true;
3506       // Create the iteration variable for this array index.
3507       IdentifierInfo *IterationVarName = nullptr;
3508       {
3509         SmallString<8> Str;
3510         llvm::raw_svector_ostream OS(Str);
3511         OS << "__i" << IndexVariables.size();
3512         IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3513       }
3514       VarDecl *IterationVar
3515         = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3516                           IterationVarName, SizeType,
3517                         SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3518                           SC_None);
3519       IndexVariables.push_back(IterationVar);
3520 
3521       // Create a reference to the iteration variable.
3522       ExprResult IterationVarRef
3523         = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3524       assert(!IterationVarRef.isInvalid() &&
3525              "Reference to invented variable cannot fail!");
3526       IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
3527       assert(!IterationVarRef.isInvalid() &&
3528              "Conversion of invented variable cannot fail!");
3529 
3530       // Subscript the array with this iteration variable.
3531       CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3532                                                         IterationVarRef.get(),
3533                                                         Loc);
3534       if (CtorArg.isInvalid())
3535         return true;
3536 
3537       BaseType = Array->getElementType();
3538     }
3539 
3540     // The array subscript expression is an lvalue, which is wrong for moving.
3541     if (Moving && InitializingArray)
3542       CtorArg = CastForMoving(SemaRef, CtorArg.get());
3543 
3544     // Construct the entity that we will be initializing. For an array, this
3545     // will be first element in the array, which may require several levels
3546     // of array-subscript entities.
3547     SmallVector<InitializedEntity, 4> Entities;
3548     Entities.reserve(1 + IndexVariables.size());
3549     if (Indirect)
3550       Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3551     else
3552       Entities.push_back(InitializedEntity::InitializeMember(Field));
3553     for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3554       Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3555                                                               0,
3556                                                               Entities.back()));
3557 
3558     // Direct-initialize to use the copy constructor.
3559     InitializationKind InitKind =
3560       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3561 
3562     Expr *CtorArgE = CtorArg.getAs<Expr>();
3563     InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
3564                                    CtorArgE);
3565 
3566     ExprResult MemberInit
3567       = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3568                         MultiExprArg(&CtorArgE, 1));
3569     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3570     if (MemberInit.isInvalid())
3571       return true;
3572 
3573     if (Indirect) {
3574       assert(IndexVariables.size() == 0 &&
3575              "Indirect field improperly initialized");
3576       CXXMemberInit
3577         = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3578                                                    Loc, Loc,
3579                                                    MemberInit.getAs<Expr>(),
3580                                                    Loc);
3581     } else
3582       CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3583                                                  Loc, MemberInit.getAs<Expr>(),
3584                                                  Loc,
3585                                                  IndexVariables.data(),
3586                                                  IndexVariables.size());
3587     return false;
3588   }
3589 
3590   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3591          "Unhandled implicit init kind!");
3592 
3593   QualType FieldBaseElementType =
3594     SemaRef.Context.getBaseElementType(Field->getType());
3595 
3596   if (FieldBaseElementType->isRecordType()) {
3597     InitializedEntity InitEntity
3598       = Indirect? InitializedEntity::InitializeMember(Indirect)
3599                 : InitializedEntity::InitializeMember(Field);
3600     InitializationKind InitKind =
3601       InitializationKind::CreateDefault(Loc);
3602 
3603     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3604     ExprResult MemberInit =
3605       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3606 
3607     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3608     if (MemberInit.isInvalid())
3609       return true;
3610 
3611     if (Indirect)
3612       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3613                                                                Indirect, Loc,
3614                                                                Loc,
3615                                                                MemberInit.get(),
3616                                                                Loc);
3617     else
3618       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3619                                                                Field, Loc, Loc,
3620                                                                MemberInit.get(),
3621                                                                Loc);
3622     return false;
3623   }
3624 
3625   if (!Field->getParent()->isUnion()) {
3626     if (FieldBaseElementType->isReferenceType()) {
3627       SemaRef.Diag(Constructor->getLocation(),
3628                    diag::err_uninitialized_member_in_ctor)
3629       << (int)Constructor->isImplicit()
3630       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3631       << 0 << Field->getDeclName();
3632       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3633       return true;
3634     }
3635 
3636     if (FieldBaseElementType.isConstQualified()) {
3637       SemaRef.Diag(Constructor->getLocation(),
3638                    diag::err_uninitialized_member_in_ctor)
3639       << (int)Constructor->isImplicit()
3640       << SemaRef.Context.getTagDeclType(Constructor->getParent())
3641       << 1 << Field->getDeclName();
3642       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3643       return true;
3644     }
3645   }
3646 
3647   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3648       FieldBaseElementType->isObjCRetainableType() &&
3649       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3650       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3651     // ARC:
3652     //   Default-initialize Objective-C pointers to NULL.
3653     CXXMemberInit
3654       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3655                                                  Loc, Loc,
3656                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3657                                                  Loc);
3658     return false;
3659   }
3660 
3661   // Nothing to initialize.
3662   CXXMemberInit = nullptr;
3663   return false;
3664 }
3665 
3666 namespace {
3667 struct BaseAndFieldInfo {
3668   Sema &S;
3669   CXXConstructorDecl *Ctor;
3670   bool AnyErrorsInInits;
3671   ImplicitInitializerKind IIK;
3672   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3673   SmallVector<CXXCtorInitializer*, 8> AllToInit;
3674   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
3675 
3676   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3677     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3678     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3679     if (Generated && Ctor->isCopyConstructor())
3680       IIK = IIK_Copy;
3681     else if (Generated && Ctor->isMoveConstructor())
3682       IIK = IIK_Move;
3683     else if (Ctor->getInheritedConstructor())
3684       IIK = IIK_Inherit;
3685     else
3686       IIK = IIK_Default;
3687   }
3688 
3689   bool isImplicitCopyOrMove() const {
3690     switch (IIK) {
3691     case IIK_Copy:
3692     case IIK_Move:
3693       return true;
3694 
3695     case IIK_Default:
3696     case IIK_Inherit:
3697       return false;
3698     }
3699 
3700     llvm_unreachable("Invalid ImplicitInitializerKind!");
3701   }
3702 
3703   bool addFieldInitializer(CXXCtorInitializer *Init) {
3704     AllToInit.push_back(Init);
3705 
3706     // Check whether this initializer makes the field "used".
3707     if (Init->getInit()->HasSideEffects(S.Context))
3708       S.UnusedPrivateFields.remove(Init->getAnyMember());
3709 
3710     return false;
3711   }
3712 
3713   bool isInactiveUnionMember(FieldDecl *Field) {
3714     RecordDecl *Record = Field->getParent();
3715     if (!Record->isUnion())
3716       return false;
3717 
3718     if (FieldDecl *Active =
3719             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3720       return Active != Field->getCanonicalDecl();
3721 
3722     // In an implicit copy or move constructor, ignore any in-class initializer.
3723     if (isImplicitCopyOrMove())
3724       return true;
3725 
3726     // If there's no explicit initialization, the field is active only if it
3727     // has an in-class initializer...
3728     if (Field->hasInClassInitializer())
3729       return false;
3730     // ... or it's an anonymous struct or union whose class has an in-class
3731     // initializer.
3732     if (!Field->isAnonymousStructOrUnion())
3733       return true;
3734     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3735     return !FieldRD->hasInClassInitializer();
3736   }
3737 
3738   /// \brief Determine whether the given field is, or is within, a union member
3739   /// that is inactive (because there was an initializer given for a different
3740   /// member of the union, or because the union was not initialized at all).
3741   bool isWithinInactiveUnionMember(FieldDecl *Field,
3742                                    IndirectFieldDecl *Indirect) {
3743     if (!Indirect)
3744       return isInactiveUnionMember(Field);
3745 
3746     for (auto *C : Indirect->chain()) {
3747       FieldDecl *Field = dyn_cast<FieldDecl>(C);
3748       if (Field && isInactiveUnionMember(Field))
3749         return true;
3750     }
3751     return false;
3752   }
3753 };
3754 }
3755 
3756 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
3757 /// array type.
3758 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3759   if (T->isIncompleteArrayType())
3760     return true;
3761 
3762   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3763     if (!ArrayT->getSize())
3764       return true;
3765 
3766     T = ArrayT->getElementType();
3767   }
3768 
3769   return false;
3770 }
3771 
3772 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3773                                     FieldDecl *Field,
3774                                     IndirectFieldDecl *Indirect = nullptr) {
3775   if (Field->isInvalidDecl())
3776     return false;
3777 
3778   // Overwhelmingly common case: we have a direct initializer for this field.
3779   if (CXXCtorInitializer *Init =
3780           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
3781     return Info.addFieldInitializer(Init);
3782 
3783   // C++11 [class.base.init]p8:
3784   //   if the entity is a non-static data member that has a
3785   //   brace-or-equal-initializer and either
3786   //   -- the constructor's class is a union and no other variant member of that
3787   //      union is designated by a mem-initializer-id or
3788   //   -- the constructor's class is not a union, and, if the entity is a member
3789   //      of an anonymous union, no other member of that union is designated by
3790   //      a mem-initializer-id,
3791   //   the entity is initialized as specified in [dcl.init].
3792   //
3793   // We also apply the same rules to handle anonymous structs within anonymous
3794   // unions.
3795   if (Info.isWithinInactiveUnionMember(Field, Indirect))
3796     return false;
3797 
3798   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3799     ExprResult DIE =
3800         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3801     if (DIE.isInvalid())
3802       return true;
3803     CXXCtorInitializer *Init;
3804     if (Indirect)
3805       Init = new (SemaRef.Context)
3806           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3807                              SourceLocation(), DIE.get(), SourceLocation());
3808     else
3809       Init = new (SemaRef.Context)
3810           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3811                              SourceLocation(), DIE.get(), SourceLocation());
3812     return Info.addFieldInitializer(Init);
3813   }
3814 
3815   // Don't initialize incomplete or zero-length arrays.
3816   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3817     return false;
3818 
3819   // Don't try to build an implicit initializer if there were semantic
3820   // errors in any of the initializers (and therefore we might be
3821   // missing some that the user actually wrote).
3822   if (Info.AnyErrorsInInits)
3823     return false;
3824 
3825   CXXCtorInitializer *Init = nullptr;
3826   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3827                                      Indirect, Init))
3828     return true;
3829 
3830   if (!Init)
3831     return false;
3832 
3833   return Info.addFieldInitializer(Init);
3834 }
3835 
3836 bool
3837 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3838                                CXXCtorInitializer *Initializer) {
3839   assert(Initializer->isDelegatingInitializer());
3840   Constructor->setNumCtorInitializers(1);
3841   CXXCtorInitializer **initializer =
3842     new (Context) CXXCtorInitializer*[1];
3843   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3844   Constructor->setCtorInitializers(initializer);
3845 
3846   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3847     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3848     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3849   }
3850 
3851   DelegatingCtorDecls.push_back(Constructor);
3852 
3853   DiagnoseUninitializedFields(*this, Constructor);
3854 
3855   return false;
3856 }
3857 
3858 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3859                                ArrayRef<CXXCtorInitializer *> Initializers) {
3860   if (Constructor->isDependentContext()) {
3861     // Just store the initializers as written, they will be checked during
3862     // instantiation.
3863     if (!Initializers.empty()) {
3864       Constructor->setNumCtorInitializers(Initializers.size());
3865       CXXCtorInitializer **baseOrMemberInitializers =
3866         new (Context) CXXCtorInitializer*[Initializers.size()];
3867       memcpy(baseOrMemberInitializers, Initializers.data(),
3868              Initializers.size() * sizeof(CXXCtorInitializer*));
3869       Constructor->setCtorInitializers(baseOrMemberInitializers);
3870     }
3871 
3872     // Let template instantiation know whether we had errors.
3873     if (AnyErrors)
3874       Constructor->setInvalidDecl();
3875 
3876     return false;
3877   }
3878 
3879   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3880 
3881   // We need to build the initializer AST according to order of construction
3882   // and not what user specified in the Initializers list.
3883   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3884   if (!ClassDecl)
3885     return true;
3886 
3887   bool HadError = false;
3888 
3889   for (unsigned i = 0; i < Initializers.size(); i++) {
3890     CXXCtorInitializer *Member = Initializers[i];
3891 
3892     if (Member->isBaseInitializer())
3893       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3894     else {
3895       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
3896 
3897       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3898         for (auto *C : F->chain()) {
3899           FieldDecl *FD = dyn_cast<FieldDecl>(C);
3900           if (FD && FD->getParent()->isUnion())
3901             Info.ActiveUnionMember.insert(std::make_pair(
3902                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3903         }
3904       } else if (FieldDecl *FD = Member->getMember()) {
3905         if (FD->getParent()->isUnion())
3906           Info.ActiveUnionMember.insert(std::make_pair(
3907               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3908       }
3909     }
3910   }
3911 
3912   // Keep track of the direct virtual bases.
3913   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3914   for (auto &I : ClassDecl->bases()) {
3915     if (I.isVirtual())
3916       DirectVBases.insert(&I);
3917   }
3918 
3919   // Push virtual bases before others.
3920   for (auto &VBase : ClassDecl->vbases()) {
3921     if (CXXCtorInitializer *Value
3922         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
3923       // [class.base.init]p7, per DR257:
3924       //   A mem-initializer where the mem-initializer-id names a virtual base
3925       //   class is ignored during execution of a constructor of any class that
3926       //   is not the most derived class.
3927       if (ClassDecl->isAbstract()) {
3928         // FIXME: Provide a fixit to remove the base specifier. This requires
3929         // tracking the location of the associated comma for a base specifier.
3930         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3931           << VBase.getType() << ClassDecl;
3932         DiagnoseAbstractType(ClassDecl);
3933       }
3934 
3935       Info.AllToInit.push_back(Value);
3936     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3937       // [class.base.init]p8, per DR257:
3938       //   If a given [...] base class is not named by a mem-initializer-id
3939       //   [...] and the entity is not a virtual base class of an abstract
3940       //   class, then [...] the entity is default-initialized.
3941       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
3942       CXXCtorInitializer *CXXBaseInit;
3943       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3944                                        &VBase, IsInheritedVirtualBase,
3945                                        CXXBaseInit)) {
3946         HadError = true;
3947         continue;
3948       }
3949 
3950       Info.AllToInit.push_back(CXXBaseInit);
3951     }
3952   }
3953 
3954   // Non-virtual bases.
3955   for (auto &Base : ClassDecl->bases()) {
3956     // Virtuals are in the virtual base list and already constructed.
3957     if (Base.isVirtual())
3958       continue;
3959 
3960     if (CXXCtorInitializer *Value
3961           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
3962       Info.AllToInit.push_back(Value);
3963     } else if (!AnyErrors) {
3964       CXXCtorInitializer *CXXBaseInit;
3965       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3966                                        &Base, /*IsInheritedVirtualBase=*/false,
3967                                        CXXBaseInit)) {
3968         HadError = true;
3969         continue;
3970       }
3971 
3972       Info.AllToInit.push_back(CXXBaseInit);
3973     }
3974   }
3975 
3976   // Fields.
3977   for (auto *Mem : ClassDecl->decls()) {
3978     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
3979       // C++ [class.bit]p2:
3980       //   A declaration for a bit-field that omits the identifier declares an
3981       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3982       //   initialized.
3983       if (F->isUnnamedBitfield())
3984         continue;
3985 
3986       // If we're not generating the implicit copy/move constructor, then we'll
3987       // handle anonymous struct/union fields based on their individual
3988       // indirect fields.
3989       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3990         continue;
3991 
3992       if (CollectFieldInitializer(*this, Info, F))
3993         HadError = true;
3994       continue;
3995     }
3996 
3997     // Beyond this point, we only consider default initialization.
3998     if (Info.isImplicitCopyOrMove())
3999       continue;
4000 
4001     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4002       if (F->getType()->isIncompleteArrayType()) {
4003         assert(ClassDecl->hasFlexibleArrayMember() &&
4004                "Incomplete array type is not valid");
4005         continue;
4006       }
4007 
4008       // Initialize each field of an anonymous struct individually.
4009       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4010         HadError = true;
4011 
4012       continue;
4013     }
4014   }
4015 
4016   unsigned NumInitializers = Info.AllToInit.size();
4017   if (NumInitializers > 0) {
4018     Constructor->setNumCtorInitializers(NumInitializers);
4019     CXXCtorInitializer **baseOrMemberInitializers =
4020       new (Context) CXXCtorInitializer*[NumInitializers];
4021     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4022            NumInitializers * sizeof(CXXCtorInitializer*));
4023     Constructor->setCtorInitializers(baseOrMemberInitializers);
4024 
4025     // Constructors implicitly reference the base and member
4026     // destructors.
4027     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4028                                            Constructor->getParent());
4029   }
4030 
4031   return HadError;
4032 }
4033 
4034 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4035   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4036     const RecordDecl *RD = RT->getDecl();
4037     if (RD->isAnonymousStructOrUnion()) {
4038       for (auto *Field : RD->fields())
4039         PopulateKeysForFields(Field, IdealInits);
4040       return;
4041     }
4042   }
4043   IdealInits.push_back(Field->getCanonicalDecl());
4044 }
4045 
4046 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4047   return Context.getCanonicalType(BaseType).getTypePtr();
4048 }
4049 
4050 static const void *GetKeyForMember(ASTContext &Context,
4051                                    CXXCtorInitializer *Member) {
4052   if (!Member->isAnyMemberInitializer())
4053     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4054 
4055   return Member->getAnyMember()->getCanonicalDecl();
4056 }
4057 
4058 static void DiagnoseBaseOrMemInitializerOrder(
4059     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4060     ArrayRef<CXXCtorInitializer *> Inits) {
4061   if (Constructor->getDeclContext()->isDependentContext())
4062     return;
4063 
4064   // Don't check initializers order unless the warning is enabled at the
4065   // location of at least one initializer.
4066   bool ShouldCheckOrder = false;
4067   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4068     CXXCtorInitializer *Init = Inits[InitIndex];
4069     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4070                                  Init->getSourceLocation())) {
4071       ShouldCheckOrder = true;
4072       break;
4073     }
4074   }
4075   if (!ShouldCheckOrder)
4076     return;
4077 
4078   // Build the list of bases and members in the order that they'll
4079   // actually be initialized.  The explicit initializers should be in
4080   // this same order but may be missing things.
4081   SmallVector<const void*, 32> IdealInitKeys;
4082 
4083   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4084 
4085   // 1. Virtual bases.
4086   for (const auto &VBase : ClassDecl->vbases())
4087     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4088 
4089   // 2. Non-virtual bases.
4090   for (const auto &Base : ClassDecl->bases()) {
4091     if (Base.isVirtual())
4092       continue;
4093     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4094   }
4095 
4096   // 3. Direct fields.
4097   for (auto *Field : ClassDecl->fields()) {
4098     if (Field->isUnnamedBitfield())
4099       continue;
4100 
4101     PopulateKeysForFields(Field, IdealInitKeys);
4102   }
4103 
4104   unsigned NumIdealInits = IdealInitKeys.size();
4105   unsigned IdealIndex = 0;
4106 
4107   CXXCtorInitializer *PrevInit = nullptr;
4108   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4109     CXXCtorInitializer *Init = Inits[InitIndex];
4110     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4111 
4112     // Scan forward to try to find this initializer in the idealized
4113     // initializers list.
4114     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4115       if (InitKey == IdealInitKeys[IdealIndex])
4116         break;
4117 
4118     // If we didn't find this initializer, it must be because we
4119     // scanned past it on a previous iteration.  That can only
4120     // happen if we're out of order;  emit a warning.
4121     if (IdealIndex == NumIdealInits && PrevInit) {
4122       Sema::SemaDiagnosticBuilder D =
4123         SemaRef.Diag(PrevInit->getSourceLocation(),
4124                      diag::warn_initializer_out_of_order);
4125 
4126       if (PrevInit->isAnyMemberInitializer())
4127         D << 0 << PrevInit->getAnyMember()->getDeclName();
4128       else
4129         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4130 
4131       if (Init->isAnyMemberInitializer())
4132         D << 0 << Init->getAnyMember()->getDeclName();
4133       else
4134         D << 1 << Init->getTypeSourceInfo()->getType();
4135 
4136       // Move back to the initializer's location in the ideal list.
4137       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4138         if (InitKey == IdealInitKeys[IdealIndex])
4139           break;
4140 
4141       assert(IdealIndex < NumIdealInits &&
4142              "initializer not found in initializer list");
4143     }
4144 
4145     PrevInit = Init;
4146   }
4147 }
4148 
4149 namespace {
4150 bool CheckRedundantInit(Sema &S,
4151                         CXXCtorInitializer *Init,
4152                         CXXCtorInitializer *&PrevInit) {
4153   if (!PrevInit) {
4154     PrevInit = Init;
4155     return false;
4156   }
4157 
4158   if (FieldDecl *Field = Init->getAnyMember())
4159     S.Diag(Init->getSourceLocation(),
4160            diag::err_multiple_mem_initialization)
4161       << Field->getDeclName()
4162       << Init->getSourceRange();
4163   else {
4164     const Type *BaseClass = Init->getBaseClass();
4165     assert(BaseClass && "neither field nor base");
4166     S.Diag(Init->getSourceLocation(),
4167            diag::err_multiple_base_initialization)
4168       << QualType(BaseClass, 0)
4169       << Init->getSourceRange();
4170   }
4171   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4172     << 0 << PrevInit->getSourceRange();
4173 
4174   return true;
4175 }
4176 
4177 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4178 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4179 
4180 bool CheckRedundantUnionInit(Sema &S,
4181                              CXXCtorInitializer *Init,
4182                              RedundantUnionMap &Unions) {
4183   FieldDecl *Field = Init->getAnyMember();
4184   RecordDecl *Parent = Field->getParent();
4185   NamedDecl *Child = Field;
4186 
4187   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4188     if (Parent->isUnion()) {
4189       UnionEntry &En = Unions[Parent];
4190       if (En.first && En.first != Child) {
4191         S.Diag(Init->getSourceLocation(),
4192                diag::err_multiple_mem_union_initialization)
4193           << Field->getDeclName()
4194           << Init->getSourceRange();
4195         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4196           << 0 << En.second->getSourceRange();
4197         return true;
4198       }
4199       if (!En.first) {
4200         En.first = Child;
4201         En.second = Init;
4202       }
4203       if (!Parent->isAnonymousStructOrUnion())
4204         return false;
4205     }
4206 
4207     Child = Parent;
4208     Parent = cast<RecordDecl>(Parent->getDeclContext());
4209   }
4210 
4211   return false;
4212 }
4213 }
4214 
4215 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4216 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4217                                 SourceLocation ColonLoc,
4218                                 ArrayRef<CXXCtorInitializer*> MemInits,
4219                                 bool AnyErrors) {
4220   if (!ConstructorDecl)
4221     return;
4222 
4223   AdjustDeclIfTemplate(ConstructorDecl);
4224 
4225   CXXConstructorDecl *Constructor
4226     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4227 
4228   if (!Constructor) {
4229     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4230     return;
4231   }
4232 
4233   // Mapping for the duplicate initializers check.
4234   // For member initializers, this is keyed with a FieldDecl*.
4235   // For base initializers, this is keyed with a Type*.
4236   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4237 
4238   // Mapping for the inconsistent anonymous-union initializers check.
4239   RedundantUnionMap MemberUnions;
4240 
4241   bool HadError = false;
4242   for (unsigned i = 0; i < MemInits.size(); i++) {
4243     CXXCtorInitializer *Init = MemInits[i];
4244 
4245     // Set the source order index.
4246     Init->setSourceOrder(i);
4247 
4248     if (Init->isAnyMemberInitializer()) {
4249       const void *Key = GetKeyForMember(Context, Init);
4250       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4251           CheckRedundantUnionInit(*this, Init, MemberUnions))
4252         HadError = true;
4253     } else if (Init->isBaseInitializer()) {
4254       const void *Key = GetKeyForMember(Context, Init);
4255       if (CheckRedundantInit(*this, Init, Members[Key]))
4256         HadError = true;
4257     } else {
4258       assert(Init->isDelegatingInitializer());
4259       // This must be the only initializer
4260       if (MemInits.size() != 1) {
4261         Diag(Init->getSourceLocation(),
4262              diag::err_delegating_initializer_alone)
4263           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4264         // We will treat this as being the only initializer.
4265       }
4266       SetDelegatingInitializer(Constructor, MemInits[i]);
4267       // Return immediately as the initializer is set.
4268       return;
4269     }
4270   }
4271 
4272   if (HadError)
4273     return;
4274 
4275   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4276 
4277   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4278 
4279   DiagnoseUninitializedFields(*this, Constructor);
4280 }
4281 
4282 void
4283 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4284                                              CXXRecordDecl *ClassDecl) {
4285   // Ignore dependent contexts. Also ignore unions, since their members never
4286   // have destructors implicitly called.
4287   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4288     return;
4289 
4290   // FIXME: all the access-control diagnostics are positioned on the
4291   // field/base declaration.  That's probably good; that said, the
4292   // user might reasonably want to know why the destructor is being
4293   // emitted, and we currently don't say.
4294 
4295   // Non-static data members.
4296   for (auto *Field : ClassDecl->fields()) {
4297     if (Field->isInvalidDecl())
4298       continue;
4299 
4300     // Don't destroy incomplete or zero-length arrays.
4301     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4302       continue;
4303 
4304     QualType FieldType = Context.getBaseElementType(Field->getType());
4305 
4306     const RecordType* RT = FieldType->getAs<RecordType>();
4307     if (!RT)
4308       continue;
4309 
4310     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4311     if (FieldClassDecl->isInvalidDecl())
4312       continue;
4313     if (FieldClassDecl->hasIrrelevantDestructor())
4314       continue;
4315     // The destructor for an implicit anonymous union member is never invoked.
4316     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4317       continue;
4318 
4319     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
4320     assert(Dtor && "No dtor found for FieldClassDecl!");
4321     CheckDestructorAccess(Field->getLocation(), Dtor,
4322                           PDiag(diag::err_access_dtor_field)
4323                             << Field->getDeclName()
4324                             << FieldType);
4325 
4326     MarkFunctionReferenced(Location, Dtor);
4327     DiagnoseUseOfDecl(Dtor, Location);
4328   }
4329 
4330   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4331 
4332   // Bases.
4333   for (const auto &Base : ClassDecl->bases()) {
4334     // Bases are always records in a well-formed non-dependent class.
4335     const RecordType *RT = Base.getType()->getAs<RecordType>();
4336 
4337     // Remember direct virtual bases.
4338     if (Base.isVirtual())
4339       DirectVirtualBases.insert(RT);
4340 
4341     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4342     // If our base class is invalid, we probably can't get its dtor anyway.
4343     if (BaseClassDecl->isInvalidDecl())
4344       continue;
4345     if (BaseClassDecl->hasIrrelevantDestructor())
4346       continue;
4347 
4348     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4349     assert(Dtor && "No dtor found for BaseClassDecl!");
4350 
4351     // FIXME: caret should be on the start of the class name
4352     CheckDestructorAccess(Base.getLocStart(), Dtor,
4353                           PDiag(diag::err_access_dtor_base)
4354                             << Base.getType()
4355                             << Base.getSourceRange(),
4356                           Context.getTypeDeclType(ClassDecl));
4357 
4358     MarkFunctionReferenced(Location, Dtor);
4359     DiagnoseUseOfDecl(Dtor, Location);
4360   }
4361 
4362   // Virtual bases.
4363   for (const auto &VBase : ClassDecl->vbases()) {
4364     // Bases are always records in a well-formed non-dependent class.
4365     const RecordType *RT = VBase.getType()->castAs<RecordType>();
4366 
4367     // Ignore direct virtual bases.
4368     if (DirectVirtualBases.count(RT))
4369       continue;
4370 
4371     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4372     // If our base class is invalid, we probably can't get its dtor anyway.
4373     if (BaseClassDecl->isInvalidDecl())
4374       continue;
4375     if (BaseClassDecl->hasIrrelevantDestructor())
4376       continue;
4377 
4378     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
4379     assert(Dtor && "No dtor found for BaseClassDecl!");
4380     if (CheckDestructorAccess(
4381             ClassDecl->getLocation(), Dtor,
4382             PDiag(diag::err_access_dtor_vbase)
4383                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
4384             Context.getTypeDeclType(ClassDecl)) ==
4385         AR_accessible) {
4386       CheckDerivedToBaseConversion(
4387           Context.getTypeDeclType(ClassDecl), VBase.getType(),
4388           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4389           SourceRange(), DeclarationName(), nullptr);
4390     }
4391 
4392     MarkFunctionReferenced(Location, Dtor);
4393     DiagnoseUseOfDecl(Dtor, Location);
4394   }
4395 }
4396 
4397 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4398   if (!CDtorDecl)
4399     return;
4400 
4401   if (CXXConstructorDecl *Constructor
4402       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4403     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4404     DiagnoseUninitializedFields(*this, Constructor);
4405   }
4406 }
4407 
4408 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4409                                   unsigned DiagID, AbstractDiagSelID SelID) {
4410   class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4411     unsigned DiagID;
4412     AbstractDiagSelID SelID;
4413 
4414   public:
4415     NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4416       : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4417 
4418     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
4419       if (Suppressed) return;
4420       if (SelID == -1)
4421         S.Diag(Loc, DiagID) << T;
4422       else
4423         S.Diag(Loc, DiagID) << SelID << T;
4424     }
4425   } Diagnoser(DiagID, SelID);
4426 
4427   return RequireNonAbstractType(Loc, T, Diagnoser);
4428 }
4429 
4430 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4431                                   TypeDiagnoser &Diagnoser) {
4432   if (!getLangOpts().CPlusPlus)
4433     return false;
4434 
4435   if (const ArrayType *AT = Context.getAsArrayType(T))
4436     return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4437 
4438   if (const PointerType *PT = T->getAs<PointerType>()) {
4439     // Find the innermost pointer type.
4440     while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4441       PT = T;
4442 
4443     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4444       return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4445   }
4446 
4447   const RecordType *RT = T->getAs<RecordType>();
4448   if (!RT)
4449     return false;
4450 
4451   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4452 
4453   // We can't answer whether something is abstract until it has a
4454   // definition.  If it's currently being defined, we'll walk back
4455   // over all the declarations when we have a full definition.
4456   const CXXRecordDecl *Def = RD->getDefinition();
4457   if (!Def || Def->isBeingDefined())
4458     return false;
4459 
4460   if (!RD->isAbstract())
4461     return false;
4462 
4463   Diagnoser.diagnose(*this, Loc, T);
4464   DiagnoseAbstractType(RD);
4465 
4466   return true;
4467 }
4468 
4469 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4470   // Check if we've already emitted the list of pure virtual functions
4471   // for this class.
4472   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4473     return;
4474 
4475   // If the diagnostic is suppressed, don't emit the notes. We're only
4476   // going to emit them once, so try to attach them to a diagnostic we're
4477   // actually going to show.
4478   if (Diags.isLastDiagnosticIgnored())
4479     return;
4480 
4481   CXXFinalOverriderMap FinalOverriders;
4482   RD->getFinalOverriders(FinalOverriders);
4483 
4484   // Keep a set of seen pure methods so we won't diagnose the same method
4485   // more than once.
4486   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4487 
4488   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4489                                    MEnd = FinalOverriders.end();
4490        M != MEnd;
4491        ++M) {
4492     for (OverridingMethods::iterator SO = M->second.begin(),
4493                                   SOEnd = M->second.end();
4494          SO != SOEnd; ++SO) {
4495       // C++ [class.abstract]p4:
4496       //   A class is abstract if it contains or inherits at least one
4497       //   pure virtual function for which the final overrider is pure
4498       //   virtual.
4499 
4500       //
4501       if (SO->second.size() != 1)
4502         continue;
4503 
4504       if (!SO->second.front().Method->isPure())
4505         continue;
4506 
4507       if (!SeenPureMethods.insert(SO->second.front().Method).second)
4508         continue;
4509 
4510       Diag(SO->second.front().Method->getLocation(),
4511            diag::note_pure_virtual_function)
4512         << SO->second.front().Method->getDeclName() << RD->getDeclName();
4513     }
4514   }
4515 
4516   if (!PureVirtualClassDiagSet)
4517     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4518   PureVirtualClassDiagSet->insert(RD);
4519 }
4520 
4521 namespace {
4522 struct AbstractUsageInfo {
4523   Sema &S;
4524   CXXRecordDecl *Record;
4525   CanQualType AbstractType;
4526   bool Invalid;
4527 
4528   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4529     : S(S), Record(Record),
4530       AbstractType(S.Context.getCanonicalType(
4531                    S.Context.getTypeDeclType(Record))),
4532       Invalid(false) {}
4533 
4534   void DiagnoseAbstractType() {
4535     if (Invalid) return;
4536     S.DiagnoseAbstractType(Record);
4537     Invalid = true;
4538   }
4539 
4540   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4541 };
4542 
4543 struct CheckAbstractUsage {
4544   AbstractUsageInfo &Info;
4545   const NamedDecl *Ctx;
4546 
4547   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4548     : Info(Info), Ctx(Ctx) {}
4549 
4550   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4551     switch (TL.getTypeLocClass()) {
4552 #define ABSTRACT_TYPELOC(CLASS, PARENT)
4553 #define TYPELOC(CLASS, PARENT) \
4554     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4555 #include "clang/AST/TypeLocNodes.def"
4556     }
4557   }
4558 
4559   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4560     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4561     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4562       if (!TL.getParam(I))
4563         continue;
4564 
4565       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
4566       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4567     }
4568   }
4569 
4570   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4571     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4572   }
4573 
4574   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4575     // Visit the type parameters from a permissive context.
4576     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4577       TemplateArgumentLoc TAL = TL.getArgLoc(I);
4578       if (TAL.getArgument().getKind() == TemplateArgument::Type)
4579         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4580           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4581       // TODO: other template argument types?
4582     }
4583   }
4584 
4585   // Visit pointee types from a permissive context.
4586 #define CheckPolymorphic(Type) \
4587   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4588     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4589   }
4590   CheckPolymorphic(PointerTypeLoc)
4591   CheckPolymorphic(ReferenceTypeLoc)
4592   CheckPolymorphic(MemberPointerTypeLoc)
4593   CheckPolymorphic(BlockPointerTypeLoc)
4594   CheckPolymorphic(AtomicTypeLoc)
4595 
4596   /// Handle all the types we haven't given a more specific
4597   /// implementation for above.
4598   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4599     // Every other kind of type that we haven't called out already
4600     // that has an inner type is either (1) sugar or (2) contains that
4601     // inner type in some way as a subobject.
4602     if (TypeLoc Next = TL.getNextTypeLoc())
4603       return Visit(Next, Sel);
4604 
4605     // If there's no inner type and we're in a permissive context,
4606     // don't diagnose.
4607     if (Sel == Sema::AbstractNone) return;
4608 
4609     // Check whether the type matches the abstract type.
4610     QualType T = TL.getType();
4611     if (T->isArrayType()) {
4612       Sel = Sema::AbstractArrayType;
4613       T = Info.S.Context.getBaseElementType(T);
4614     }
4615     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4616     if (CT != Info.AbstractType) return;
4617 
4618     // It matched; do some magic.
4619     if (Sel == Sema::AbstractArrayType) {
4620       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4621         << T << TL.getSourceRange();
4622     } else {
4623       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4624         << Sel << T << TL.getSourceRange();
4625     }
4626     Info.DiagnoseAbstractType();
4627   }
4628 };
4629 
4630 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4631                                   Sema::AbstractDiagSelID Sel) {
4632   CheckAbstractUsage(*this, D).Visit(TL, Sel);
4633 }
4634 
4635 }
4636 
4637 /// Check for invalid uses of an abstract type in a method declaration.
4638 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4639                                     CXXMethodDecl *MD) {
4640   // No need to do the check on definitions, which require that
4641   // the return/param types be complete.
4642   if (MD->doesThisDeclarationHaveABody())
4643     return;
4644 
4645   // For safety's sake, just ignore it if we don't have type source
4646   // information.  This should never happen for non-implicit methods,
4647   // but...
4648   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4649     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4650 }
4651 
4652 /// Check for invalid uses of an abstract type within a class definition.
4653 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4654                                     CXXRecordDecl *RD) {
4655   for (auto *D : RD->decls()) {
4656     if (D->isImplicit()) continue;
4657 
4658     // Methods and method templates.
4659     if (isa<CXXMethodDecl>(D)) {
4660       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4661     } else if (isa<FunctionTemplateDecl>(D)) {
4662       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4663       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4664 
4665     // Fields and static variables.
4666     } else if (isa<FieldDecl>(D)) {
4667       FieldDecl *FD = cast<FieldDecl>(D);
4668       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4669         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4670     } else if (isa<VarDecl>(D)) {
4671       VarDecl *VD = cast<VarDecl>(D);
4672       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4673         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4674 
4675     // Nested classes and class templates.
4676     } else if (isa<CXXRecordDecl>(D)) {
4677       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4678     } else if (isa<ClassTemplateDecl>(D)) {
4679       CheckAbstractClassUsage(Info,
4680                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4681     }
4682   }
4683 }
4684 
4685 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
4686   Attr *ClassAttr = getDLLAttr(Class);
4687   if (!ClassAttr)
4688     return;
4689 
4690   assert(ClassAttr->getKind() == attr::DLLExport);
4691 
4692   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4693 
4694   if (TSK == TSK_ExplicitInstantiationDeclaration)
4695     // Don't go any further if this is just an explicit instantiation
4696     // declaration.
4697     return;
4698 
4699   for (Decl *Member : Class->decls()) {
4700     auto *MD = dyn_cast<CXXMethodDecl>(Member);
4701     if (!MD)
4702       continue;
4703 
4704     if (Member->getAttr<DLLExportAttr>()) {
4705       if (MD->isUserProvided()) {
4706         // Instantiate non-default class member functions ...
4707 
4708         // .. except for certain kinds of template specializations.
4709         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4710           continue;
4711 
4712         S.MarkFunctionReferenced(Class->getLocation(), MD);
4713 
4714         // The function will be passed to the consumer when its definition is
4715         // encountered.
4716       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4717                  MD->isCopyAssignmentOperator() ||
4718                  MD->isMoveAssignmentOperator()) {
4719         // Synthesize and instantiate non-trivial implicit methods, explicitly
4720         // defaulted methods, and the copy and move assignment operators. The
4721         // latter are exported even if they are trivial, because the address of
4722         // an operator can be taken and should compare equal accross libraries.
4723         DiagnosticErrorTrap Trap(S.Diags);
4724         S.MarkFunctionReferenced(Class->getLocation(), MD);
4725         if (Trap.hasErrorOccurred()) {
4726           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
4727               << Class->getName() << !S.getLangOpts().CPlusPlus11;
4728           break;
4729         }
4730 
4731         // There is no later point when we will see the definition of this
4732         // function, so pass it to the consumer now.
4733         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
4734       }
4735     }
4736   }
4737 }
4738 
4739 /// \brief Check class-level dllimport/dllexport attribute.
4740 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
4741   Attr *ClassAttr = getDLLAttr(Class);
4742 
4743   // MSVC inherits DLL attributes to partial class template specializations.
4744   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4745     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4746       if (Attr *TemplateAttr =
4747               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4748         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
4749         A->setInherited(true);
4750         ClassAttr = A;
4751       }
4752     }
4753   }
4754 
4755   if (!ClassAttr)
4756     return;
4757 
4758   if (!Class->isExternallyVisible()) {
4759     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4760         << Class << ClassAttr;
4761     return;
4762   }
4763 
4764   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4765       !ClassAttr->isInherited()) {
4766     // Diagnose dll attributes on members of class with dll attribute.
4767     for (Decl *Member : Class->decls()) {
4768       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4769         continue;
4770       InheritableAttr *MemberAttr = getDLLAttr(Member);
4771       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4772         continue;
4773 
4774       Diag(MemberAttr->getLocation(),
4775              diag::err_attribute_dll_member_of_dll_class)
4776           << MemberAttr << ClassAttr;
4777       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4778       Member->setInvalidDecl();
4779     }
4780   }
4781 
4782   if (Class->getDescribedClassTemplate())
4783     // Don't inherit dll attribute until the template is instantiated.
4784     return;
4785 
4786   // The class is either imported or exported.
4787   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4788   const bool ClassImported = !ClassExported;
4789 
4790   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
4791 
4792   // Ignore explicit dllexport on explicit class template instantiation declarations.
4793   if (ClassExported && !ClassAttr->isInherited() &&
4794       TSK == TSK_ExplicitInstantiationDeclaration) {
4795     Class->dropAttr<DLLExportAttr>();
4796     return;
4797   }
4798 
4799   // Force declaration of implicit members so they can inherit the attribute.
4800   ForceDeclarationOfImplicitMembers(Class);
4801 
4802   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4803   // seem to be true in practice?
4804 
4805   for (Decl *Member : Class->decls()) {
4806     VarDecl *VD = dyn_cast<VarDecl>(Member);
4807     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4808 
4809     // Only methods and static fields inherit the attributes.
4810     if (!VD && !MD)
4811       continue;
4812 
4813     if (MD) {
4814       // Don't process deleted methods.
4815       if (MD->isDeleted())
4816         continue;
4817 
4818       if (MD->isInlined()) {
4819         // MinGW does not import or export inline methods.
4820         if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
4821           continue;
4822 
4823         // MSVC versions before 2015 don't export the move assignment operators,
4824         // so don't attempt to import them if we have a definition.
4825         if (ClassImported && MD->isMoveAssignmentOperator() &&
4826             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
4827           continue;
4828       }
4829     }
4830 
4831     if (!cast<NamedDecl>(Member)->isExternallyVisible())
4832       continue;
4833 
4834     if (!getDLLAttr(Member)) {
4835       auto *NewAttr =
4836           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4837       NewAttr->setInherited(true);
4838       Member->addAttr(NewAttr);
4839     }
4840   }
4841 
4842   if (ClassExported)
4843     DelayedDllExportClasses.push_back(Class);
4844 }
4845 
4846 /// \brief Perform propagation of DLL attributes from a derived class to a
4847 /// templated base class for MS compatibility.
4848 void Sema::propagateDLLAttrToBaseClassTemplate(
4849     CXXRecordDecl *Class, Attr *ClassAttr,
4850     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
4851   if (getDLLAttr(
4852           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
4853     // If the base class template has a DLL attribute, don't try to change it.
4854     return;
4855   }
4856 
4857   auto TSK = BaseTemplateSpec->getSpecializationKind();
4858   if (!getDLLAttr(BaseTemplateSpec) &&
4859       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
4860        TSK == TSK_ImplicitInstantiation)) {
4861     // The template hasn't been instantiated yet (or it has, but only as an
4862     // explicit instantiation declaration or implicit instantiation, which means
4863     // we haven't codegenned any members yet), so propagate the attribute.
4864     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
4865     NewAttr->setInherited(true);
4866     BaseTemplateSpec->addAttr(NewAttr);
4867 
4868     // If the template is already instantiated, checkDLLAttributeRedeclaration()
4869     // needs to be run again to work see the new attribute. Otherwise this will
4870     // get run whenever the template is instantiated.
4871     if (TSK != TSK_Undeclared)
4872       checkClassLevelDLLAttribute(BaseTemplateSpec);
4873 
4874     return;
4875   }
4876 
4877   if (getDLLAttr(BaseTemplateSpec)) {
4878     // The template has already been specialized or instantiated with an
4879     // attribute, explicitly or through propagation. We should not try to change
4880     // it.
4881     return;
4882   }
4883 
4884   // The template was previously instantiated or explicitly specialized without
4885   // a dll attribute, It's too late for us to add an attribute, so warn that
4886   // this is unsupported.
4887   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
4888       << BaseTemplateSpec->isExplicitSpecialization();
4889   Diag(ClassAttr->getLocation(), diag::note_attribute);
4890   if (BaseTemplateSpec->isExplicitSpecialization()) {
4891     Diag(BaseTemplateSpec->getLocation(),
4892            diag::note_template_class_explicit_specialization_was_here)
4893         << BaseTemplateSpec;
4894   } else {
4895     Diag(BaseTemplateSpec->getPointOfInstantiation(),
4896            diag::note_template_class_instantiation_was_here)
4897         << BaseTemplateSpec;
4898   }
4899 }
4900 
4901 /// \brief Perform semantic checks on a class definition that has been
4902 /// completing, introducing implicitly-declared members, checking for
4903 /// abstract types, etc.
4904 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4905   if (!Record)
4906     return;
4907 
4908   if (Record->isAbstract() && !Record->isInvalidDecl()) {
4909     AbstractUsageInfo Info(*this, Record);
4910     CheckAbstractClassUsage(Info, Record);
4911   }
4912 
4913   // If this is not an aggregate type and has no user-declared constructor,
4914   // complain about any non-static data members of reference or const scalar
4915   // type, since they will never get initializers.
4916   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4917       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4918       !Record->isLambda()) {
4919     bool Complained = false;
4920     for (const auto *F : Record->fields()) {
4921       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4922         continue;
4923 
4924       if (F->getType()->isReferenceType() ||
4925           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4926         if (!Complained) {
4927           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4928             << Record->getTagKind() << Record;
4929           Complained = true;
4930         }
4931 
4932         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4933           << F->getType()->isReferenceType()
4934           << F->getDeclName();
4935       }
4936     }
4937   }
4938 
4939   if (Record->getIdentifier()) {
4940     // C++ [class.mem]p13:
4941     //   If T is the name of a class, then each of the following shall have a
4942     //   name different from T:
4943     //     - every member of every anonymous union that is a member of class T.
4944     //
4945     // C++ [class.mem]p14:
4946     //   In addition, if class T has a user-declared constructor (12.1), every
4947     //   non-static data member of class T shall have a name different from T.
4948     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4949     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4950          ++I) {
4951       NamedDecl *D = *I;
4952       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4953           isa<IndirectFieldDecl>(D)) {
4954         Diag(D->getLocation(), diag::err_member_name_of_class)
4955           << D->getDeclName();
4956         break;
4957       }
4958     }
4959   }
4960 
4961   // Warn if the class has virtual methods but non-virtual public destructor.
4962   if (Record->isPolymorphic() && !Record->isDependentType()) {
4963     CXXDestructorDecl *dtor = Record->getDestructor();
4964     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4965         !Record->hasAttr<FinalAttr>())
4966       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4967            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4968   }
4969 
4970   if (Record->isAbstract()) {
4971     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4972       Diag(Record->getLocation(), diag::warn_abstract_final_class)
4973         << FA->isSpelledAsSealed();
4974       DiagnoseAbstractType(Record);
4975     }
4976   }
4977 
4978   bool HasMethodWithOverrideControl = false,
4979        HasOverridingMethodWithoutOverrideControl = false;
4980   if (!Record->isDependentType()) {
4981     for (auto *M : Record->methods()) {
4982       // See if a method overloads virtual methods in a base
4983       // class without overriding any.
4984       if (!M->isStatic())
4985         DiagnoseHiddenVirtualMethods(M);
4986       if (M->hasAttr<OverrideAttr>())
4987         HasMethodWithOverrideControl = true;
4988       else if (M->size_overridden_methods() > 0)
4989         HasOverridingMethodWithoutOverrideControl = true;
4990       // Check whether the explicitly-defaulted special members are valid.
4991       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4992         CheckExplicitlyDefaultedSpecialMember(M);
4993 
4994       // For an explicitly defaulted or deleted special member, we defer
4995       // determining triviality until the class is complete. That time is now!
4996       if (!M->isImplicit() && !M->isUserProvided()) {
4997         CXXSpecialMember CSM = getSpecialMember(M);
4998         if (CSM != CXXInvalid) {
4999           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5000 
5001           // Inform the class that we've finished declaring this member.
5002           Record->finishedDefaultedOrDeletedMember(M);
5003         }
5004       }
5005     }
5006   }
5007 
5008   if (HasMethodWithOverrideControl &&
5009       HasOverridingMethodWithoutOverrideControl) {
5010     // At least one method has the 'override' control declared.
5011     // Diagnose all other overridden methods which do not have 'override' specified on them.
5012     for (auto *M : Record->methods())
5013       DiagnoseAbsenceOfOverrideControl(M);
5014   }
5015 
5016   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5017   // whether this class uses any C++ features that are implemented
5018   // completely differently in MSVC, and if so, emit a diagnostic.
5019   // That diagnostic defaults to an error, but we allow projects to
5020   // map it down to a warning (or ignore it).  It's a fairly common
5021   // practice among users of the ms_struct pragma to mass-annotate
5022   // headers, sweeping up a bunch of types that the project doesn't
5023   // really rely on MSVC-compatible layout for.  We must therefore
5024   // support "ms_struct except for C++ stuff" as a secondary ABI.
5025   if (Record->isMsStruct(Context) &&
5026       (Record->isPolymorphic() || Record->getNumBases())) {
5027     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5028   }
5029 
5030   // Declare inheriting constructors. We do this eagerly here because:
5031   // - The standard requires an eager diagnostic for conflicting inheriting
5032   //   constructors from different classes.
5033   // - The lazy declaration of the other implicit constructors is so as to not
5034   //   waste space and performance on classes that are not meant to be
5035   //   instantiated (e.g. meta-functions). This doesn't apply to classes that
5036   //   have inheriting constructors.
5037   DeclareInheritingConstructors(Record);
5038 
5039   checkClassLevelDLLAttribute(Record);
5040 }
5041 
5042 /// Look up the special member function that would be called by a special
5043 /// member function for a subobject of class type.
5044 ///
5045 /// \param Class The class type of the subobject.
5046 /// \param CSM The kind of special member function.
5047 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5048 /// \param ConstRHS True if this is a copy operation with a const object
5049 ///        on its RHS, that is, if the argument to the outer special member
5050 ///        function is 'const' and this is not a field marked 'mutable'.
5051 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5052     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5053     unsigned FieldQuals, bool ConstRHS) {
5054   unsigned LHSQuals = 0;
5055   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5056     LHSQuals = FieldQuals;
5057 
5058   unsigned RHSQuals = FieldQuals;
5059   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5060     RHSQuals = 0;
5061   else if (ConstRHS)
5062     RHSQuals |= Qualifiers::Const;
5063 
5064   return S.LookupSpecialMember(Class, CSM,
5065                                RHSQuals & Qualifiers::Const,
5066                                RHSQuals & Qualifiers::Volatile,
5067                                false,
5068                                LHSQuals & Qualifiers::Const,
5069                                LHSQuals & Qualifiers::Volatile);
5070 }
5071 
5072 /// Is the special member function which would be selected to perform the
5073 /// specified operation on the specified class type a constexpr constructor?
5074 static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5075                                      Sema::CXXSpecialMember CSM,
5076                                      unsigned Quals, bool ConstRHS) {
5077   Sema::SpecialMemberOverloadResult *SMOR =
5078       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5079   if (!SMOR || !SMOR->getMethod())
5080     // A constructor we wouldn't select can't be "involved in initializing"
5081     // anything.
5082     return true;
5083   return SMOR->getMethod()->isConstexpr();
5084 }
5085 
5086 /// Determine whether the specified special member function would be constexpr
5087 /// if it were implicitly defined.
5088 static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5089                                               Sema::CXXSpecialMember CSM,
5090                                               bool ConstArg) {
5091   if (!S.getLangOpts().CPlusPlus11)
5092     return false;
5093 
5094   // C++11 [dcl.constexpr]p4:
5095   // In the definition of a constexpr constructor [...]
5096   bool Ctor = true;
5097   switch (CSM) {
5098   case Sema::CXXDefaultConstructor:
5099     // Since default constructor lookup is essentially trivial (and cannot
5100     // involve, for instance, template instantiation), we compute whether a
5101     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5102     //
5103     // This is important for performance; we need to know whether the default
5104     // constructor is constexpr to determine whether the type is a literal type.
5105     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5106 
5107   case Sema::CXXCopyConstructor:
5108   case Sema::CXXMoveConstructor:
5109     // For copy or move constructors, we need to perform overload resolution.
5110     break;
5111 
5112   case Sema::CXXCopyAssignment:
5113   case Sema::CXXMoveAssignment:
5114     if (!S.getLangOpts().CPlusPlus14)
5115       return false;
5116     // In C++1y, we need to perform overload resolution.
5117     Ctor = false;
5118     break;
5119 
5120   case Sema::CXXDestructor:
5121   case Sema::CXXInvalid:
5122     return false;
5123   }
5124 
5125   //   -- if the class is a non-empty union, or for each non-empty anonymous
5126   //      union member of a non-union class, exactly one non-static data member
5127   //      shall be initialized; [DR1359]
5128   //
5129   // If we squint, this is guaranteed, since exactly one non-static data member
5130   // will be initialized (if the constructor isn't deleted), we just don't know
5131   // which one.
5132   if (Ctor && ClassDecl->isUnion())
5133     return true;
5134 
5135   //   -- the class shall not have any virtual base classes;
5136   if (Ctor && ClassDecl->getNumVBases())
5137     return false;
5138 
5139   // C++1y [class.copy]p26:
5140   //   -- [the class] is a literal type, and
5141   if (!Ctor && !ClassDecl->isLiteral())
5142     return false;
5143 
5144   //   -- every constructor involved in initializing [...] base class
5145   //      sub-objects shall be a constexpr constructor;
5146   //   -- the assignment operator selected to copy/move each direct base
5147   //      class is a constexpr function, and
5148   for (const auto &B : ClassDecl->bases()) {
5149     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5150     if (!BaseType) continue;
5151 
5152     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5153     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
5154       return false;
5155   }
5156 
5157   //   -- every constructor involved in initializing non-static data members
5158   //      [...] shall be a constexpr constructor;
5159   //   -- every non-static data member and base class sub-object shall be
5160   //      initialized
5161   //   -- for each non-static data member of X that is of class type (or array
5162   //      thereof), the assignment operator selected to copy/move that member is
5163   //      a constexpr function
5164   for (const auto *F : ClassDecl->fields()) {
5165     if (F->isInvalidDecl())
5166       continue;
5167     QualType BaseType = S.Context.getBaseElementType(F->getType());
5168     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
5169       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5170       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5171                                     BaseType.getCVRQualifiers(),
5172                                     ConstArg && !F->isMutable()))
5173         return false;
5174     }
5175   }
5176 
5177   // All OK, it's constexpr!
5178   return true;
5179 }
5180 
5181 static Sema::ImplicitExceptionSpecification
5182 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5183   switch (S.getSpecialMember(MD)) {
5184   case Sema::CXXDefaultConstructor:
5185     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5186   case Sema::CXXCopyConstructor:
5187     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5188   case Sema::CXXCopyAssignment:
5189     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5190   case Sema::CXXMoveConstructor:
5191     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5192   case Sema::CXXMoveAssignment:
5193     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5194   case Sema::CXXDestructor:
5195     return S.ComputeDefaultedDtorExceptionSpec(MD);
5196   case Sema::CXXInvalid:
5197     break;
5198   }
5199   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5200          "only special members have implicit exception specs");
5201   return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
5202 }
5203 
5204 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5205                                                             CXXMethodDecl *MD) {
5206   FunctionProtoType::ExtProtoInfo EPI;
5207 
5208   // Build an exception specification pointing back at this member.
5209   EPI.ExceptionSpec.Type = EST_Unevaluated;
5210   EPI.ExceptionSpec.SourceDecl = MD;
5211 
5212   // Set the calling convention to the default for C++ instance methods.
5213   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5214       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5215                                             /*IsCXXMethod=*/true));
5216   return EPI;
5217 }
5218 
5219 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5220   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5221   if (FPT->getExceptionSpecType() != EST_Unevaluated)
5222     return;
5223 
5224   // Evaluate the exception specification.
5225   auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
5226 
5227   // Update the type of the special member to use it.
5228   UpdateExceptionSpec(MD, ESI);
5229 
5230   // A user-provided destructor can be defined outside the class. When that
5231   // happens, be sure to update the exception specification on both
5232   // declarations.
5233   const FunctionProtoType *CanonicalFPT =
5234     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5235   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
5236     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
5237 }
5238 
5239 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5240   CXXRecordDecl *RD = MD->getParent();
5241   CXXSpecialMember CSM = getSpecialMember(MD);
5242 
5243   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5244          "not an explicitly-defaulted special member");
5245 
5246   // Whether this was the first-declared instance of the constructor.
5247   // This affects whether we implicitly add an exception spec and constexpr.
5248   bool First = MD == MD->getCanonicalDecl();
5249 
5250   bool HadError = false;
5251 
5252   // C++11 [dcl.fct.def.default]p1:
5253   //   A function that is explicitly defaulted shall
5254   //     -- be a special member function (checked elsewhere),
5255   //     -- have the same type (except for ref-qualifiers, and except that a
5256   //        copy operation can take a non-const reference) as an implicit
5257   //        declaration, and
5258   //     -- not have default arguments.
5259   unsigned ExpectedParams = 1;
5260   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5261     ExpectedParams = 0;
5262   if (MD->getNumParams() != ExpectedParams) {
5263     // This also checks for default arguments: a copy or move constructor with a
5264     // default argument is classified as a default constructor, and assignment
5265     // operations and destructors can't have default arguments.
5266     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5267       << CSM << MD->getSourceRange();
5268     HadError = true;
5269   } else if (MD->isVariadic()) {
5270     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5271       << CSM << MD->getSourceRange();
5272     HadError = true;
5273   }
5274 
5275   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
5276 
5277   bool CanHaveConstParam = false;
5278   if (CSM == CXXCopyConstructor)
5279     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
5280   else if (CSM == CXXCopyAssignment)
5281     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
5282 
5283   QualType ReturnType = Context.VoidTy;
5284   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5285     // Check for return type matching.
5286     ReturnType = Type->getReturnType();
5287     QualType ExpectedReturnType =
5288         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5289     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5290       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5291         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5292       HadError = true;
5293     }
5294 
5295     // A defaulted special member cannot have cv-qualifiers.
5296     if (Type->getTypeQuals()) {
5297       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
5298         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
5299       HadError = true;
5300     }
5301   }
5302 
5303   // Check for parameter type matching.
5304   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
5305   bool HasConstParam = false;
5306   if (ExpectedParams && ArgType->isReferenceType()) {
5307     // Argument must be reference to possibly-const T.
5308     QualType ReferentType = ArgType->getPointeeType();
5309     HasConstParam = ReferentType.isConstQualified();
5310 
5311     if (ReferentType.isVolatileQualified()) {
5312       Diag(MD->getLocation(),
5313            diag::err_defaulted_special_member_volatile_param) << CSM;
5314       HadError = true;
5315     }
5316 
5317     if (HasConstParam && !CanHaveConstParam) {
5318       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5319         Diag(MD->getLocation(),
5320              diag::err_defaulted_special_member_copy_const_param)
5321           << (CSM == CXXCopyAssignment);
5322         // FIXME: Explain why this special member can't be const.
5323       } else {
5324         Diag(MD->getLocation(),
5325              diag::err_defaulted_special_member_move_const_param)
5326           << (CSM == CXXMoveAssignment);
5327       }
5328       HadError = true;
5329     }
5330   } else if (ExpectedParams) {
5331     // A copy assignment operator can take its argument by value, but a
5332     // defaulted one cannot.
5333     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
5334     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
5335     HadError = true;
5336   }
5337 
5338   // C++11 [dcl.fct.def.default]p2:
5339   //   An explicitly-defaulted function may be declared constexpr only if it
5340   //   would have been implicitly declared as constexpr,
5341   // Do not apply this rule to members of class templates, since core issue 1358
5342   // makes such functions always instantiate to constexpr functions. For
5343   // functions which cannot be constexpr (for non-constructors in C++11 and for
5344   // destructors in C++1y), this is checked elsewhere.
5345   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5346                                                      HasConstParam);
5347   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
5348                                  : isa<CXXConstructorDecl>(MD)) &&
5349       MD->isConstexpr() && !Constexpr &&
5350       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5351     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
5352     // FIXME: Explain why the special member can't be constexpr.
5353     HadError = true;
5354   }
5355 
5356   //   and may have an explicit exception-specification only if it is compatible
5357   //   with the exception-specification on the implicit declaration.
5358   if (Type->hasExceptionSpec()) {
5359     // Delay the check if this is the first declaration of the special member,
5360     // since we may not have parsed some necessary in-class initializers yet.
5361     if (First) {
5362       // If the exception specification needs to be instantiated, do so now,
5363       // before we clobber it with an EST_Unevaluated specification below.
5364       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5365         InstantiateExceptionSpec(MD->getLocStart(), MD);
5366         Type = MD->getType()->getAs<FunctionProtoType>();
5367       }
5368       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
5369     } else
5370       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5371   }
5372 
5373   //   If a function is explicitly defaulted on its first declaration,
5374   if (First) {
5375     //  -- it is implicitly considered to be constexpr if the implicit
5376     //     definition would be,
5377     MD->setConstexpr(Constexpr);
5378 
5379     //  -- it is implicitly considered to have the same exception-specification
5380     //     as if it had been implicitly declared,
5381     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
5382     EPI.ExceptionSpec.Type = EST_Unevaluated;
5383     EPI.ExceptionSpec.SourceDecl = MD;
5384     MD->setType(Context.getFunctionType(ReturnType,
5385                                         llvm::makeArrayRef(&ArgType,
5386                                                            ExpectedParams),
5387                                         EPI));
5388   }
5389 
5390   if (ShouldDeleteSpecialMember(MD, CSM)) {
5391     if (First) {
5392       SetDeclDeleted(MD, MD->getLocation());
5393     } else {
5394       // C++11 [dcl.fct.def.default]p4:
5395       //   [For a] user-provided explicitly-defaulted function [...] if such a
5396       //   function is implicitly defined as deleted, the program is ill-formed.
5397       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
5398       ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
5399       HadError = true;
5400     }
5401   }
5402 
5403   if (HadError)
5404     MD->setInvalidDecl();
5405 }
5406 
5407 /// Check whether the exception specification provided for an
5408 /// explicitly-defaulted special member matches the exception specification
5409 /// that would have been generated for an implicit special member, per
5410 /// C++11 [dcl.fct.def.default]p2.
5411 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5412     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
5413   // If the exception specification was explicitly specified but hadn't been
5414   // parsed when the method was defaulted, grab it now.
5415   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5416     SpecifiedType =
5417         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5418 
5419   // Compute the implicit exception specification.
5420   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5421                                                        /*IsCXXMethod=*/true);
5422   FunctionProtoType::ExtProtoInfo EPI(CC);
5423   EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5424                           .getExceptionSpec();
5425   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
5426     Context.getFunctionType(Context.VoidTy, None, EPI));
5427 
5428   // Ensure that it matches.
5429   CheckEquivalentExceptionSpec(
5430     PDiag(diag::err_incorrect_defaulted_exception_spec)
5431       << getSpecialMember(MD), PDiag(),
5432     ImplicitType, SourceLocation(),
5433     SpecifiedType, MD->getLocation());
5434 }
5435 
5436 void Sema::CheckDelayedMemberExceptionSpecs() {
5437   decltype(DelayedExceptionSpecChecks) Checks;
5438   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
5439 
5440   std::swap(Checks, DelayedExceptionSpecChecks);
5441   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5442 
5443   // Perform any deferred checking of exception specifications for virtual
5444   // destructors.
5445   for (auto &Check : Checks)
5446     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
5447 
5448   // Check that any explicitly-defaulted methods have exception specifications
5449   // compatible with their implicit exception specifications.
5450   for (auto &Spec : Specs)
5451     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
5452 }
5453 
5454 namespace {
5455 struct SpecialMemberDeletionInfo {
5456   Sema &S;
5457   CXXMethodDecl *MD;
5458   Sema::CXXSpecialMember CSM;
5459   bool Diagnose;
5460 
5461   // Properties of the special member, computed for convenience.
5462   bool IsConstructor, IsAssignment, IsMove, ConstArg;
5463   SourceLocation Loc;
5464 
5465   bool AllFieldsAreConst;
5466 
5467   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
5468                             Sema::CXXSpecialMember CSM, bool Diagnose)
5469     : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
5470       IsConstructor(false), IsAssignment(false), IsMove(false),
5471       ConstArg(false), Loc(MD->getLocation()),
5472       AllFieldsAreConst(true) {
5473     switch (CSM) {
5474       case Sema::CXXDefaultConstructor:
5475       case Sema::CXXCopyConstructor:
5476         IsConstructor = true;
5477         break;
5478       case Sema::CXXMoveConstructor:
5479         IsConstructor = true;
5480         IsMove = true;
5481         break;
5482       case Sema::CXXCopyAssignment:
5483         IsAssignment = true;
5484         break;
5485       case Sema::CXXMoveAssignment:
5486         IsAssignment = true;
5487         IsMove = true;
5488         break;
5489       case Sema::CXXDestructor:
5490         break;
5491       case Sema::CXXInvalid:
5492         llvm_unreachable("invalid special member kind");
5493     }
5494 
5495     if (MD->getNumParams()) {
5496       if (const ReferenceType *RT =
5497               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5498         ConstArg = RT->getPointeeType().isConstQualified();
5499     }
5500   }
5501 
5502   bool inUnion() const { return MD->getParent()->isUnion(); }
5503 
5504   /// Look up the corresponding special member in the given class.
5505   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
5506                                               unsigned Quals, bool IsMutable) {
5507     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5508                                        ConstArg && !IsMutable);
5509   }
5510 
5511   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
5512 
5513   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
5514   bool shouldDeleteForField(FieldDecl *FD);
5515   bool shouldDeleteForAllConstMembers();
5516 
5517   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5518                                      unsigned Quals);
5519   bool shouldDeleteForSubobjectCall(Subobject Subobj,
5520                                     Sema::SpecialMemberOverloadResult *SMOR,
5521                                     bool IsDtorCallInCtor);
5522 
5523   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
5524 };
5525 }
5526 
5527 /// Is the given special member inaccessible when used on the given
5528 /// sub-object.
5529 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5530                                              CXXMethodDecl *target) {
5531   /// If we're operating on a base class, the object type is the
5532   /// type of this special member.
5533   QualType objectTy;
5534   AccessSpecifier access = target->getAccess();
5535   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5536     objectTy = S.Context.getTypeDeclType(MD->getParent());
5537     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5538 
5539   // If we're operating on a field, the object type is the type of the field.
5540   } else {
5541     objectTy = S.Context.getTypeDeclType(target->getParent());
5542   }
5543 
5544   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5545 }
5546 
5547 /// Check whether we should delete a special member due to the implicit
5548 /// definition containing a call to a special member of a subobject.
5549 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5550     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5551     bool IsDtorCallInCtor) {
5552   CXXMethodDecl *Decl = SMOR->getMethod();
5553   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5554 
5555   int DiagKind = -1;
5556 
5557   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5558     DiagKind = !Decl ? 0 : 1;
5559   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5560     DiagKind = 2;
5561   else if (!isAccessible(Subobj, Decl))
5562     DiagKind = 3;
5563   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5564            !Decl->isTrivial()) {
5565     // A member of a union must have a trivial corresponding special member.
5566     // As a weird special case, a destructor call from a union's constructor
5567     // must be accessible and non-deleted, but need not be trivial. Such a
5568     // destructor is never actually called, but is semantically checked as
5569     // if it were.
5570     DiagKind = 4;
5571   }
5572 
5573   if (DiagKind == -1)
5574     return false;
5575 
5576   if (Diagnose) {
5577     if (Field) {
5578       S.Diag(Field->getLocation(),
5579              diag::note_deleted_special_member_class_subobject)
5580         << CSM << MD->getParent() << /*IsField*/true
5581         << Field << DiagKind << IsDtorCallInCtor;
5582     } else {
5583       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5584       S.Diag(Base->getLocStart(),
5585              diag::note_deleted_special_member_class_subobject)
5586         << CSM << MD->getParent() << /*IsField*/false
5587         << Base->getType() << DiagKind << IsDtorCallInCtor;
5588     }
5589 
5590     if (DiagKind == 1)
5591       S.NoteDeletedFunction(Decl);
5592     // FIXME: Explain inaccessibility if DiagKind == 3.
5593   }
5594 
5595   return true;
5596 }
5597 
5598 /// Check whether we should delete a special member function due to having a
5599 /// direct or virtual base class or non-static data member of class type M.
5600 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5601     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5602   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5603   bool IsMutable = Field && Field->isMutable();
5604 
5605   // C++11 [class.ctor]p5:
5606   // -- any direct or virtual base class, or non-static data member with no
5607   //    brace-or-equal-initializer, has class type M (or array thereof) and
5608   //    either M has no default constructor or overload resolution as applied
5609   //    to M's default constructor results in an ambiguity or in a function
5610   //    that is deleted or inaccessible
5611   // C++11 [class.copy]p11, C++11 [class.copy]p23:
5612   // -- a direct or virtual base class B that cannot be copied/moved because
5613   //    overload resolution, as applied to B's corresponding special member,
5614   //    results in an ambiguity or a function that is deleted or inaccessible
5615   //    from the defaulted special member
5616   // C++11 [class.dtor]p5:
5617   // -- any direct or virtual base class [...] has a type with a destructor
5618   //    that is deleted or inaccessible
5619   if (!(CSM == Sema::CXXDefaultConstructor &&
5620         Field && Field->hasInClassInitializer()) &&
5621       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5622                                    false))
5623     return true;
5624 
5625   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5626   // -- any direct or virtual base class or non-static data member has a
5627   //    type with a destructor that is deleted or inaccessible
5628   if (IsConstructor) {
5629     Sema::SpecialMemberOverloadResult *SMOR =
5630         S.LookupSpecialMember(Class, Sema::CXXDestructor,
5631                               false, false, false, false, false);
5632     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5633       return true;
5634   }
5635 
5636   return false;
5637 }
5638 
5639 /// Check whether we should delete a special member function due to the class
5640 /// having a particular direct or virtual base class.
5641 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5642   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5643   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5644 }
5645 
5646 /// Check whether we should delete a special member function due to the class
5647 /// having a particular non-static data member.
5648 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5649   QualType FieldType = S.Context.getBaseElementType(FD->getType());
5650   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5651 
5652   if (CSM == Sema::CXXDefaultConstructor) {
5653     // For a default constructor, all references must be initialized in-class
5654     // and, if a union, it must have a non-const member.
5655     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5656       if (Diagnose)
5657         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5658           << MD->getParent() << FD << FieldType << /*Reference*/0;
5659       return true;
5660     }
5661     // C++11 [class.ctor]p5: any non-variant non-static data member of
5662     // const-qualified type (or array thereof) with no
5663     // brace-or-equal-initializer does not have a user-provided default
5664     // constructor.
5665     if (!inUnion() && FieldType.isConstQualified() &&
5666         !FD->hasInClassInitializer() &&
5667         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5668       if (Diagnose)
5669         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5670           << MD->getParent() << FD << FD->getType() << /*Const*/1;
5671       return true;
5672     }
5673 
5674     if (inUnion() && !FieldType.isConstQualified())
5675       AllFieldsAreConst = false;
5676   } else if (CSM == Sema::CXXCopyConstructor) {
5677     // For a copy constructor, data members must not be of rvalue reference
5678     // type.
5679     if (FieldType->isRValueReferenceType()) {
5680       if (Diagnose)
5681         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5682           << MD->getParent() << FD << FieldType;
5683       return true;
5684     }
5685   } else if (IsAssignment) {
5686     // For an assignment operator, data members must not be of reference type.
5687     if (FieldType->isReferenceType()) {
5688       if (Diagnose)
5689         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5690           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5691       return true;
5692     }
5693     if (!FieldRecord && FieldType.isConstQualified()) {
5694       // C++11 [class.copy]p23:
5695       // -- a non-static data member of const non-class type (or array thereof)
5696       if (Diagnose)
5697         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5698           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5699       return true;
5700     }
5701   }
5702 
5703   if (FieldRecord) {
5704     // Some additional restrictions exist on the variant members.
5705     if (!inUnion() && FieldRecord->isUnion() &&
5706         FieldRecord->isAnonymousStructOrUnion()) {
5707       bool AllVariantFieldsAreConst = true;
5708 
5709       // FIXME: Handle anonymous unions declared within anonymous unions.
5710       for (auto *UI : FieldRecord->fields()) {
5711         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5712 
5713         if (!UnionFieldType.isConstQualified())
5714           AllVariantFieldsAreConst = false;
5715 
5716         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5717         if (UnionFieldRecord &&
5718             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
5719                                           UnionFieldType.getCVRQualifiers()))
5720           return true;
5721       }
5722 
5723       // At least one member in each anonymous union must be non-const
5724       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5725           !FieldRecord->field_empty()) {
5726         if (Diagnose)
5727           S.Diag(FieldRecord->getLocation(),
5728                  diag::note_deleted_default_ctor_all_const)
5729             << MD->getParent() << /*anonymous union*/1;
5730         return true;
5731       }
5732 
5733       // Don't check the implicit member of the anonymous union type.
5734       // This is technically non-conformant, but sanity demands it.
5735       return false;
5736     }
5737 
5738     if (shouldDeleteForClassSubobject(FieldRecord, FD,
5739                                       FieldType.getCVRQualifiers()))
5740       return true;
5741   }
5742 
5743   return false;
5744 }
5745 
5746 /// C++11 [class.ctor] p5:
5747 ///   A defaulted default constructor for a class X is defined as deleted if
5748 /// X is a union and all of its variant members are of const-qualified type.
5749 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5750   // This is a silly definition, because it gives an empty union a deleted
5751   // default constructor. Don't do that.
5752   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5753       !MD->getParent()->field_empty()) {
5754     if (Diagnose)
5755       S.Diag(MD->getParent()->getLocation(),
5756              diag::note_deleted_default_ctor_all_const)
5757         << MD->getParent() << /*not anonymous union*/0;
5758     return true;
5759   }
5760   return false;
5761 }
5762 
5763 /// Determine whether a defaulted special member function should be defined as
5764 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5765 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5766 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5767                                      bool Diagnose) {
5768   if (MD->isInvalidDecl())
5769     return false;
5770   CXXRecordDecl *RD = MD->getParent();
5771   assert(!RD->isDependentType() && "do deletion after instantiation");
5772   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5773     return false;
5774 
5775   // C++11 [expr.lambda.prim]p19:
5776   //   The closure type associated with a lambda-expression has a
5777   //   deleted (8.4.3) default constructor and a deleted copy
5778   //   assignment operator.
5779   if (RD->isLambda() &&
5780       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5781     if (Diagnose)
5782       Diag(RD->getLocation(), diag::note_lambda_decl);
5783     return true;
5784   }
5785 
5786   // For an anonymous struct or union, the copy and assignment special members
5787   // will never be used, so skip the check. For an anonymous union declared at
5788   // namespace scope, the constructor and destructor are used.
5789   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5790       RD->isAnonymousStructOrUnion())
5791     return false;
5792 
5793   // C++11 [class.copy]p7, p18:
5794   //   If the class definition declares a move constructor or move assignment
5795   //   operator, an implicitly declared copy constructor or copy assignment
5796   //   operator is defined as deleted.
5797   if (MD->isImplicit() &&
5798       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5799     CXXMethodDecl *UserDeclaredMove = nullptr;
5800 
5801     // In Microsoft mode, a user-declared move only causes the deletion of the
5802     // corresponding copy operation, not both copy operations.
5803     if (RD->hasUserDeclaredMoveConstructor() &&
5804         (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
5805       if (!Diagnose) return true;
5806 
5807       // Find any user-declared move constructor.
5808       for (auto *I : RD->ctors()) {
5809         if (I->isMoveConstructor()) {
5810           UserDeclaredMove = I;
5811           break;
5812         }
5813       }
5814       assert(UserDeclaredMove);
5815     } else if (RD->hasUserDeclaredMoveAssignment() &&
5816                (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
5817       if (!Diagnose) return true;
5818 
5819       // Find any user-declared move assignment operator.
5820       for (auto *I : RD->methods()) {
5821         if (I->isMoveAssignmentOperator()) {
5822           UserDeclaredMove = I;
5823           break;
5824         }
5825       }
5826       assert(UserDeclaredMove);
5827     }
5828 
5829     if (UserDeclaredMove) {
5830       Diag(UserDeclaredMove->getLocation(),
5831            diag::note_deleted_copy_user_declared_move)
5832         << (CSM == CXXCopyAssignment) << RD
5833         << UserDeclaredMove->isMoveAssignmentOperator();
5834       return true;
5835     }
5836   }
5837 
5838   // Do access control from the special member function
5839   ContextRAII MethodContext(*this, MD);
5840 
5841   // C++11 [class.dtor]p5:
5842   // -- for a virtual destructor, lookup of the non-array deallocation function
5843   //    results in an ambiguity or in a function that is deleted or inaccessible
5844   if (CSM == CXXDestructor && MD->isVirtual()) {
5845     FunctionDecl *OperatorDelete = nullptr;
5846     DeclarationName Name =
5847       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5848     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5849                                  OperatorDelete, false)) {
5850       if (Diagnose)
5851         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5852       return true;
5853     }
5854   }
5855 
5856   SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5857 
5858   for (auto &BI : RD->bases())
5859     if (!BI.isVirtual() &&
5860         SMI.shouldDeleteForBase(&BI))
5861       return true;
5862 
5863   // Per DR1611, do not consider virtual bases of constructors of abstract
5864   // classes, since we are not going to construct them.
5865   if (!RD->isAbstract() || !SMI.IsConstructor) {
5866     for (auto &BI : RD->vbases())
5867       if (SMI.shouldDeleteForBase(&BI))
5868         return true;
5869   }
5870 
5871   for (auto *FI : RD->fields())
5872     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5873         SMI.shouldDeleteForField(FI))
5874       return true;
5875 
5876   if (SMI.shouldDeleteForAllConstMembers())
5877     return true;
5878 
5879   if (getLangOpts().CUDA) {
5880     // We should delete the special member in CUDA mode if target inference
5881     // failed.
5882     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5883                                                    Diagnose);
5884   }
5885 
5886   return false;
5887 }
5888 
5889 /// Perform lookup for a special member of the specified kind, and determine
5890 /// whether it is trivial. If the triviality can be determined without the
5891 /// lookup, skip it. This is intended for use when determining whether a
5892 /// special member of a containing object is trivial, and thus does not ever
5893 /// perform overload resolution for default constructors.
5894 ///
5895 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5896 /// member that was most likely to be intended to be trivial, if any.
5897 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5898                                      Sema::CXXSpecialMember CSM, unsigned Quals,
5899                                      bool ConstRHS, CXXMethodDecl **Selected) {
5900   if (Selected)
5901     *Selected = nullptr;
5902 
5903   switch (CSM) {
5904   case Sema::CXXInvalid:
5905     llvm_unreachable("not a special member");
5906 
5907   case Sema::CXXDefaultConstructor:
5908     // C++11 [class.ctor]p5:
5909     //   A default constructor is trivial if:
5910     //    - all the [direct subobjects] have trivial default constructors
5911     //
5912     // Note, no overload resolution is performed in this case.
5913     if (RD->hasTrivialDefaultConstructor())
5914       return true;
5915 
5916     if (Selected) {
5917       // If there's a default constructor which could have been trivial, dig it
5918       // out. Otherwise, if there's any user-provided default constructor, point
5919       // to that as an example of why there's not a trivial one.
5920       CXXConstructorDecl *DefCtor = nullptr;
5921       if (RD->needsImplicitDefaultConstructor())
5922         S.DeclareImplicitDefaultConstructor(RD);
5923       for (auto *CI : RD->ctors()) {
5924         if (!CI->isDefaultConstructor())
5925           continue;
5926         DefCtor = CI;
5927         if (!DefCtor->isUserProvided())
5928           break;
5929       }
5930 
5931       *Selected = DefCtor;
5932     }
5933 
5934     return false;
5935 
5936   case Sema::CXXDestructor:
5937     // C++11 [class.dtor]p5:
5938     //   A destructor is trivial if:
5939     //    - all the direct [subobjects] have trivial destructors
5940     if (RD->hasTrivialDestructor())
5941       return true;
5942 
5943     if (Selected) {
5944       if (RD->needsImplicitDestructor())
5945         S.DeclareImplicitDestructor(RD);
5946       *Selected = RD->getDestructor();
5947     }
5948 
5949     return false;
5950 
5951   case Sema::CXXCopyConstructor:
5952     // C++11 [class.copy]p12:
5953     //   A copy constructor is trivial if:
5954     //    - the constructor selected to copy each direct [subobject] is trivial
5955     if (RD->hasTrivialCopyConstructor()) {
5956       if (Quals == Qualifiers::Const)
5957         // We must either select the trivial copy constructor or reach an
5958         // ambiguity; no need to actually perform overload resolution.
5959         return true;
5960     } else if (!Selected) {
5961       return false;
5962     }
5963     // In C++98, we are not supposed to perform overload resolution here, but we
5964     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5965     // cases like B as having a non-trivial copy constructor:
5966     //   struct A { template<typename T> A(T&); };
5967     //   struct B { mutable A a; };
5968     goto NeedOverloadResolution;
5969 
5970   case Sema::CXXCopyAssignment:
5971     // C++11 [class.copy]p25:
5972     //   A copy assignment operator is trivial if:
5973     //    - the assignment operator selected to copy each direct [subobject] is
5974     //      trivial
5975     if (RD->hasTrivialCopyAssignment()) {
5976       if (Quals == Qualifiers::Const)
5977         return true;
5978     } else if (!Selected) {
5979       return false;
5980     }
5981     // In C++98, we are not supposed to perform overload resolution here, but we
5982     // treat that as a language defect.
5983     goto NeedOverloadResolution;
5984 
5985   case Sema::CXXMoveConstructor:
5986   case Sema::CXXMoveAssignment:
5987   NeedOverloadResolution:
5988     Sema::SpecialMemberOverloadResult *SMOR =
5989         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
5990 
5991     // The standard doesn't describe how to behave if the lookup is ambiguous.
5992     // We treat it as not making the member non-trivial, just like the standard
5993     // mandates for the default constructor. This should rarely matter, because
5994     // the member will also be deleted.
5995     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5996       return true;
5997 
5998     if (!SMOR->getMethod()) {
5999       assert(SMOR->getKind() ==
6000              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6001       return false;
6002     }
6003 
6004     // We deliberately don't check if we found a deleted special member. We're
6005     // not supposed to!
6006     if (Selected)
6007       *Selected = SMOR->getMethod();
6008     return SMOR->getMethod()->isTrivial();
6009   }
6010 
6011   llvm_unreachable("unknown special method kind");
6012 }
6013 
6014 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6015   for (auto *CI : RD->ctors())
6016     if (!CI->isImplicit())
6017       return CI;
6018 
6019   // Look for constructor templates.
6020   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6021   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6022     if (CXXConstructorDecl *CD =
6023           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6024       return CD;
6025   }
6026 
6027   return nullptr;
6028 }
6029 
6030 /// The kind of subobject we are checking for triviality. The values of this
6031 /// enumeration are used in diagnostics.
6032 enum TrivialSubobjectKind {
6033   /// The subobject is a base class.
6034   TSK_BaseClass,
6035   /// The subobject is a non-static data member.
6036   TSK_Field,
6037   /// The object is actually the complete object.
6038   TSK_CompleteObject
6039 };
6040 
6041 /// Check whether the special member selected for a given type would be trivial.
6042 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6043                                       QualType SubType, bool ConstRHS,
6044                                       Sema::CXXSpecialMember CSM,
6045                                       TrivialSubobjectKind Kind,
6046                                       bool Diagnose) {
6047   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6048   if (!SubRD)
6049     return true;
6050 
6051   CXXMethodDecl *Selected;
6052   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6053                                ConstRHS, Diagnose ? &Selected : nullptr))
6054     return true;
6055 
6056   if (Diagnose) {
6057     if (ConstRHS)
6058       SubType.addConst();
6059 
6060     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6061       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6062         << Kind << SubType.getUnqualifiedType();
6063       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6064         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6065     } else if (!Selected)
6066       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6067         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6068     else if (Selected->isUserProvided()) {
6069       if (Kind == TSK_CompleteObject)
6070         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6071           << Kind << SubType.getUnqualifiedType() << CSM;
6072       else {
6073         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6074           << Kind << SubType.getUnqualifiedType() << CSM;
6075         S.Diag(Selected->getLocation(), diag::note_declared_at);
6076       }
6077     } else {
6078       if (Kind != TSK_CompleteObject)
6079         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6080           << Kind << SubType.getUnqualifiedType() << CSM;
6081 
6082       // Explain why the defaulted or deleted special member isn't trivial.
6083       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6084     }
6085   }
6086 
6087   return false;
6088 }
6089 
6090 /// Check whether the members of a class type allow a special member to be
6091 /// trivial.
6092 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6093                                      Sema::CXXSpecialMember CSM,
6094                                      bool ConstArg, bool Diagnose) {
6095   for (const auto *FI : RD->fields()) {
6096     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6097       continue;
6098 
6099     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6100 
6101     // Pretend anonymous struct or union members are members of this class.
6102     if (FI->isAnonymousStructOrUnion()) {
6103       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6104                                     CSM, ConstArg, Diagnose))
6105         return false;
6106       continue;
6107     }
6108 
6109     // C++11 [class.ctor]p5:
6110     //   A default constructor is trivial if [...]
6111     //    -- no non-static data member of its class has a
6112     //       brace-or-equal-initializer
6113     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
6114       if (Diagnose)
6115         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
6116       return false;
6117     }
6118 
6119     // Objective C ARC 4.3.5:
6120     //   [...] nontrivally ownership-qualified types are [...] not trivially
6121     //   default constructible, copy constructible, move constructible, copy
6122     //   assignable, move assignable, or destructible [...]
6123     if (S.getLangOpts().ObjCAutoRefCount &&
6124         FieldType.hasNonTrivialObjCLifetime()) {
6125       if (Diagnose)
6126         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6127           << RD << FieldType.getObjCLifetime();
6128       return false;
6129     }
6130 
6131     bool ConstRHS = ConstArg && !FI->isMutable();
6132     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6133                                    CSM, TSK_Field, Diagnose))
6134       return false;
6135   }
6136 
6137   return true;
6138 }
6139 
6140 /// Diagnose why the specified class does not have a trivial special member of
6141 /// the given kind.
6142 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6143   QualType Ty = Context.getRecordType(RD);
6144 
6145   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6146   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
6147                             TSK_CompleteObject, /*Diagnose*/true);
6148 }
6149 
6150 /// Determine whether a defaulted or deleted special member function is trivial,
6151 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6152 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6153 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6154                                   bool Diagnose) {
6155   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6156 
6157   CXXRecordDecl *RD = MD->getParent();
6158 
6159   bool ConstArg = false;
6160 
6161   // C++11 [class.copy]p12, p25: [DR1593]
6162   //   A [special member] is trivial if [...] its parameter-type-list is
6163   //   equivalent to the parameter-type-list of an implicit declaration [...]
6164   switch (CSM) {
6165   case CXXDefaultConstructor:
6166   case CXXDestructor:
6167     // Trivial default constructors and destructors cannot have parameters.
6168     break;
6169 
6170   case CXXCopyConstructor:
6171   case CXXCopyAssignment: {
6172     // Trivial copy operations always have const, non-volatile parameter types.
6173     ConstArg = true;
6174     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6175     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6176     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6177       if (Diagnose)
6178         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6179           << Param0->getSourceRange() << Param0->getType()
6180           << Context.getLValueReferenceType(
6181                Context.getRecordType(RD).withConst());
6182       return false;
6183     }
6184     break;
6185   }
6186 
6187   case CXXMoveConstructor:
6188   case CXXMoveAssignment: {
6189     // Trivial move operations always have non-cv-qualified parameters.
6190     const ParmVarDecl *Param0 = MD->getParamDecl(0);
6191     const RValueReferenceType *RT =
6192       Param0->getType()->getAs<RValueReferenceType>();
6193     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6194       if (Diagnose)
6195         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6196           << Param0->getSourceRange() << Param0->getType()
6197           << Context.getRValueReferenceType(Context.getRecordType(RD));
6198       return false;
6199     }
6200     break;
6201   }
6202 
6203   case CXXInvalid:
6204     llvm_unreachable("not a special member");
6205   }
6206 
6207   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6208     if (Diagnose)
6209       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6210            diag::note_nontrivial_default_arg)
6211         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6212     return false;
6213   }
6214   if (MD->isVariadic()) {
6215     if (Diagnose)
6216       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6217     return false;
6218   }
6219 
6220   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6221   //   A copy/move [constructor or assignment operator] is trivial if
6222   //    -- the [member] selected to copy/move each direct base class subobject
6223   //       is trivial
6224   //
6225   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6226   //   A [default constructor or destructor] is trivial if
6227   //    -- all the direct base classes have trivial [default constructors or
6228   //       destructors]
6229   for (const auto &BI : RD->bases())
6230     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6231                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
6232       return false;
6233 
6234   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6235   //   A copy/move [constructor or assignment operator] for a class X is
6236   //   trivial if
6237   //    -- for each non-static data member of X that is of class type (or array
6238   //       thereof), the constructor selected to copy/move that member is
6239   //       trivial
6240   //
6241   // C++11 [class.copy]p12, C++11 [class.copy]p25:
6242   //   A [default constructor or destructor] is trivial if
6243   //    -- for all of the non-static data members of its class that are of class
6244   //       type (or array thereof), each such class has a trivial [default
6245   //       constructor or destructor]
6246   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6247     return false;
6248 
6249   // C++11 [class.dtor]p5:
6250   //   A destructor is trivial if [...]
6251   //    -- the destructor is not virtual
6252   if (CSM == CXXDestructor && MD->isVirtual()) {
6253     if (Diagnose)
6254       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6255     return false;
6256   }
6257 
6258   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6259   //   A [special member] for class X is trivial if [...]
6260   //    -- class X has no virtual functions and no virtual base classes
6261   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6262     if (!Diagnose)
6263       return false;
6264 
6265     if (RD->getNumVBases()) {
6266       // Check for virtual bases. We already know that the corresponding
6267       // member in all bases is trivial, so vbases must all be direct.
6268       CXXBaseSpecifier &BS = *RD->vbases_begin();
6269       assert(BS.isVirtual());
6270       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6271       return false;
6272     }
6273 
6274     // Must have a virtual method.
6275     for (const auto *MI : RD->methods()) {
6276       if (MI->isVirtual()) {
6277         SourceLocation MLoc = MI->getLocStart();
6278         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6279         return false;
6280       }
6281     }
6282 
6283     llvm_unreachable("dynamic class with no vbases and no virtual functions");
6284   }
6285 
6286   // Looks like it's trivial!
6287   return true;
6288 }
6289 
6290 namespace {
6291 struct FindHiddenVirtualMethod {
6292   Sema *S;
6293   CXXMethodDecl *Method;
6294   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
6295   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6296 
6297 private:
6298   /// Check whether any most overriden method from MD in Methods
6299   static bool CheckMostOverridenMethods(
6300       const CXXMethodDecl *MD,
6301       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
6302     if (MD->size_overridden_methods() == 0)
6303       return Methods.count(MD->getCanonicalDecl());
6304     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6305                                         E = MD->end_overridden_methods();
6306          I != E; ++I)
6307       if (CheckMostOverridenMethods(*I, Methods))
6308         return true;
6309     return false;
6310   }
6311 
6312 public:
6313   /// Member lookup function that determines whether a given C++
6314   /// method overloads virtual methods in a base class without overriding any,
6315   /// to be used with CXXRecordDecl::lookupInBases().
6316   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6317     RecordDecl *BaseRecord =
6318         Specifier->getType()->getAs<RecordType>()->getDecl();
6319 
6320     DeclarationName Name = Method->getDeclName();
6321     assert(Name.getNameKind() == DeclarationName::Identifier);
6322 
6323     bool foundSameNameMethod = false;
6324     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
6325     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6326          Path.Decls = Path.Decls.slice(1)) {
6327       NamedDecl *D = Path.Decls.front();
6328       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6329         MD = MD->getCanonicalDecl();
6330         foundSameNameMethod = true;
6331         // Interested only in hidden virtual methods.
6332         if (!MD->isVirtual())
6333           continue;
6334         // If the method we are checking overrides a method from its base
6335         // don't warn about the other overloaded methods. Clang deviates from
6336         // GCC by only diagnosing overloads of inherited virtual functions that
6337         // do not override any other virtual functions in the base. GCC's
6338         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6339         // function from a base class. These cases may be better served by a
6340         // warning (not specific to virtual functions) on call sites when the
6341         // call would select a different function from the base class, were it
6342         // visible.
6343         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
6344         if (!S->IsOverload(Method, MD, false))
6345           return true;
6346         // Collect the overload only if its hidden.
6347         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
6348           overloadedMethods.push_back(MD);
6349       }
6350     }
6351 
6352     if (foundSameNameMethod)
6353       OverloadedMethods.append(overloadedMethods.begin(),
6354                                overloadedMethods.end());
6355     return foundSameNameMethod;
6356   }
6357 };
6358 } // end anonymous namespace
6359 
6360 /// \brief Add the most overriden methods from MD to Methods
6361 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
6362                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
6363   if (MD->size_overridden_methods() == 0)
6364     Methods.insert(MD->getCanonicalDecl());
6365   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6366                                       E = MD->end_overridden_methods();
6367        I != E; ++I)
6368     AddMostOverridenMethods(*I, Methods);
6369 }
6370 
6371 /// \brief Check if a method overloads virtual methods in a base class without
6372 /// overriding any.
6373 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6374                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6375   if (!MD->getDeclName().isIdentifier())
6376     return;
6377 
6378   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6379                      /*bool RecordPaths=*/false,
6380                      /*bool DetectVirtual=*/false);
6381   FindHiddenVirtualMethod FHVM;
6382   FHVM.Method = MD;
6383   FHVM.S = this;
6384 
6385   // Keep the base methods that were overriden or introduced in the subclass
6386   // by 'using' in a set. A base method not in this set is hidden.
6387   CXXRecordDecl *DC = MD->getParent();
6388   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6389   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6390     NamedDecl *ND = *I;
6391     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
6392       ND = shad->getTargetDecl();
6393     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6394       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
6395   }
6396 
6397   if (DC->lookupInBases(FHVM, Paths))
6398     OverloadedMethods = FHVM.OverloadedMethods;
6399 }
6400 
6401 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6402                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6403   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6404     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6405     PartialDiagnostic PD = PDiag(
6406          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6407     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6408     Diag(overloadedMD->getLocation(), PD);
6409   }
6410 }
6411 
6412 /// \brief Diagnose methods which overload virtual methods in a base class
6413 /// without overriding any.
6414 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6415   if (MD->isInvalidDecl())
6416     return;
6417 
6418   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
6419     return;
6420 
6421   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6422   FindHiddenVirtualMethods(MD, OverloadedMethods);
6423   if (!OverloadedMethods.empty()) {
6424     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6425       << MD << (OverloadedMethods.size() > 1);
6426 
6427     NoteHiddenVirtualMethods(MD, OverloadedMethods);
6428   }
6429 }
6430 
6431 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
6432                                              Decl *TagDecl,
6433                                              SourceLocation LBrac,
6434                                              SourceLocation RBrac,
6435                                              AttributeList *AttrList) {
6436   if (!TagDecl)
6437     return;
6438 
6439   AdjustDeclIfTemplate(TagDecl);
6440 
6441   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6442     if (l->getKind() != AttributeList::AT_Visibility)
6443       continue;
6444     l->setInvalid();
6445     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6446       l->getName();
6447   }
6448 
6449   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
6450               // strict aliasing violation!
6451               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
6452               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
6453 
6454   CheckCompletedCXXClass(
6455                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
6456 }
6457 
6458 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6459 /// special functions, such as the default constructor, copy
6460 /// constructor, or destructor, to the given C++ class (C++
6461 /// [special]p1).  This routine can only be executed just before the
6462 /// definition of the class is complete.
6463 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
6464   if (!ClassDecl->hasUserDeclaredConstructor())
6465     ++ASTContext::NumImplicitDefaultConstructors;
6466 
6467   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
6468     ++ASTContext::NumImplicitCopyConstructors;
6469 
6470     // If the properties or semantics of the copy constructor couldn't be
6471     // determined while the class was being declared, force a declaration
6472     // of it now.
6473     if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6474       DeclareImplicitCopyConstructor(ClassDecl);
6475   }
6476 
6477   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
6478     ++ASTContext::NumImplicitMoveConstructors;
6479 
6480     if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6481       DeclareImplicitMoveConstructor(ClassDecl);
6482   }
6483 
6484   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6485     ++ASTContext::NumImplicitCopyAssignmentOperators;
6486 
6487     // If we have a dynamic class, then the copy assignment operator may be
6488     // virtual, so we have to declare it immediately. This ensures that, e.g.,
6489     // it shows up in the right place in the vtable and that we diagnose
6490     // problems with the implicit exception specification.
6491     if (ClassDecl->isDynamicClass() ||
6492         ClassDecl->needsOverloadResolutionForCopyAssignment())
6493       DeclareImplicitCopyAssignment(ClassDecl);
6494   }
6495 
6496   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
6497     ++ASTContext::NumImplicitMoveAssignmentOperators;
6498 
6499     // Likewise for the move assignment operator.
6500     if (ClassDecl->isDynamicClass() ||
6501         ClassDecl->needsOverloadResolutionForMoveAssignment())
6502       DeclareImplicitMoveAssignment(ClassDecl);
6503   }
6504 
6505   if (!ClassDecl->hasUserDeclaredDestructor()) {
6506     ++ASTContext::NumImplicitDestructors;
6507 
6508     // If we have a dynamic class, then the destructor may be virtual, so we
6509     // have to declare the destructor immediately. This ensures that, e.g., it
6510     // shows up in the right place in the vtable and that we diagnose problems
6511     // with the implicit exception specification.
6512     if (ClassDecl->isDynamicClass() ||
6513         ClassDecl->needsOverloadResolutionForDestructor())
6514       DeclareImplicitDestructor(ClassDecl);
6515   }
6516 }
6517 
6518 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
6519   if (!D)
6520     return 0;
6521 
6522   // The order of template parameters is not important here. All names
6523   // get added to the same scope.
6524   SmallVector<TemplateParameterList *, 4> ParameterLists;
6525 
6526   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6527     D = TD->getTemplatedDecl();
6528 
6529   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6530     ParameterLists.push_back(PSD->getTemplateParameters());
6531 
6532   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6533     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6534       ParameterLists.push_back(DD->getTemplateParameterList(i));
6535 
6536     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6537       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6538         ParameterLists.push_back(FTD->getTemplateParameters());
6539     }
6540   }
6541 
6542   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6543     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6544       ParameterLists.push_back(TD->getTemplateParameterList(i));
6545 
6546     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6547       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6548         ParameterLists.push_back(CTD->getTemplateParameters());
6549     }
6550   }
6551 
6552   unsigned Count = 0;
6553   for (TemplateParameterList *Params : ParameterLists) {
6554     if (Params->size() > 0)
6555       // Ignore explicit specializations; they don't contribute to the template
6556       // depth.
6557       ++Count;
6558     for (NamedDecl *Param : *Params) {
6559       if (Param->getDeclName()) {
6560         S->AddDecl(Param);
6561         IdResolver.AddDecl(Param);
6562       }
6563     }
6564   }
6565 
6566   return Count;
6567 }
6568 
6569 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6570   if (!RecordD) return;
6571   AdjustDeclIfTemplate(RecordD);
6572   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
6573   PushDeclContext(S, Record);
6574 }
6575 
6576 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
6577   if (!RecordD) return;
6578   PopDeclContext();
6579 }
6580 
6581 /// This is used to implement the constant expression evaluation part of the
6582 /// attribute enable_if extension. There is nothing in standard C++ which would
6583 /// require reentering parameters.
6584 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6585   if (!Param)
6586     return;
6587 
6588   S->AddDecl(Param);
6589   if (Param->getDeclName())
6590     IdResolver.AddDecl(Param);
6591 }
6592 
6593 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
6594 /// parsing a top-level (non-nested) C++ class, and we are now
6595 /// parsing those parts of the given Method declaration that could
6596 /// not be parsed earlier (C++ [class.mem]p2), such as default
6597 /// arguments. This action should enter the scope of the given
6598 /// Method declaration as if we had just parsed the qualified method
6599 /// name. However, it should not bring the parameters into scope;
6600 /// that will be performed by ActOnDelayedCXXMethodParameter.
6601 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6602 }
6603 
6604 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
6605 /// C++ method declaration. We're (re-)introducing the given
6606 /// function parameter into scope for use in parsing later parts of
6607 /// the method declaration. For example, we could see an
6608 /// ActOnParamDefaultArgument event for this parameter.
6609 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6610   if (!ParamD)
6611     return;
6612 
6613   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6614 
6615   // If this parameter has an unparsed default argument, clear it out
6616   // to make way for the parsed default argument.
6617   if (Param->hasUnparsedDefaultArg())
6618     Param->setDefaultArg(nullptr);
6619 
6620   S->AddDecl(Param);
6621   if (Param->getDeclName())
6622     IdResolver.AddDecl(Param);
6623 }
6624 
6625 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6626 /// processing the delayed method declaration for Method. The method
6627 /// declaration is now considered finished. There may be a separate
6628 /// ActOnStartOfFunctionDef action later (not necessarily
6629 /// immediately!) for this method, if it was also defined inside the
6630 /// class body.
6631 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6632   if (!MethodD)
6633     return;
6634 
6635   AdjustDeclIfTemplate(MethodD);
6636 
6637   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6638 
6639   // Now that we have our default arguments, check the constructor
6640   // again. It could produce additional diagnostics or affect whether
6641   // the class has implicitly-declared destructors, among other
6642   // things.
6643   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6644     CheckConstructor(Constructor);
6645 
6646   // Check the default arguments, which we may have added.
6647   if (!Method->isInvalidDecl())
6648     CheckCXXDefaultArguments(Method);
6649 }
6650 
6651 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6652 /// the well-formedness of the constructor declarator @p D with type @p
6653 /// R. If there are any errors in the declarator, this routine will
6654 /// emit diagnostics and set the invalid bit to true.  In any case, the type
6655 /// will be updated to reflect a well-formed type for the constructor and
6656 /// returned.
6657 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6658                                           StorageClass &SC) {
6659   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6660 
6661   // C++ [class.ctor]p3:
6662   //   A constructor shall not be virtual (10.3) or static (9.4). A
6663   //   constructor can be invoked for a const, volatile or const
6664   //   volatile object. A constructor shall not be declared const,
6665   //   volatile, or const volatile (9.3.2).
6666   if (isVirtual) {
6667     if (!D.isInvalidType())
6668       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6669         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6670         << SourceRange(D.getIdentifierLoc());
6671     D.setInvalidType();
6672   }
6673   if (SC == SC_Static) {
6674     if (!D.isInvalidType())
6675       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6676         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6677         << SourceRange(D.getIdentifierLoc());
6678     D.setInvalidType();
6679     SC = SC_None;
6680   }
6681 
6682   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6683     diagnoseIgnoredQualifiers(
6684         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6685         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6686         D.getDeclSpec().getRestrictSpecLoc(),
6687         D.getDeclSpec().getAtomicSpecLoc());
6688     D.setInvalidType();
6689   }
6690 
6691   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6692   if (FTI.TypeQuals != 0) {
6693     if (FTI.TypeQuals & Qualifiers::Const)
6694       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6695         << "const" << SourceRange(D.getIdentifierLoc());
6696     if (FTI.TypeQuals & Qualifiers::Volatile)
6697       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6698         << "volatile" << SourceRange(D.getIdentifierLoc());
6699     if (FTI.TypeQuals & Qualifiers::Restrict)
6700       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6701         << "restrict" << SourceRange(D.getIdentifierLoc());
6702     D.setInvalidType();
6703   }
6704 
6705   // C++0x [class.ctor]p4:
6706   //   A constructor shall not be declared with a ref-qualifier.
6707   if (FTI.hasRefQualifier()) {
6708     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6709       << FTI.RefQualifierIsLValueRef
6710       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6711     D.setInvalidType();
6712   }
6713 
6714   // Rebuild the function type "R" without any type qualifiers (in
6715   // case any of the errors above fired) and with "void" as the
6716   // return type, since constructors don't have return types.
6717   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6718   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
6719     return R;
6720 
6721   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6722   EPI.TypeQuals = 0;
6723   EPI.RefQualifier = RQ_None;
6724 
6725   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
6726 }
6727 
6728 /// CheckConstructor - Checks a fully-formed constructor for
6729 /// well-formedness, issuing any diagnostics required. Returns true if
6730 /// the constructor declarator is invalid.
6731 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6732   CXXRecordDecl *ClassDecl
6733     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6734   if (!ClassDecl)
6735     return Constructor->setInvalidDecl();
6736 
6737   // C++ [class.copy]p3:
6738   //   A declaration of a constructor for a class X is ill-formed if
6739   //   its first parameter is of type (optionally cv-qualified) X and
6740   //   either there are no other parameters or else all other
6741   //   parameters have default arguments.
6742   if (!Constructor->isInvalidDecl() &&
6743       ((Constructor->getNumParams() == 1) ||
6744        (Constructor->getNumParams() > 1 &&
6745         Constructor->getParamDecl(1)->hasDefaultArg())) &&
6746       Constructor->getTemplateSpecializationKind()
6747                                               != TSK_ImplicitInstantiation) {
6748     QualType ParamType = Constructor->getParamDecl(0)->getType();
6749     QualType ClassTy = Context.getTagDeclType(ClassDecl);
6750     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6751       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6752       const char *ConstRef
6753         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6754                                                         : " const &";
6755       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6756         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6757 
6758       // FIXME: Rather that making the constructor invalid, we should endeavor
6759       // to fix the type.
6760       Constructor->setInvalidDecl();
6761     }
6762   }
6763 }
6764 
6765 /// CheckDestructor - Checks a fully-formed destructor definition for
6766 /// well-formedness, issuing any diagnostics required.  Returns true
6767 /// on error.
6768 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6769   CXXRecordDecl *RD = Destructor->getParent();
6770 
6771   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6772     SourceLocation Loc;
6773 
6774     if (!Destructor->isImplicit())
6775       Loc = Destructor->getLocation();
6776     else
6777       Loc = RD->getLocation();
6778 
6779     // If we have a virtual destructor, look up the deallocation function
6780     FunctionDecl *OperatorDelete = nullptr;
6781     DeclarationName Name =
6782     Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6783     if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6784       return true;
6785     // If there's no class-specific operator delete, look up the global
6786     // non-array delete.
6787     if (!OperatorDelete)
6788       OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
6789 
6790     MarkFunctionReferenced(Loc, OperatorDelete);
6791 
6792     Destructor->setOperatorDelete(OperatorDelete);
6793   }
6794 
6795   return false;
6796 }
6797 
6798 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6799 /// the well-formednes of the destructor declarator @p D with type @p
6800 /// R. If there are any errors in the declarator, this routine will
6801 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
6802 /// will be updated to reflect a well-formed type for the destructor and
6803 /// returned.
6804 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6805                                          StorageClass& SC) {
6806   // C++ [class.dtor]p1:
6807   //   [...] A typedef-name that names a class is a class-name
6808   //   (7.1.3); however, a typedef-name that names a class shall not
6809   //   be used as the identifier in the declarator for a destructor
6810   //   declaration.
6811   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6812   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6813     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6814       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6815   else if (const TemplateSpecializationType *TST =
6816              DeclaratorType->getAs<TemplateSpecializationType>())
6817     if (TST->isTypeAlias())
6818       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6819         << DeclaratorType << 1;
6820 
6821   // C++ [class.dtor]p2:
6822   //   A destructor is used to destroy objects of its class type. A
6823   //   destructor takes no parameters, and no return type can be
6824   //   specified for it (not even void). The address of a destructor
6825   //   shall not be taken. A destructor shall not be static. A
6826   //   destructor can be invoked for a const, volatile or const
6827   //   volatile object. A destructor shall not be declared const,
6828   //   volatile or const volatile (9.3.2).
6829   if (SC == SC_Static) {
6830     if (!D.isInvalidType())
6831       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6832         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6833         << SourceRange(D.getIdentifierLoc())
6834         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6835 
6836     SC = SC_None;
6837   }
6838   if (!D.isInvalidType()) {
6839     // Destructors don't have return types, but the parser will
6840     // happily parse something like:
6841     //
6842     //   class X {
6843     //     float ~X();
6844     //   };
6845     //
6846     // The return type will be eliminated later.
6847     if (D.getDeclSpec().hasTypeSpecifier())
6848       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6849         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6850         << SourceRange(D.getIdentifierLoc());
6851     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6852       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6853                                 SourceLocation(),
6854                                 D.getDeclSpec().getConstSpecLoc(),
6855                                 D.getDeclSpec().getVolatileSpecLoc(),
6856                                 D.getDeclSpec().getRestrictSpecLoc(),
6857                                 D.getDeclSpec().getAtomicSpecLoc());
6858       D.setInvalidType();
6859     }
6860   }
6861 
6862   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6863   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6864     if (FTI.TypeQuals & Qualifiers::Const)
6865       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6866         << "const" << SourceRange(D.getIdentifierLoc());
6867     if (FTI.TypeQuals & Qualifiers::Volatile)
6868       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6869         << "volatile" << SourceRange(D.getIdentifierLoc());
6870     if (FTI.TypeQuals & Qualifiers::Restrict)
6871       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6872         << "restrict" << SourceRange(D.getIdentifierLoc());
6873     D.setInvalidType();
6874   }
6875 
6876   // C++0x [class.dtor]p2:
6877   //   A destructor shall not be declared with a ref-qualifier.
6878   if (FTI.hasRefQualifier()) {
6879     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6880       << FTI.RefQualifierIsLValueRef
6881       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6882     D.setInvalidType();
6883   }
6884 
6885   // Make sure we don't have any parameters.
6886   if (FTIHasNonVoidParameters(FTI)) {
6887     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6888 
6889     // Delete the parameters.
6890     FTI.freeParams();
6891     D.setInvalidType();
6892   }
6893 
6894   // Make sure the destructor isn't variadic.
6895   if (FTI.isVariadic) {
6896     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6897     D.setInvalidType();
6898   }
6899 
6900   // Rebuild the function type "R" without any type qualifiers or
6901   // parameters (in case any of the errors above fired) and with
6902   // "void" as the return type, since destructors don't have return
6903   // types.
6904   if (!D.isInvalidType())
6905     return R;
6906 
6907   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6908   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6909   EPI.Variadic = false;
6910   EPI.TypeQuals = 0;
6911   EPI.RefQualifier = RQ_None;
6912   return Context.getFunctionType(Context.VoidTy, None, EPI);
6913 }
6914 
6915 static void extendLeft(SourceRange &R, const SourceRange &Before) {
6916   if (Before.isInvalid())
6917     return;
6918   R.setBegin(Before.getBegin());
6919   if (R.getEnd().isInvalid())
6920     R.setEnd(Before.getEnd());
6921 }
6922 
6923 static void extendRight(SourceRange &R, const SourceRange &After) {
6924   if (After.isInvalid())
6925     return;
6926   if (R.getBegin().isInvalid())
6927     R.setBegin(After.getBegin());
6928   R.setEnd(After.getEnd());
6929 }
6930 
6931 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6932 /// well-formednes of the conversion function declarator @p D with
6933 /// type @p R. If there are any errors in the declarator, this routine
6934 /// will emit diagnostics and return true. Otherwise, it will return
6935 /// false. Either way, the type @p R will be updated to reflect a
6936 /// well-formed type for the conversion operator.
6937 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6938                                      StorageClass& SC) {
6939   // C++ [class.conv.fct]p1:
6940   //   Neither parameter types nor return type can be specified. The
6941   //   type of a conversion function (8.3.5) is "function taking no
6942   //   parameter returning conversion-type-id."
6943   if (SC == SC_Static) {
6944     if (!D.isInvalidType())
6945       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6946         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6947         << D.getName().getSourceRange();
6948     D.setInvalidType();
6949     SC = SC_None;
6950   }
6951 
6952   TypeSourceInfo *ConvTSI = nullptr;
6953   QualType ConvType =
6954       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
6955 
6956   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6957     // Conversion functions don't have return types, but the parser will
6958     // happily parse something like:
6959     //
6960     //   class X {
6961     //     float operator bool();
6962     //   };
6963     //
6964     // The return type will be changed later anyway.
6965     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6966       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6967       << SourceRange(D.getIdentifierLoc());
6968     D.setInvalidType();
6969   }
6970 
6971   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6972 
6973   // Make sure we don't have any parameters.
6974   if (Proto->getNumParams() > 0) {
6975     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6976 
6977     // Delete the parameters.
6978     D.getFunctionTypeInfo().freeParams();
6979     D.setInvalidType();
6980   } else if (Proto->isVariadic()) {
6981     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6982     D.setInvalidType();
6983   }
6984 
6985   // Diagnose "&operator bool()" and other such nonsense.  This
6986   // is actually a gcc extension which we don't support.
6987   if (Proto->getReturnType() != ConvType) {
6988     bool NeedsTypedef = false;
6989     SourceRange Before, After;
6990 
6991     // Walk the chunks and extract information on them for our diagnostic.
6992     bool PastFunctionChunk = false;
6993     for (auto &Chunk : D.type_objects()) {
6994       switch (Chunk.Kind) {
6995       case DeclaratorChunk::Function:
6996         if (!PastFunctionChunk) {
6997           if (Chunk.Fun.HasTrailingReturnType) {
6998             TypeSourceInfo *TRT = nullptr;
6999             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7000             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7001           }
7002           PastFunctionChunk = true;
7003           break;
7004         }
7005         // Fall through.
7006       case DeclaratorChunk::Array:
7007         NeedsTypedef = true;
7008         extendRight(After, Chunk.getSourceRange());
7009         break;
7010 
7011       case DeclaratorChunk::Pointer:
7012       case DeclaratorChunk::BlockPointer:
7013       case DeclaratorChunk::Reference:
7014       case DeclaratorChunk::MemberPointer:
7015         extendLeft(Before, Chunk.getSourceRange());
7016         break;
7017 
7018       case DeclaratorChunk::Paren:
7019         extendLeft(Before, Chunk.Loc);
7020         extendRight(After, Chunk.EndLoc);
7021         break;
7022       }
7023     }
7024 
7025     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7026                          After.isValid()  ? After.getBegin() :
7027                                             D.getIdentifierLoc();
7028     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7029     DB << Before << After;
7030 
7031     if (!NeedsTypedef) {
7032       DB << /*don't need a typedef*/0;
7033 
7034       // If we can provide a correct fix-it hint, do so.
7035       if (After.isInvalid() && ConvTSI) {
7036         SourceLocation InsertLoc =
7037             PP.getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7038         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7039            << FixItHint::CreateInsertionFromRange(
7040                   InsertLoc, CharSourceRange::getTokenRange(Before))
7041            << FixItHint::CreateRemoval(Before);
7042       }
7043     } else if (!Proto->getReturnType()->isDependentType()) {
7044       DB << /*typedef*/1 << Proto->getReturnType();
7045     } else if (getLangOpts().CPlusPlus11) {
7046       DB << /*alias template*/2 << Proto->getReturnType();
7047     } else {
7048       DB << /*might not be fixable*/3;
7049     }
7050 
7051     // Recover by incorporating the other type chunks into the result type.
7052     // Note, this does *not* change the name of the function. This is compatible
7053     // with the GCC extension:
7054     //   struct S { &operator int(); } s;
7055     //   int &r = s.operator int(); // ok in GCC
7056     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7057     ConvType = Proto->getReturnType();
7058   }
7059 
7060   // C++ [class.conv.fct]p4:
7061   //   The conversion-type-id shall not represent a function type nor
7062   //   an array type.
7063   if (ConvType->isArrayType()) {
7064     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7065     ConvType = Context.getPointerType(ConvType);
7066     D.setInvalidType();
7067   } else if (ConvType->isFunctionType()) {
7068     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7069     ConvType = Context.getPointerType(ConvType);
7070     D.setInvalidType();
7071   }
7072 
7073   // Rebuild the function type "R" without any parameters (in case any
7074   // of the errors above fired) and with the conversion type as the
7075   // return type.
7076   if (D.isInvalidType())
7077     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7078 
7079   // C++0x explicit conversion operators.
7080   if (D.getDeclSpec().isExplicitSpecified())
7081     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7082          getLangOpts().CPlusPlus11 ?
7083            diag::warn_cxx98_compat_explicit_conversion_functions :
7084            diag::ext_explicit_conversion_functions)
7085       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7086 }
7087 
7088 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7089 /// the declaration of the given C++ conversion function. This routine
7090 /// is responsible for recording the conversion function in the C++
7091 /// class, if possible.
7092 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7093   assert(Conversion && "Expected to receive a conversion function declaration");
7094 
7095   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7096 
7097   // Make sure we aren't redeclaring the conversion function.
7098   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
7099 
7100   // C++ [class.conv.fct]p1:
7101   //   [...] A conversion function is never used to convert a
7102   //   (possibly cv-qualified) object to the (possibly cv-qualified)
7103   //   same object type (or a reference to it), to a (possibly
7104   //   cv-qualified) base class of that type (or a reference to it),
7105   //   or to (possibly cv-qualified) void.
7106   // FIXME: Suppress this warning if the conversion function ends up being a
7107   // virtual function that overrides a virtual function in a base class.
7108   QualType ClassType
7109     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7110   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
7111     ConvType = ConvTypeRef->getPointeeType();
7112   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
7113       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
7114     /* Suppress diagnostics for instantiations. */;
7115   else if (ConvType->isRecordType()) {
7116     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
7117     if (ConvType == ClassType)
7118       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
7119         << ClassType;
7120     else if (IsDerivedFrom(ClassType, ConvType))
7121       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
7122         <<  ClassType << ConvType;
7123   } else if (ConvType->isVoidType()) {
7124     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
7125       << ClassType << ConvType;
7126   }
7127 
7128   if (FunctionTemplateDecl *ConversionTemplate
7129                                 = Conversion->getDescribedFunctionTemplate())
7130     return ConversionTemplate;
7131 
7132   return Conversion;
7133 }
7134 
7135 //===----------------------------------------------------------------------===//
7136 // Namespace Handling
7137 //===----------------------------------------------------------------------===//
7138 
7139 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
7140 /// reopened.
7141 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
7142                                             SourceLocation Loc,
7143                                             IdentifierInfo *II, bool *IsInline,
7144                                             NamespaceDecl *PrevNS) {
7145   assert(*IsInline != PrevNS->isInline());
7146 
7147   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
7148   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
7149   // inline namespaces, with the intention of bringing names into namespace std.
7150   //
7151   // We support this just well enough to get that case working; this is not
7152   // sufficient to support reopening namespaces as inline in general.
7153   if (*IsInline && II && II->getName().startswith("__atomic") &&
7154       S.getSourceManager().isInSystemHeader(Loc)) {
7155     // Mark all prior declarations of the namespace as inline.
7156     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
7157          NS = NS->getPreviousDecl())
7158       NS->setInline(*IsInline);
7159     // Patch up the lookup table for the containing namespace. This isn't really
7160     // correct, but it's good enough for this particular case.
7161     for (auto *I : PrevNS->decls())
7162       if (auto *ND = dyn_cast<NamedDecl>(I))
7163         PrevNS->getParent()->makeDeclVisibleInContext(ND);
7164     return;
7165   }
7166 
7167   if (PrevNS->isInline())
7168     // The user probably just forgot the 'inline', so suggest that it
7169     // be added back.
7170     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
7171       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
7172   else
7173     S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
7174 
7175   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
7176   *IsInline = PrevNS->isInline();
7177 }
7178 
7179 /// ActOnStartNamespaceDef - This is called at the start of a namespace
7180 /// definition.
7181 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
7182                                    SourceLocation InlineLoc,
7183                                    SourceLocation NamespaceLoc,
7184                                    SourceLocation IdentLoc,
7185                                    IdentifierInfo *II,
7186                                    SourceLocation LBrace,
7187                                    AttributeList *AttrList) {
7188   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
7189   // For anonymous namespace, take the location of the left brace.
7190   SourceLocation Loc = II ? IdentLoc : LBrace;
7191   bool IsInline = InlineLoc.isValid();
7192   bool IsInvalid = false;
7193   bool IsStd = false;
7194   bool AddToKnown = false;
7195   Scope *DeclRegionScope = NamespcScope->getParent();
7196 
7197   NamespaceDecl *PrevNS = nullptr;
7198   if (II) {
7199     // C++ [namespace.def]p2:
7200     //   The identifier in an original-namespace-definition shall not
7201     //   have been previously defined in the declarative region in
7202     //   which the original-namespace-definition appears. The
7203     //   identifier in an original-namespace-definition is the name of
7204     //   the namespace. Subsequently in that declarative region, it is
7205     //   treated as an original-namespace-name.
7206     //
7207     // Since namespace names are unique in their scope, and we don't
7208     // look through using directives, just look for any ordinary names.
7209 
7210     const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
7211     Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7212     Decl::IDNS_Namespace;
7213     NamedDecl *PrevDecl = nullptr;
7214     DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7215     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7216          ++I) {
7217       if ((*I)->getIdentifierNamespace() & IDNS) {
7218         PrevDecl = *I;
7219         break;
7220       }
7221     }
7222 
7223     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7224 
7225     if (PrevNS) {
7226       // This is an extended namespace definition.
7227       if (IsInline != PrevNS->isInline())
7228         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7229                                         &IsInline, PrevNS);
7230     } else if (PrevDecl) {
7231       // This is an invalid name redefinition.
7232       Diag(Loc, diag::err_redefinition_different_kind)
7233         << II;
7234       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7235       IsInvalid = true;
7236       // Continue on to push Namespc as current DeclContext and return it.
7237     } else if (II->isStr("std") &&
7238                CurContext->getRedeclContext()->isTranslationUnit()) {
7239       // This is the first "real" definition of the namespace "std", so update
7240       // our cache of the "std" namespace to point at this definition.
7241       PrevNS = getStdNamespace();
7242       IsStd = true;
7243       AddToKnown = !IsInline;
7244     } else {
7245       // We've seen this namespace for the first time.
7246       AddToKnown = !IsInline;
7247     }
7248   } else {
7249     // Anonymous namespaces.
7250 
7251     // Determine whether the parent already has an anonymous namespace.
7252     DeclContext *Parent = CurContext->getRedeclContext();
7253     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7254       PrevNS = TU->getAnonymousNamespace();
7255     } else {
7256       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
7257       PrevNS = ND->getAnonymousNamespace();
7258     }
7259 
7260     if (PrevNS && IsInline != PrevNS->isInline())
7261       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7262                                       &IsInline, PrevNS);
7263   }
7264 
7265   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7266                                                  StartLoc, Loc, II, PrevNS);
7267   if (IsInvalid)
7268     Namespc->setInvalidDecl();
7269 
7270   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
7271 
7272   // FIXME: Should we be merging attributes?
7273   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
7274     PushNamespaceVisibilityAttr(Attr, Loc);
7275 
7276   if (IsStd)
7277     StdNamespace = Namespc;
7278   if (AddToKnown)
7279     KnownNamespaces[Namespc] = false;
7280 
7281   if (II) {
7282     PushOnScopeChains(Namespc, DeclRegionScope);
7283   } else {
7284     // Link the anonymous namespace into its parent.
7285     DeclContext *Parent = CurContext->getRedeclContext();
7286     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7287       TU->setAnonymousNamespace(Namespc);
7288     } else {
7289       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
7290     }
7291 
7292     CurContext->addDecl(Namespc);
7293 
7294     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
7295     //   behaves as if it were replaced by
7296     //     namespace unique { /* empty body */ }
7297     //     using namespace unique;
7298     //     namespace unique { namespace-body }
7299     //   where all occurrences of 'unique' in a translation unit are
7300     //   replaced by the same identifier and this identifier differs
7301     //   from all other identifiers in the entire program.
7302 
7303     // We just create the namespace with an empty name and then add an
7304     // implicit using declaration, just like the standard suggests.
7305     //
7306     // CodeGen enforces the "universally unique" aspect by giving all
7307     // declarations semantically contained within an anonymous
7308     // namespace internal linkage.
7309 
7310     if (!PrevNS) {
7311       UsingDirectiveDecl* UD
7312         = UsingDirectiveDecl::Create(Context, Parent,
7313                                      /* 'using' */ LBrace,
7314                                      /* 'namespace' */ SourceLocation(),
7315                                      /* qualifier */ NestedNameSpecifierLoc(),
7316                                      /* identifier */ SourceLocation(),
7317                                      Namespc,
7318                                      /* Ancestor */ Parent);
7319       UD->setImplicit();
7320       Parent->addDecl(UD);
7321     }
7322   }
7323 
7324   ActOnDocumentableDecl(Namespc);
7325 
7326   // Although we could have an invalid decl (i.e. the namespace name is a
7327   // redefinition), push it as current DeclContext and try to continue parsing.
7328   // FIXME: We should be able to push Namespc here, so that the each DeclContext
7329   // for the namespace has the declarations that showed up in that particular
7330   // namespace definition.
7331   PushDeclContext(NamespcScope, Namespc);
7332   return Namespc;
7333 }
7334 
7335 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7336 /// is a namespace alias, returns the namespace it points to.
7337 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7338   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7339     return AD->getNamespace();
7340   return dyn_cast_or_null<NamespaceDecl>(D);
7341 }
7342 
7343 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
7344 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
7345 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
7346   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7347   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
7348   Namespc->setRBraceLoc(RBrace);
7349   PopDeclContext();
7350   if (Namespc->hasAttr<VisibilityAttr>())
7351     PopPragmaVisibility(true, RBrace);
7352 }
7353 
7354 CXXRecordDecl *Sema::getStdBadAlloc() const {
7355   return cast_or_null<CXXRecordDecl>(
7356                                   StdBadAlloc.get(Context.getExternalSource()));
7357 }
7358 
7359 NamespaceDecl *Sema::getStdNamespace() const {
7360   return cast_or_null<NamespaceDecl>(
7361                                  StdNamespace.get(Context.getExternalSource()));
7362 }
7363 
7364 /// \brief Retrieve the special "std" namespace, which may require us to
7365 /// implicitly define the namespace.
7366 NamespaceDecl *Sema::getOrCreateStdNamespace() {
7367   if (!StdNamespace) {
7368     // The "std" namespace has not yet been defined, so build one implicitly.
7369     StdNamespace = NamespaceDecl::Create(Context,
7370                                          Context.getTranslationUnitDecl(),
7371                                          /*Inline=*/false,
7372                                          SourceLocation(), SourceLocation(),
7373                                          &PP.getIdentifierTable().get("std"),
7374                                          /*PrevDecl=*/nullptr);
7375     getStdNamespace()->setImplicit(true);
7376   }
7377 
7378   return getStdNamespace();
7379 }
7380 
7381 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
7382   assert(getLangOpts().CPlusPlus &&
7383          "Looking for std::initializer_list outside of C++.");
7384 
7385   // We're looking for implicit instantiations of
7386   // template <typename E> class std::initializer_list.
7387 
7388   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7389     return false;
7390 
7391   ClassTemplateDecl *Template = nullptr;
7392   const TemplateArgument *Arguments = nullptr;
7393 
7394   if (const RecordType *RT = Ty->getAs<RecordType>()) {
7395 
7396     ClassTemplateSpecializationDecl *Specialization =
7397         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7398     if (!Specialization)
7399       return false;
7400 
7401     Template = Specialization->getSpecializedTemplate();
7402     Arguments = Specialization->getTemplateArgs().data();
7403   } else if (const TemplateSpecializationType *TST =
7404                  Ty->getAs<TemplateSpecializationType>()) {
7405     Template = dyn_cast_or_null<ClassTemplateDecl>(
7406         TST->getTemplateName().getAsTemplateDecl());
7407     Arguments = TST->getArgs();
7408   }
7409   if (!Template)
7410     return false;
7411 
7412   if (!StdInitializerList) {
7413     // Haven't recognized std::initializer_list yet, maybe this is it.
7414     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7415     if (TemplateClass->getIdentifier() !=
7416             &PP.getIdentifierTable().get("initializer_list") ||
7417         !getStdNamespace()->InEnclosingNamespaceSetOf(
7418             TemplateClass->getDeclContext()))
7419       return false;
7420     // This is a template called std::initializer_list, but is it the right
7421     // template?
7422     TemplateParameterList *Params = Template->getTemplateParameters();
7423     if (Params->getMinRequiredArguments() != 1)
7424       return false;
7425     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7426       return false;
7427 
7428     // It's the right template.
7429     StdInitializerList = Template;
7430   }
7431 
7432   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
7433     return false;
7434 
7435   // This is an instance of std::initializer_list. Find the argument type.
7436   if (Element)
7437     *Element = Arguments[0].getAsType();
7438   return true;
7439 }
7440 
7441 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7442   NamespaceDecl *Std = S.getStdNamespace();
7443   if (!Std) {
7444     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7445     return nullptr;
7446   }
7447 
7448   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7449                       Loc, Sema::LookupOrdinaryName);
7450   if (!S.LookupQualifiedName(Result, Std)) {
7451     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
7452     return nullptr;
7453   }
7454   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7455   if (!Template) {
7456     Result.suppressDiagnostics();
7457     // We found something weird. Complain about the first thing we found.
7458     NamedDecl *Found = *Result.begin();
7459     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
7460     return nullptr;
7461   }
7462 
7463   // We found some template called std::initializer_list. Now verify that it's
7464   // correct.
7465   TemplateParameterList *Params = Template->getTemplateParameters();
7466   if (Params->getMinRequiredArguments() != 1 ||
7467       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
7468     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
7469     return nullptr;
7470   }
7471 
7472   return Template;
7473 }
7474 
7475 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7476   if (!StdInitializerList) {
7477     StdInitializerList = LookupStdInitializerList(*this, Loc);
7478     if (!StdInitializerList)
7479       return QualType();
7480   }
7481 
7482   TemplateArgumentListInfo Args(Loc, Loc);
7483   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7484                                        Context.getTrivialTypeSourceInfo(Element,
7485                                                                         Loc)));
7486   return Context.getCanonicalType(
7487       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7488 }
7489 
7490 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7491   // C++ [dcl.init.list]p2:
7492   //   A constructor is an initializer-list constructor if its first parameter
7493   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
7494   //   std::initializer_list<E> for some type E, and either there are no other
7495   //   parameters or else all other parameters have default arguments.
7496   if (Ctor->getNumParams() < 1 ||
7497       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7498     return false;
7499 
7500   QualType ArgType = Ctor->getParamDecl(0)->getType();
7501   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7502     ArgType = RT->getPointeeType().getUnqualifiedType();
7503 
7504   return isStdInitializerList(ArgType, nullptr);
7505 }
7506 
7507 /// \brief Determine whether a using statement is in a context where it will be
7508 /// apply in all contexts.
7509 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7510   switch (CurContext->getDeclKind()) {
7511     case Decl::TranslationUnit:
7512       return true;
7513     case Decl::LinkageSpec:
7514       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7515     default:
7516       return false;
7517   }
7518 }
7519 
7520 namespace {
7521 
7522 // Callback to only accept typo corrections that are namespaces.
7523 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
7524 public:
7525   bool ValidateCandidate(const TypoCorrection &candidate) override {
7526     if (NamedDecl *ND = candidate.getCorrectionDecl())
7527       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
7528     return false;
7529   }
7530 };
7531 
7532 }
7533 
7534 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7535                                        CXXScopeSpec &SS,
7536                                        SourceLocation IdentLoc,
7537                                        IdentifierInfo *Ident) {
7538   R.clear();
7539   if (TypoCorrection Corrected =
7540           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7541                         llvm::make_unique<NamespaceValidatorCCC>(),
7542                         Sema::CTK_ErrorRecovery)) {
7543     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
7544       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7545       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
7546                               Ident->getName().equals(CorrectedStr);
7547       S.diagnoseTypo(Corrected,
7548                      S.PDiag(diag::err_using_directive_member_suggest)
7549                        << Ident << DC << DroppedSpecifier << SS.getRange(),
7550                      S.PDiag(diag::note_namespace_defined_here));
7551     } else {
7552       S.diagnoseTypo(Corrected,
7553                      S.PDiag(diag::err_using_directive_suggest) << Ident,
7554                      S.PDiag(diag::note_namespace_defined_here));
7555     }
7556     R.addDecl(Corrected.getCorrectionDecl());
7557     return true;
7558   }
7559   return false;
7560 }
7561 
7562 Decl *Sema::ActOnUsingDirective(Scope *S,
7563                                           SourceLocation UsingLoc,
7564                                           SourceLocation NamespcLoc,
7565                                           CXXScopeSpec &SS,
7566                                           SourceLocation IdentLoc,
7567                                           IdentifierInfo *NamespcName,
7568                                           AttributeList *AttrList) {
7569   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7570   assert(NamespcName && "Invalid NamespcName.");
7571   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
7572 
7573   // This can only happen along a recovery path.
7574   while (S->getFlags() & Scope::TemplateParamScope)
7575     S = S->getParent();
7576   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7577 
7578   UsingDirectiveDecl *UDir = nullptr;
7579   NestedNameSpecifier *Qualifier = nullptr;
7580   if (SS.isSet())
7581     Qualifier = SS.getScopeRep();
7582 
7583   // Lookup namespace name.
7584   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7585   LookupParsedName(R, S, &SS);
7586   if (R.isAmbiguous())
7587     return nullptr;
7588 
7589   if (R.empty()) {
7590     R.clear();
7591     // Allow "using namespace std;" or "using namespace ::std;" even if
7592     // "std" hasn't been defined yet, for GCC compatibility.
7593     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7594         NamespcName->isStr("std")) {
7595       Diag(IdentLoc, diag::ext_using_undefined_std);
7596       R.addDecl(getOrCreateStdNamespace());
7597       R.resolveKind();
7598     }
7599     // Otherwise, attempt typo correction.
7600     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
7601   }
7602 
7603   if (!R.empty()) {
7604     NamedDecl *Named = R.getFoundDecl();
7605     assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7606         && "expected namespace decl");
7607 
7608     // The use of a nested name specifier may trigger deprecation warnings.
7609     DiagnoseUseOfDecl(Named, IdentLoc);
7610 
7611     // C++ [namespace.udir]p1:
7612     //   A using-directive specifies that the names in the nominated
7613     //   namespace can be used in the scope in which the
7614     //   using-directive appears after the using-directive. During
7615     //   unqualified name lookup (3.4.1), the names appear as if they
7616     //   were declared in the nearest enclosing namespace which
7617     //   contains both the using-directive and the nominated
7618     //   namespace. [Note: in this context, "contains" means "contains
7619     //   directly or indirectly". ]
7620 
7621     // Find enclosing context containing both using-directive and
7622     // nominated namespace.
7623     NamespaceDecl *NS = getNamespaceDecl(Named);
7624     DeclContext *CommonAncestor = cast<DeclContext>(NS);
7625     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7626       CommonAncestor = CommonAncestor->getParent();
7627 
7628     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
7629                                       SS.getWithLocInContext(Context),
7630                                       IdentLoc, Named, CommonAncestor);
7631 
7632     if (IsUsingDirectiveInToplevelContext(CurContext) &&
7633         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
7634       Diag(IdentLoc, diag::warn_using_directive_in_header);
7635     }
7636 
7637     PushUsingDirective(S, UDir);
7638   } else {
7639     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7640   }
7641 
7642   if (UDir)
7643     ProcessDeclAttributeList(S, UDir, AttrList);
7644 
7645   return UDir;
7646 }
7647 
7648 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
7649   // If the scope has an associated entity and the using directive is at
7650   // namespace or translation unit scope, add the UsingDirectiveDecl into
7651   // its lookup structure so qualified name lookup can find it.
7652   DeclContext *Ctx = S->getEntity();
7653   if (Ctx && !Ctx->isFunctionOrMethod())
7654     Ctx->addDecl(UDir);
7655   else
7656     // Otherwise, it is at block scope. The using-directives will affect lookup
7657     // only to the end of the scope.
7658     S->PushUsingDirective(UDir);
7659 }
7660 
7661 
7662 Decl *Sema::ActOnUsingDeclaration(Scope *S,
7663                                   AccessSpecifier AS,
7664                                   bool HasUsingKeyword,
7665                                   SourceLocation UsingLoc,
7666                                   CXXScopeSpec &SS,
7667                                   UnqualifiedId &Name,
7668                                   AttributeList *AttrList,
7669                                   bool HasTypenameKeyword,
7670                                   SourceLocation TypenameLoc) {
7671   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
7672 
7673   switch (Name.getKind()) {
7674   case UnqualifiedId::IK_ImplicitSelfParam:
7675   case UnqualifiedId::IK_Identifier:
7676   case UnqualifiedId::IK_OperatorFunctionId:
7677   case UnqualifiedId::IK_LiteralOperatorId:
7678   case UnqualifiedId::IK_ConversionFunctionId:
7679     break;
7680 
7681   case UnqualifiedId::IK_ConstructorName:
7682   case UnqualifiedId::IK_ConstructorTemplateId:
7683     // C++11 inheriting constructors.
7684     Diag(Name.getLocStart(),
7685          getLangOpts().CPlusPlus11 ?
7686            diag::warn_cxx98_compat_using_decl_constructor :
7687            diag::err_using_decl_constructor)
7688       << SS.getRange();
7689 
7690     if (getLangOpts().CPlusPlus11) break;
7691 
7692     return nullptr;
7693 
7694   case UnqualifiedId::IK_DestructorName:
7695     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
7696       << SS.getRange();
7697     return nullptr;
7698 
7699   case UnqualifiedId::IK_TemplateId:
7700     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
7701       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
7702     return nullptr;
7703   }
7704 
7705   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7706   DeclarationName TargetName = TargetNameInfo.getName();
7707   if (!TargetName)
7708     return nullptr;
7709 
7710   // Warn about access declarations.
7711   if (!HasUsingKeyword) {
7712     Diag(Name.getLocStart(),
7713          getLangOpts().CPlusPlus11 ? diag::err_access_decl
7714                                    : diag::warn_access_decl_deprecated)
7715       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7716   }
7717 
7718   if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7719       DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7720     return nullptr;
7721 
7722   NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7723                                         TargetNameInfo, AttrList,
7724                                         /* IsInstantiation */ false,
7725                                         HasTypenameKeyword, TypenameLoc);
7726   if (UD)
7727     PushOnScopeChains(UD, S, /*AddToContext*/ false);
7728 
7729   return UD;
7730 }
7731 
7732 /// \brief Determine whether a using declaration considers the given
7733 /// declarations as "equivalent", e.g., if they are redeclarations of
7734 /// the same entity or are both typedefs of the same type.
7735 static bool
7736 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7737   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7738     return true;
7739 
7740   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7741     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7742       return Context.hasSameType(TD1->getUnderlyingType(),
7743                                  TD2->getUnderlyingType());
7744 
7745   return false;
7746 }
7747 
7748 
7749 /// Determines whether to create a using shadow decl for a particular
7750 /// decl, given the set of decls existing prior to this using lookup.
7751 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7752                                 const LookupResult &Previous,
7753                                 UsingShadowDecl *&PrevShadow) {
7754   // Diagnose finding a decl which is not from a base class of the
7755   // current class.  We do this now because there are cases where this
7756   // function will silently decide not to build a shadow decl, which
7757   // will pre-empt further diagnostics.
7758   //
7759   // We don't need to do this in C++0x because we do the check once on
7760   // the qualifier.
7761   //
7762   // FIXME: diagnose the following if we care enough:
7763   //   struct A { int foo; };
7764   //   struct B : A { using A::foo; };
7765   //   template <class T> struct C : A {};
7766   //   template <class T> struct D : C<T> { using B::foo; } // <---
7767   // This is invalid (during instantiation) in C++03 because B::foo
7768   // resolves to the using decl in B, which is not a base class of D<T>.
7769   // We can't diagnose it immediately because C<T> is an unknown
7770   // specialization.  The UsingShadowDecl in D<T> then points directly
7771   // to A::foo, which will look well-formed when we instantiate.
7772   // The right solution is to not collapse the shadow-decl chain.
7773   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7774     DeclContext *OrigDC = Orig->getDeclContext();
7775 
7776     // Handle enums and anonymous structs.
7777     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7778     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7779     while (OrigRec->isAnonymousStructOrUnion())
7780       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7781 
7782     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7783       if (OrigDC == CurContext) {
7784         Diag(Using->getLocation(),
7785              diag::err_using_decl_nested_name_specifier_is_current_class)
7786           << Using->getQualifierLoc().getSourceRange();
7787         Diag(Orig->getLocation(), diag::note_using_decl_target);
7788         return true;
7789       }
7790 
7791       Diag(Using->getQualifierLoc().getBeginLoc(),
7792            diag::err_using_decl_nested_name_specifier_is_not_base_class)
7793         << Using->getQualifier()
7794         << cast<CXXRecordDecl>(CurContext)
7795         << Using->getQualifierLoc().getSourceRange();
7796       Diag(Orig->getLocation(), diag::note_using_decl_target);
7797       return true;
7798     }
7799   }
7800 
7801   if (Previous.empty()) return false;
7802 
7803   NamedDecl *Target = Orig;
7804   if (isa<UsingShadowDecl>(Target))
7805     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7806 
7807   // If the target happens to be one of the previous declarations, we
7808   // don't have a conflict.
7809   //
7810   // FIXME: but we might be increasing its access, in which case we
7811   // should redeclare it.
7812   NamedDecl *NonTag = nullptr, *Tag = nullptr;
7813   bool FoundEquivalentDecl = false;
7814   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7815          I != E; ++I) {
7816     NamedDecl *D = (*I)->getUnderlyingDecl();
7817     if (IsEquivalentForUsingDecl(Context, D, Target)) {
7818       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7819         PrevShadow = Shadow;
7820       FoundEquivalentDecl = true;
7821     }
7822 
7823     (isa<TagDecl>(D) ? Tag : NonTag) = D;
7824   }
7825 
7826   if (FoundEquivalentDecl)
7827     return false;
7828 
7829   if (FunctionDecl *FD = Target->getAsFunction()) {
7830     NamedDecl *OldDecl = nullptr;
7831     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7832                           /*IsForUsingDecl*/ true)) {
7833     case Ovl_Overload:
7834       return false;
7835 
7836     case Ovl_NonFunction:
7837       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7838       break;
7839 
7840     // We found a decl with the exact signature.
7841     case Ovl_Match:
7842       // If we're in a record, we want to hide the target, so we
7843       // return true (without a diagnostic) to tell the caller not to
7844       // build a shadow decl.
7845       if (CurContext->isRecord())
7846         return true;
7847 
7848       // If we're not in a record, this is an error.
7849       Diag(Using->getLocation(), diag::err_using_decl_conflict);
7850       break;
7851     }
7852 
7853     Diag(Target->getLocation(), diag::note_using_decl_target);
7854     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7855     return true;
7856   }
7857 
7858   // Target is not a function.
7859 
7860   if (isa<TagDecl>(Target)) {
7861     // No conflict between a tag and a non-tag.
7862     if (!Tag) return false;
7863 
7864     Diag(Using->getLocation(), diag::err_using_decl_conflict);
7865     Diag(Target->getLocation(), diag::note_using_decl_target);
7866     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7867     return true;
7868   }
7869 
7870   // No conflict between a tag and a non-tag.
7871   if (!NonTag) return false;
7872 
7873   Diag(Using->getLocation(), diag::err_using_decl_conflict);
7874   Diag(Target->getLocation(), diag::note_using_decl_target);
7875   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7876   return true;
7877 }
7878 
7879 /// Builds a shadow declaration corresponding to a 'using' declaration.
7880 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7881                                             UsingDecl *UD,
7882                                             NamedDecl *Orig,
7883                                             UsingShadowDecl *PrevDecl) {
7884 
7885   // If we resolved to another shadow declaration, just coalesce them.
7886   NamedDecl *Target = Orig;
7887   if (isa<UsingShadowDecl>(Target)) {
7888     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7889     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7890   }
7891 
7892   UsingShadowDecl *Shadow
7893     = UsingShadowDecl::Create(Context, CurContext,
7894                               UD->getLocation(), UD, Target);
7895   UD->addShadowDecl(Shadow);
7896 
7897   Shadow->setAccess(UD->getAccess());
7898   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7899     Shadow->setInvalidDecl();
7900 
7901   Shadow->setPreviousDecl(PrevDecl);
7902 
7903   if (S)
7904     PushOnScopeChains(Shadow, S);
7905   else
7906     CurContext->addDecl(Shadow);
7907 
7908 
7909   return Shadow;
7910 }
7911 
7912 /// Hides a using shadow declaration.  This is required by the current
7913 /// using-decl implementation when a resolvable using declaration in a
7914 /// class is followed by a declaration which would hide or override
7915 /// one or more of the using decl's targets; for example:
7916 ///
7917 ///   struct Base { void foo(int); };
7918 ///   struct Derived : Base {
7919 ///     using Base::foo;
7920 ///     void foo(int);
7921 ///   };
7922 ///
7923 /// The governing language is C++03 [namespace.udecl]p12:
7924 ///
7925 ///   When a using-declaration brings names from a base class into a
7926 ///   derived class scope, member functions in the derived class
7927 ///   override and/or hide member functions with the same name and
7928 ///   parameter types in a base class (rather than conflicting).
7929 ///
7930 /// There are two ways to implement this:
7931 ///   (1) optimistically create shadow decls when they're not hidden
7932 ///       by existing declarations, or
7933 ///   (2) don't create any shadow decls (or at least don't make them
7934 ///       visible) until we've fully parsed/instantiated the class.
7935 /// The problem with (1) is that we might have to retroactively remove
7936 /// a shadow decl, which requires several O(n) operations because the
7937 /// decl structures are (very reasonably) not designed for removal.
7938 /// (2) avoids this but is very fiddly and phase-dependent.
7939 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7940   if (Shadow->getDeclName().getNameKind() ==
7941         DeclarationName::CXXConversionFunctionName)
7942     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7943 
7944   // Remove it from the DeclContext...
7945   Shadow->getDeclContext()->removeDecl(Shadow);
7946 
7947   // ...and the scope, if applicable...
7948   if (S) {
7949     S->RemoveDecl(Shadow);
7950     IdResolver.RemoveDecl(Shadow);
7951   }
7952 
7953   // ...and the using decl.
7954   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7955 
7956   // TODO: complain somehow if Shadow was used.  It shouldn't
7957   // be possible for this to happen, because...?
7958 }
7959 
7960 /// Find the base specifier for a base class with the given type.
7961 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7962                                                 QualType DesiredBase,
7963                                                 bool &AnyDependentBases) {
7964   // Check whether the named type is a direct base class.
7965   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7966   for (auto &Base : Derived->bases()) {
7967     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7968     if (CanonicalDesiredBase == BaseType)
7969       return &Base;
7970     if (BaseType->isDependentType())
7971       AnyDependentBases = true;
7972   }
7973   return nullptr;
7974 }
7975 
7976 namespace {
7977 class UsingValidatorCCC : public CorrectionCandidateCallback {
7978 public:
7979   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7980                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
7981       : HasTypenameKeyword(HasTypenameKeyword),
7982         IsInstantiation(IsInstantiation), OldNNS(NNS),
7983         RequireMemberOf(RequireMemberOf) {}
7984 
7985   bool ValidateCandidate(const TypoCorrection &Candidate) override {
7986     NamedDecl *ND = Candidate.getCorrectionDecl();
7987 
7988     // Keywords are not valid here.
7989     if (!ND || isa<NamespaceDecl>(ND))
7990       return false;
7991 
7992     // Completely unqualified names are invalid for a 'using' declaration.
7993     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7994       return false;
7995 
7996     if (RequireMemberOf) {
7997       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7998       if (FoundRecord && FoundRecord->isInjectedClassName()) {
7999         // No-one ever wants a using-declaration to name an injected-class-name
8000         // of a base class, unless they're declaring an inheriting constructor.
8001         ASTContext &Ctx = ND->getASTContext();
8002         if (!Ctx.getLangOpts().CPlusPlus11)
8003           return false;
8004         QualType FoundType = Ctx.getRecordType(FoundRecord);
8005 
8006         // Check that the injected-class-name is named as a member of its own
8007         // type; we don't want to suggest 'using Derived::Base;', since that
8008         // means something else.
8009         NestedNameSpecifier *Specifier =
8010             Candidate.WillReplaceSpecifier()
8011                 ? Candidate.getCorrectionSpecifier()
8012                 : OldNNS;
8013         if (!Specifier->getAsType() ||
8014             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8015           return false;
8016 
8017         // Check that this inheriting constructor declaration actually names a
8018         // direct base class of the current class.
8019         bool AnyDependentBases = false;
8020         if (!findDirectBaseWithType(RequireMemberOf,
8021                                     Ctx.getRecordType(FoundRecord),
8022                                     AnyDependentBases) &&
8023             !AnyDependentBases)
8024           return false;
8025       } else {
8026         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
8027         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
8028           return false;
8029 
8030         // FIXME: Check that the base class member is accessible?
8031       }
8032     }
8033 
8034     if (isa<TypeDecl>(ND))
8035       return HasTypenameKeyword || !IsInstantiation;
8036 
8037     return !HasTypenameKeyword;
8038   }
8039 
8040 private:
8041   bool HasTypenameKeyword;
8042   bool IsInstantiation;
8043   NestedNameSpecifier *OldNNS;
8044   CXXRecordDecl *RequireMemberOf;
8045 };
8046 } // end anonymous namespace
8047 
8048 /// Builds a using declaration.
8049 ///
8050 /// \param IsInstantiation - Whether this call arises from an
8051 ///   instantiation of an unresolved using declaration.  We treat
8052 ///   the lookup differently for these declarations.
8053 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
8054                                        SourceLocation UsingLoc,
8055                                        CXXScopeSpec &SS,
8056                                        DeclarationNameInfo NameInfo,
8057                                        AttributeList *AttrList,
8058                                        bool IsInstantiation,
8059                                        bool HasTypenameKeyword,
8060                                        SourceLocation TypenameLoc) {
8061   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8062   SourceLocation IdentLoc = NameInfo.getLoc();
8063   assert(IdentLoc.isValid() && "Invalid TargetName location.");
8064 
8065   // FIXME: We ignore attributes for now.
8066 
8067   if (SS.isEmpty()) {
8068     Diag(IdentLoc, diag::err_using_requires_qualname);
8069     return nullptr;
8070   }
8071 
8072   // Do the redeclaration lookup in the current scope.
8073   LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
8074                         ForRedeclaration);
8075   Previous.setHideTags(false);
8076   if (S) {
8077     LookupName(Previous, S);
8078 
8079     // It is really dumb that we have to do this.
8080     LookupResult::Filter F = Previous.makeFilter();
8081     while (F.hasNext()) {
8082       NamedDecl *D = F.next();
8083       if (!isDeclInScope(D, CurContext, S))
8084         F.erase();
8085       // If we found a local extern declaration that's not ordinarily visible,
8086       // and this declaration is being added to a non-block scope, ignore it.
8087       // We're only checking for scope conflicts here, not also for violations
8088       // of the linkage rules.
8089       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
8090                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
8091         F.erase();
8092     }
8093     F.done();
8094   } else {
8095     assert(IsInstantiation && "no scope in non-instantiation");
8096     assert(CurContext->isRecord() && "scope not record in instantiation");
8097     LookupQualifiedName(Previous, CurContext);
8098   }
8099 
8100   // Check for invalid redeclarations.
8101   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
8102                                   SS, IdentLoc, Previous))
8103     return nullptr;
8104 
8105   // Check for bad qualifiers.
8106   if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
8107     return nullptr;
8108 
8109   DeclContext *LookupContext = computeDeclContext(SS);
8110   NamedDecl *D;
8111   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8112   if (!LookupContext) {
8113     if (HasTypenameKeyword) {
8114       // FIXME: not all declaration name kinds are legal here
8115       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
8116                                               UsingLoc, TypenameLoc,
8117                                               QualifierLoc,
8118                                               IdentLoc, NameInfo.getName());
8119     } else {
8120       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
8121                                            QualifierLoc, NameInfo);
8122     }
8123     D->setAccess(AS);
8124     CurContext->addDecl(D);
8125     return D;
8126   }
8127 
8128   auto Build = [&](bool Invalid) {
8129     UsingDecl *UD =
8130         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
8131                           HasTypenameKeyword);
8132     UD->setAccess(AS);
8133     CurContext->addDecl(UD);
8134     UD->setInvalidDecl(Invalid);
8135     return UD;
8136   };
8137   auto BuildInvalid = [&]{ return Build(true); };
8138   auto BuildValid = [&]{ return Build(false); };
8139 
8140   if (RequireCompleteDeclContext(SS, LookupContext))
8141     return BuildInvalid();
8142 
8143   // Look up the target name.
8144   LookupResult R(*this, NameInfo, LookupOrdinaryName);
8145 
8146   // Unlike most lookups, we don't always want to hide tag
8147   // declarations: tag names are visible through the using declaration
8148   // even if hidden by ordinary names, *except* in a dependent context
8149   // where it's important for the sanity of two-phase lookup.
8150   if (!IsInstantiation)
8151     R.setHideTags(false);
8152 
8153   // For the purposes of this lookup, we have a base object type
8154   // equal to that of the current context.
8155   if (CurContext->isRecord()) {
8156     R.setBaseObjectType(
8157                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
8158   }
8159 
8160   LookupQualifiedName(R, LookupContext);
8161 
8162   // Try to correct typos if possible. If constructor name lookup finds no
8163   // results, that means the named class has no explicit constructors, and we
8164   // suppressed declaring implicit ones (probably because it's dependent or
8165   // invalid).
8166   if (R.empty() &&
8167       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
8168     if (TypoCorrection Corrected = CorrectTypo(
8169             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
8170             llvm::make_unique<UsingValidatorCCC>(
8171                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
8172                 dyn_cast<CXXRecordDecl>(CurContext)),
8173             CTK_ErrorRecovery)) {
8174       // We reject any correction for which ND would be NULL.
8175       NamedDecl *ND = Corrected.getCorrectionDecl();
8176 
8177       // We reject candidates where DroppedSpecifier == true, hence the
8178       // literal '0' below.
8179       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
8180                                 << NameInfo.getName() << LookupContext << 0
8181                                 << SS.getRange());
8182 
8183       // If we corrected to an inheriting constructor, handle it as one.
8184       auto *RD = dyn_cast<CXXRecordDecl>(ND);
8185       if (RD && RD->isInjectedClassName()) {
8186         // Fix up the information we'll use to build the using declaration.
8187         if (Corrected.WillReplaceSpecifier()) {
8188           NestedNameSpecifierLocBuilder Builder;
8189           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
8190                               QualifierLoc.getSourceRange());
8191           QualifierLoc = Builder.getWithLocInContext(Context);
8192         }
8193 
8194         NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8195             Context.getCanonicalType(Context.getRecordType(RD))));
8196         NameInfo.setNamedTypeInfo(nullptr);
8197         for (auto *Ctor : LookupConstructors(RD))
8198           R.addDecl(Ctor);
8199       } else {
8200         // FIXME: Pick up all the declarations if we found an overloaded function.
8201         R.addDecl(ND);
8202       }
8203     } else {
8204       Diag(IdentLoc, diag::err_no_member)
8205         << NameInfo.getName() << LookupContext << SS.getRange();
8206       return BuildInvalid();
8207     }
8208   }
8209 
8210   if (R.isAmbiguous())
8211     return BuildInvalid();
8212 
8213   if (HasTypenameKeyword) {
8214     // If we asked for a typename and got a non-type decl, error out.
8215     if (!R.getAsSingle<TypeDecl>()) {
8216       Diag(IdentLoc, diag::err_using_typename_non_type);
8217       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8218         Diag((*I)->getUnderlyingDecl()->getLocation(),
8219              diag::note_using_decl_target);
8220       return BuildInvalid();
8221     }
8222   } else {
8223     // If we asked for a non-typename and we got a type, error out,
8224     // but only if this is an instantiation of an unresolved using
8225     // decl.  Otherwise just silently find the type name.
8226     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
8227       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8228       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
8229       return BuildInvalid();
8230     }
8231   }
8232 
8233   // C++0x N2914 [namespace.udecl]p6:
8234   // A using-declaration shall not name a namespace.
8235   if (R.getAsSingle<NamespaceDecl>()) {
8236     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8237       << SS.getRange();
8238     return BuildInvalid();
8239   }
8240 
8241   UsingDecl *UD = BuildValid();
8242 
8243   // The normal rules do not apply to inheriting constructor declarations.
8244   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
8245     // Suppress access diagnostics; the access check is instead performed at the
8246     // point of use for an inheriting constructor.
8247     R.suppressDiagnostics();
8248     CheckInheritingConstructorUsingDecl(UD);
8249     return UD;
8250   }
8251 
8252   // Otherwise, look up the target name.
8253 
8254   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8255     UsingShadowDecl *PrevDecl = nullptr;
8256     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8257       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
8258   }
8259 
8260   return UD;
8261 }
8262 
8263 /// Additional checks for a using declaration referring to a constructor name.
8264 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
8265   assert(!UD->hasTypename() && "expecting a constructor name");
8266 
8267   const Type *SourceType = UD->getQualifier()->getAsType();
8268   assert(SourceType &&
8269          "Using decl naming constructor doesn't have type in scope spec.");
8270   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8271 
8272   // Check whether the named type is a direct base class.
8273   bool AnyDependentBases = false;
8274   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8275                                       AnyDependentBases);
8276   if (!Base && !AnyDependentBases) {
8277     Diag(UD->getUsingLoc(),
8278          diag::err_using_decl_constructor_not_in_direct_base)
8279       << UD->getNameInfo().getSourceRange()
8280       << QualType(SourceType, 0) << TargetClass;
8281     UD->setInvalidDecl();
8282     return true;
8283   }
8284 
8285   if (Base)
8286     Base->setInheritConstructors();
8287 
8288   return false;
8289 }
8290 
8291 /// Checks that the given using declaration is not an invalid
8292 /// redeclaration.  Note that this is checking only for the using decl
8293 /// itself, not for any ill-formedness among the UsingShadowDecls.
8294 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
8295                                        bool HasTypenameKeyword,
8296                                        const CXXScopeSpec &SS,
8297                                        SourceLocation NameLoc,
8298                                        const LookupResult &Prev) {
8299   // C++03 [namespace.udecl]p8:
8300   // C++0x [namespace.udecl]p10:
8301   //   A using-declaration is a declaration and can therefore be used
8302   //   repeatedly where (and only where) multiple declarations are
8303   //   allowed.
8304   //
8305   // That's in non-member contexts.
8306   if (!CurContext->getRedeclContext()->isRecord())
8307     return false;
8308 
8309   NestedNameSpecifier *Qual = SS.getScopeRep();
8310 
8311   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8312     NamedDecl *D = *I;
8313 
8314     bool DTypename;
8315     NestedNameSpecifier *DQual;
8316     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
8317       DTypename = UD->hasTypename();
8318       DQual = UD->getQualifier();
8319     } else if (UnresolvedUsingValueDecl *UD
8320                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8321       DTypename = false;
8322       DQual = UD->getQualifier();
8323     } else if (UnresolvedUsingTypenameDecl *UD
8324                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8325       DTypename = true;
8326       DQual = UD->getQualifier();
8327     } else continue;
8328 
8329     // using decls differ if one says 'typename' and the other doesn't.
8330     // FIXME: non-dependent using decls?
8331     if (HasTypenameKeyword != DTypename) continue;
8332 
8333     // using decls differ if they name different scopes (but note that
8334     // template instantiation can cause this check to trigger when it
8335     // didn't before instantiation).
8336     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8337         Context.getCanonicalNestedNameSpecifier(DQual))
8338       continue;
8339 
8340     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
8341     Diag(D->getLocation(), diag::note_using_decl) << 1;
8342     return true;
8343   }
8344 
8345   return false;
8346 }
8347 
8348 
8349 /// Checks that the given nested-name qualifier used in a using decl
8350 /// in the current context is appropriately related to the current
8351 /// scope.  If an error is found, diagnoses it and returns true.
8352 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8353                                    const CXXScopeSpec &SS,
8354                                    const DeclarationNameInfo &NameInfo,
8355                                    SourceLocation NameLoc) {
8356   DeclContext *NamedContext = computeDeclContext(SS);
8357 
8358   if (!CurContext->isRecord()) {
8359     // C++03 [namespace.udecl]p3:
8360     // C++0x [namespace.udecl]p8:
8361     //   A using-declaration for a class member shall be a member-declaration.
8362 
8363     // If we weren't able to compute a valid scope, it must be a
8364     // dependent class scope.
8365     if (!NamedContext || NamedContext->isRecord()) {
8366       auto *RD = dyn_cast_or_null<CXXRecordDecl>(NamedContext);
8367       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
8368         RD = nullptr;
8369 
8370       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8371         << SS.getRange();
8372 
8373       // If we have a complete, non-dependent source type, try to suggest a
8374       // way to get the same effect.
8375       if (!RD)
8376         return true;
8377 
8378       // Find what this using-declaration was referring to.
8379       LookupResult R(*this, NameInfo, LookupOrdinaryName);
8380       R.setHideTags(false);
8381       R.suppressDiagnostics();
8382       LookupQualifiedName(R, RD);
8383 
8384       if (R.getAsSingle<TypeDecl>()) {
8385         if (getLangOpts().CPlusPlus11) {
8386           // Convert 'using X::Y;' to 'using Y = X::Y;'.
8387           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8388             << 0 // alias declaration
8389             << FixItHint::CreateInsertion(SS.getBeginLoc(),
8390                                           NameInfo.getName().getAsString() +
8391                                               " = ");
8392         } else {
8393           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8394           SourceLocation InsertLoc =
8395               PP.getLocForEndOfToken(NameInfo.getLocEnd());
8396           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8397             << 1 // typedef declaration
8398             << FixItHint::CreateReplacement(UsingLoc, "typedef")
8399             << FixItHint::CreateInsertion(
8400                    InsertLoc, " " + NameInfo.getName().getAsString());
8401         }
8402       } else if (R.getAsSingle<VarDecl>()) {
8403         // Don't provide a fixit outside C++11 mode; we don't want to suggest
8404         // repeating the type of the static data member here.
8405         FixItHint FixIt;
8406         if (getLangOpts().CPlusPlus11) {
8407           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8408           FixIt = FixItHint::CreateReplacement(
8409               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8410         }
8411 
8412         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8413           << 2 // reference declaration
8414           << FixIt;
8415       }
8416       return true;
8417     }
8418 
8419     // Otherwise, everything is known to be fine.
8420     return false;
8421   }
8422 
8423   // The current scope is a record.
8424 
8425   // If the named context is dependent, we can't decide much.
8426   if (!NamedContext) {
8427     // FIXME: in C++0x, we can diagnose if we can prove that the
8428     // nested-name-specifier does not refer to a base class, which is
8429     // still possible in some cases.
8430 
8431     // Otherwise we have to conservatively report that things might be
8432     // okay.
8433     return false;
8434   }
8435 
8436   if (!NamedContext->isRecord()) {
8437     // Ideally this would point at the last name in the specifier,
8438     // but we don't have that level of source info.
8439     Diag(SS.getRange().getBegin(),
8440          diag::err_using_decl_nested_name_specifier_is_not_class)
8441       << SS.getScopeRep() << SS.getRange();
8442     return true;
8443   }
8444 
8445   if (!NamedContext->isDependentContext() &&
8446       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8447     return true;
8448 
8449   if (getLangOpts().CPlusPlus11) {
8450     // C++0x [namespace.udecl]p3:
8451     //   In a using-declaration used as a member-declaration, the
8452     //   nested-name-specifier shall name a base class of the class
8453     //   being defined.
8454 
8455     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8456                                  cast<CXXRecordDecl>(NamedContext))) {
8457       if (CurContext == NamedContext) {
8458         Diag(NameLoc,
8459              diag::err_using_decl_nested_name_specifier_is_current_class)
8460           << SS.getRange();
8461         return true;
8462       }
8463 
8464       Diag(SS.getRange().getBegin(),
8465            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8466         << SS.getScopeRep()
8467         << cast<CXXRecordDecl>(CurContext)
8468         << SS.getRange();
8469       return true;
8470     }
8471 
8472     return false;
8473   }
8474 
8475   // C++03 [namespace.udecl]p4:
8476   //   A using-declaration used as a member-declaration shall refer
8477   //   to a member of a base class of the class being defined [etc.].
8478 
8479   // Salient point: SS doesn't have to name a base class as long as
8480   // lookup only finds members from base classes.  Therefore we can
8481   // diagnose here only if we can prove that that can't happen,
8482   // i.e. if the class hierarchies provably don't intersect.
8483 
8484   // TODO: it would be nice if "definitely valid" results were cached
8485   // in the UsingDecl and UsingShadowDecl so that these checks didn't
8486   // need to be repeated.
8487 
8488   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
8489   auto Collect = [&Bases](const CXXRecordDecl *Base) {
8490     Bases.insert(Base);
8491     return true;
8492   };
8493 
8494   // Collect all bases. Return false if we find a dependent base.
8495   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
8496     return false;
8497 
8498   // Returns true if the base is dependent or is one of the accumulated base
8499   // classes.
8500   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
8501     return !Bases.count(Base);
8502   };
8503 
8504   // Return false if the class has a dependent base or if it or one
8505   // of its bases is present in the base set of the current context.
8506   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
8507       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
8508     return false;
8509 
8510   Diag(SS.getRange().getBegin(),
8511        diag::err_using_decl_nested_name_specifier_is_not_base_class)
8512     << SS.getScopeRep()
8513     << cast<CXXRecordDecl>(CurContext)
8514     << SS.getRange();
8515 
8516   return true;
8517 }
8518 
8519 Decl *Sema::ActOnAliasDeclaration(Scope *S,
8520                                   AccessSpecifier AS,
8521                                   MultiTemplateParamsArg TemplateParamLists,
8522                                   SourceLocation UsingLoc,
8523                                   UnqualifiedId &Name,
8524                                   AttributeList *AttrList,
8525                                   TypeResult Type,
8526                                   Decl *DeclFromDeclSpec) {
8527   // Skip up to the relevant declaration scope.
8528   while (S->getFlags() & Scope::TemplateParamScope)
8529     S = S->getParent();
8530   assert((S->getFlags() & Scope::DeclScope) &&
8531          "got alias-declaration outside of declaration scope");
8532 
8533   if (Type.isInvalid())
8534     return nullptr;
8535 
8536   bool Invalid = false;
8537   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
8538   TypeSourceInfo *TInfo = nullptr;
8539   GetTypeFromParser(Type.get(), &TInfo);
8540 
8541   if (DiagnoseClassNameShadow(CurContext, NameInfo))
8542     return nullptr;
8543 
8544   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
8545                                       UPPC_DeclarationType)) {
8546     Invalid = true;
8547     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8548                                              TInfo->getTypeLoc().getBeginLoc());
8549   }
8550 
8551   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8552   LookupName(Previous, S);
8553 
8554   // Warn about shadowing the name of a template parameter.
8555   if (Previous.isSingleResult() &&
8556       Previous.getFoundDecl()->isTemplateParameter()) {
8557     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
8558     Previous.clear();
8559   }
8560 
8561   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8562          "name in alias declaration must be an identifier");
8563   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8564                                                Name.StartLocation,
8565                                                Name.Identifier, TInfo);
8566 
8567   NewTD->setAccess(AS);
8568 
8569   if (Invalid)
8570     NewTD->setInvalidDecl();
8571 
8572   ProcessDeclAttributeList(S, NewTD, AttrList);
8573 
8574   CheckTypedefForVariablyModifiedType(S, NewTD);
8575   Invalid |= NewTD->isInvalidDecl();
8576 
8577   bool Redeclaration = false;
8578 
8579   NamedDecl *NewND;
8580   if (TemplateParamLists.size()) {
8581     TypeAliasTemplateDecl *OldDecl = nullptr;
8582     TemplateParameterList *OldTemplateParams = nullptr;
8583 
8584     if (TemplateParamLists.size() != 1) {
8585       Diag(UsingLoc, diag::err_alias_template_extra_headers)
8586         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8587          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
8588     }
8589     TemplateParameterList *TemplateParams = TemplateParamLists[0];
8590 
8591     // Only consider previous declarations in the same scope.
8592     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8593                          /*ExplicitInstantiationOrSpecialization*/false);
8594     if (!Previous.empty()) {
8595       Redeclaration = true;
8596 
8597       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8598       if (!OldDecl && !Invalid) {
8599         Diag(UsingLoc, diag::err_redefinition_different_kind)
8600           << Name.Identifier;
8601 
8602         NamedDecl *OldD = Previous.getRepresentativeDecl();
8603         if (OldD->getLocation().isValid())
8604           Diag(OldD->getLocation(), diag::note_previous_definition);
8605 
8606         Invalid = true;
8607       }
8608 
8609       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8610         if (TemplateParameterListsAreEqual(TemplateParams,
8611                                            OldDecl->getTemplateParameters(),
8612                                            /*Complain=*/true,
8613                                            TPL_TemplateMatch))
8614           OldTemplateParams = OldDecl->getTemplateParameters();
8615         else
8616           Invalid = true;
8617 
8618         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8619         if (!Invalid &&
8620             !Context.hasSameType(OldTD->getUnderlyingType(),
8621                                  NewTD->getUnderlyingType())) {
8622           // FIXME: The C++0x standard does not clearly say this is ill-formed,
8623           // but we can't reasonably accept it.
8624           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8625             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8626           if (OldTD->getLocation().isValid())
8627             Diag(OldTD->getLocation(), diag::note_previous_definition);
8628           Invalid = true;
8629         }
8630       }
8631     }
8632 
8633     // Merge any previous default template arguments into our parameters,
8634     // and check the parameter list.
8635     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8636                                    TPC_TypeAliasTemplate))
8637       return nullptr;
8638 
8639     TypeAliasTemplateDecl *NewDecl =
8640       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8641                                     Name.Identifier, TemplateParams,
8642                                     NewTD);
8643     NewTD->setDescribedAliasTemplate(NewDecl);
8644 
8645     NewDecl->setAccess(AS);
8646 
8647     if (Invalid)
8648       NewDecl->setInvalidDecl();
8649     else if (OldDecl)
8650       NewDecl->setPreviousDecl(OldDecl);
8651 
8652     NewND = NewDecl;
8653   } else {
8654     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
8655       setTagNameForLinkagePurposes(TD, NewTD);
8656       handleTagNumbering(TD, S);
8657     }
8658     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8659     NewND = NewTD;
8660   }
8661 
8662   if (!Redeclaration)
8663     PushOnScopeChains(NewND, S);
8664 
8665   ActOnDocumentableDecl(NewND);
8666   return NewND;
8667 }
8668 
8669 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8670                                    SourceLocation AliasLoc,
8671                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
8672                                    SourceLocation IdentLoc,
8673                                    IdentifierInfo *Ident) {
8674 
8675   // Lookup the namespace name.
8676   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8677   LookupParsedName(R, S, &SS);
8678 
8679   if (R.isAmbiguous())
8680     return nullptr;
8681 
8682   if (R.empty()) {
8683     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
8684       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8685       return nullptr;
8686     }
8687   }
8688   assert(!R.isAmbiguous() && !R.empty());
8689 
8690   // Check if we have a previous declaration with the same name.
8691   NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8692                                          ForRedeclaration);
8693   if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8694     PrevDecl = nullptr;
8695 
8696   NamedDecl *ND = R.getFoundDecl();
8697 
8698   if (PrevDecl) {
8699     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8700       // We already have an alias with the same name that points to the same
8701       // namespace; check that it matches.
8702       if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8703         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8704           << Alias;
8705         Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8706           << AD->getNamespace();
8707         return nullptr;
8708       }
8709     } else {
8710       unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8711                             ? diag::err_redefinition
8712                             : diag::err_redefinition_different_kind;
8713       Diag(AliasLoc, DiagID) << Alias;
8714       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8715       return nullptr;
8716     }
8717   }
8718 
8719   // The use of a nested name specifier may trigger deprecation warnings.
8720   DiagnoseUseOfDecl(ND, IdentLoc);
8721 
8722   NamespaceAliasDecl *AliasDecl =
8723     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
8724                                Alias, SS.getWithLocInContext(Context),
8725                                IdentLoc, ND);
8726   if (PrevDecl)
8727     AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
8728 
8729   PushOnScopeChains(AliasDecl, S);
8730   return AliasDecl;
8731 }
8732 
8733 Sema::ImplicitExceptionSpecification
8734 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8735                                                CXXMethodDecl *MD) {
8736   CXXRecordDecl *ClassDecl = MD->getParent();
8737 
8738   // C++ [except.spec]p14:
8739   //   An implicitly declared special member function (Clause 12) shall have an
8740   //   exception-specification. [...]
8741   ImplicitExceptionSpecification ExceptSpec(*this);
8742   if (ClassDecl->isInvalidDecl())
8743     return ExceptSpec;
8744 
8745   // Direct base-class constructors.
8746   for (const auto &B : ClassDecl->bases()) {
8747     if (B.isVirtual()) // Handled below.
8748       continue;
8749 
8750     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8751       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8752       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8753       // If this is a deleted function, add it anyway. This might be conformant
8754       // with the standard. This might not. I'm not sure. It might not matter.
8755       if (Constructor)
8756         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8757     }
8758   }
8759 
8760   // Virtual base-class constructors.
8761   for (const auto &B : ClassDecl->vbases()) {
8762     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8763       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8764       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8765       // If this is a deleted function, add it anyway. This might be conformant
8766       // with the standard. This might not. I'm not sure. It might not matter.
8767       if (Constructor)
8768         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8769     }
8770   }
8771 
8772   // Field constructors.
8773   for (const auto *F : ClassDecl->fields()) {
8774     if (F->hasInClassInitializer()) {
8775       if (Expr *E = F->getInClassInitializer())
8776         ExceptSpec.CalledExpr(E);
8777     } else if (const RecordType *RecordTy
8778               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8779       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8780       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8781       // If this is a deleted function, add it anyway. This might be conformant
8782       // with the standard. This might not. I'm not sure. It might not matter.
8783       // In particular, the problem is that this function never gets called. It
8784       // might just be ill-formed because this function attempts to refer to
8785       // a deleted function here.
8786       if (Constructor)
8787         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8788     }
8789   }
8790 
8791   return ExceptSpec;
8792 }
8793 
8794 Sema::ImplicitExceptionSpecification
8795 Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8796   CXXRecordDecl *ClassDecl = CD->getParent();
8797 
8798   // C++ [except.spec]p14:
8799   //   An inheriting constructor [...] shall have an exception-specification. [...]
8800   ImplicitExceptionSpecification ExceptSpec(*this);
8801   if (ClassDecl->isInvalidDecl())
8802     return ExceptSpec;
8803 
8804   // Inherited constructor.
8805   const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8806   const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8807   // FIXME: Copying or moving the parameters could add extra exceptions to the
8808   // set, as could the default arguments for the inherited constructor. This
8809   // will be addressed when we implement the resolution of core issue 1351.
8810   ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8811 
8812   // Direct base-class constructors.
8813   for (const auto &B : ClassDecl->bases()) {
8814     if (B.isVirtual()) // Handled below.
8815       continue;
8816 
8817     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8818       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8819       if (BaseClassDecl == InheritedDecl)
8820         continue;
8821       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8822       if (Constructor)
8823         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8824     }
8825   }
8826 
8827   // Virtual base-class constructors.
8828   for (const auto &B : ClassDecl->vbases()) {
8829     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
8830       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8831       if (BaseClassDecl == InheritedDecl)
8832         continue;
8833       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8834       if (Constructor)
8835         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
8836     }
8837   }
8838 
8839   // Field constructors.
8840   for (const auto *F : ClassDecl->fields()) {
8841     if (F->hasInClassInitializer()) {
8842       if (Expr *E = F->getInClassInitializer())
8843         ExceptSpec.CalledExpr(E);
8844     } else if (const RecordType *RecordTy
8845               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8846       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8847       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8848       if (Constructor)
8849         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8850     }
8851   }
8852 
8853   return ExceptSpec;
8854 }
8855 
8856 namespace {
8857 /// RAII object to register a special member as being currently declared.
8858 struct DeclaringSpecialMember {
8859   Sema &S;
8860   Sema::SpecialMemberDecl D;
8861   bool WasAlreadyBeingDeclared;
8862 
8863   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8864     : S(S), D(RD, CSM) {
8865     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
8866     if (WasAlreadyBeingDeclared)
8867       // This almost never happens, but if it does, ensure that our cache
8868       // doesn't contain a stale result.
8869       S.SpecialMemberCache.clear();
8870 
8871     // FIXME: Register a note to be produced if we encounter an error while
8872     // declaring the special member.
8873   }
8874   ~DeclaringSpecialMember() {
8875     if (!WasAlreadyBeingDeclared)
8876       S.SpecialMembersBeingDeclared.erase(D);
8877   }
8878 
8879   /// \brief Are we already trying to declare this special member?
8880   bool isAlreadyBeingDeclared() const {
8881     return WasAlreadyBeingDeclared;
8882   }
8883 };
8884 }
8885 
8886 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8887                                                      CXXRecordDecl *ClassDecl) {
8888   // C++ [class.ctor]p5:
8889   //   A default constructor for a class X is a constructor of class X
8890   //   that can be called without an argument. If there is no
8891   //   user-declared constructor for class X, a default constructor is
8892   //   implicitly declared. An implicitly-declared default constructor
8893   //   is an inline public member of its class.
8894   assert(ClassDecl->needsImplicitDefaultConstructor() &&
8895          "Should not build implicit default constructor!");
8896 
8897   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8898   if (DSM.isAlreadyBeingDeclared())
8899     return nullptr;
8900 
8901   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8902                                                      CXXDefaultConstructor,
8903                                                      false);
8904 
8905   // Create the actual constructor declaration.
8906   CanQualType ClassType
8907     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8908   SourceLocation ClassLoc = ClassDecl->getLocation();
8909   DeclarationName Name
8910     = Context.DeclarationNames.getCXXConstructorName(ClassType);
8911   DeclarationNameInfo NameInfo(Name, ClassLoc);
8912   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8913       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8914       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8915       /*isImplicitlyDeclared=*/true, Constexpr);
8916   DefaultCon->setAccess(AS_public);
8917   DefaultCon->setDefaulted();
8918 
8919   if (getLangOpts().CUDA) {
8920     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8921                                             DefaultCon,
8922                                             /* ConstRHS */ false,
8923                                             /* Diagnose */ false);
8924   }
8925 
8926   // Build an exception specification pointing back at this constructor.
8927   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8928   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8929 
8930   // We don't need to use SpecialMemberIsTrivial here; triviality for default
8931   // constructors is easy to compute.
8932   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8933 
8934   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8935     SetDeclDeleted(DefaultCon, ClassLoc);
8936 
8937   // Note that we have declared this constructor.
8938   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8939 
8940   if (Scope *S = getScopeForContext(ClassDecl))
8941     PushOnScopeChains(DefaultCon, S, false);
8942   ClassDecl->addDecl(DefaultCon);
8943 
8944   return DefaultCon;
8945 }
8946 
8947 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8948                                             CXXConstructorDecl *Constructor) {
8949   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8950           !Constructor->doesThisDeclarationHaveABody() &&
8951           !Constructor->isDeleted()) &&
8952     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8953 
8954   CXXRecordDecl *ClassDecl = Constructor->getParent();
8955   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8956 
8957   SynthesizedFunctionScope Scope(*this, Constructor);
8958   DiagnosticErrorTrap Trap(Diags);
8959   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8960       Trap.hasErrorOccurred()) {
8961     Diag(CurrentLocation, diag::note_member_synthesized_at)
8962       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8963     Constructor->setInvalidDecl();
8964     return;
8965   }
8966 
8967   // The exception specification is needed because we are defining the
8968   // function.
8969   ResolveExceptionSpec(CurrentLocation,
8970                        Constructor->getType()->castAs<FunctionProtoType>());
8971 
8972   SourceLocation Loc = Constructor->getLocEnd().isValid()
8973                            ? Constructor->getLocEnd()
8974                            : Constructor->getLocation();
8975   Constructor->setBody(new (Context) CompoundStmt(Loc));
8976 
8977   Constructor->markUsed(Context);
8978   MarkVTableUsed(CurrentLocation, ClassDecl);
8979 
8980   if (ASTMutationListener *L = getASTMutationListener()) {
8981     L->CompletedImplicitDefinition(Constructor);
8982   }
8983 
8984   DiagnoseUninitializedFields(*this, Constructor);
8985 }
8986 
8987 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8988   // Perform any delayed checks on exception specifications.
8989   CheckDelayedMemberExceptionSpecs();
8990 }
8991 
8992 namespace {
8993 /// Information on inheriting constructors to declare.
8994 class InheritingConstructorInfo {
8995 public:
8996   InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8997       : SemaRef(SemaRef), Derived(Derived) {
8998     // Mark the constructors that we already have in the derived class.
8999     //
9000     // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
9001     //   unless there is a user-declared constructor with the same signature in
9002     //   the class where the using-declaration appears.
9003     visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
9004   }
9005 
9006   void inheritAll(CXXRecordDecl *RD) {
9007     visitAll(RD, &InheritingConstructorInfo::inherit);
9008   }
9009 
9010 private:
9011   /// Information about an inheriting constructor.
9012   struct InheritingConstructor {
9013     InheritingConstructor()
9014       : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
9015 
9016     /// If \c true, a constructor with this signature is already declared
9017     /// in the derived class.
9018     bool DeclaredInDerived;
9019 
9020     /// The constructor which is inherited.
9021     const CXXConstructorDecl *BaseCtor;
9022 
9023     /// The derived constructor we declared.
9024     CXXConstructorDecl *DerivedCtor;
9025   };
9026 
9027   /// Inheriting constructors with a given canonical type. There can be at
9028   /// most one such non-template constructor, and any number of templated
9029   /// constructors.
9030   struct InheritingConstructorsForType {
9031     InheritingConstructor NonTemplate;
9032     SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
9033         Templates;
9034 
9035     InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
9036       if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
9037         TemplateParameterList *ParamList = FTD->getTemplateParameters();
9038         for (unsigned I = 0, N = Templates.size(); I != N; ++I)
9039           if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
9040                                                false, S.TPL_TemplateMatch))
9041             return Templates[I].second;
9042         Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
9043         return Templates.back().second;
9044       }
9045 
9046       return NonTemplate;
9047     }
9048   };
9049 
9050   /// Get or create the inheriting constructor record for a constructor.
9051   InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
9052                                   QualType CtorType) {
9053     return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
9054         .getEntry(SemaRef, Ctor);
9055   }
9056 
9057   typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
9058 
9059   /// Process all constructors for a class.
9060   void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
9061     for (const auto *Ctor : RD->ctors())
9062       (this->*Callback)(Ctor);
9063     for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
9064              I(RD->decls_begin()), E(RD->decls_end());
9065          I != E; ++I) {
9066       const FunctionDecl *FD = (*I)->getTemplatedDecl();
9067       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
9068         (this->*Callback)(CD);
9069     }
9070   }
9071 
9072   /// Note that a constructor (or constructor template) was declared in Derived.
9073   void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
9074     getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
9075   }
9076 
9077   /// Inherit a single constructor.
9078   void inherit(const CXXConstructorDecl *Ctor) {
9079     const FunctionProtoType *CtorType =
9080         Ctor->getType()->castAs<FunctionProtoType>();
9081     ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
9082     FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
9083 
9084     SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
9085 
9086     // Core issue (no number yet): the ellipsis is always discarded.
9087     if (EPI.Variadic) {
9088       SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
9089       SemaRef.Diag(Ctor->getLocation(),
9090                    diag::note_using_decl_constructor_ellipsis);
9091       EPI.Variadic = false;
9092     }
9093 
9094     // Declare a constructor for each number of parameters.
9095     //
9096     // C++11 [class.inhctor]p1:
9097     //   The candidate set of inherited constructors from the class X named in
9098     //   the using-declaration consists of [... modulo defects ...] for each
9099     //   constructor or constructor template of X, the set of constructors or
9100     //   constructor templates that results from omitting any ellipsis parameter
9101     //   specification and successively omitting parameters with a default
9102     //   argument from the end of the parameter-type-list
9103     unsigned MinParams = minParamsToInherit(Ctor);
9104     unsigned Params = Ctor->getNumParams();
9105     if (Params >= MinParams) {
9106       do
9107         declareCtor(UsingLoc, Ctor,
9108                     SemaRef.Context.getFunctionType(
9109                         Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
9110       while (Params > MinParams &&
9111              Ctor->getParamDecl(--Params)->hasDefaultArg());
9112     }
9113   }
9114 
9115   /// Find the using-declaration which specified that we should inherit the
9116   /// constructors of \p Base.
9117   SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
9118     // No fancy lookup required; just look for the base constructor name
9119     // directly within the derived class.
9120     ASTContext &Context = SemaRef.Context;
9121     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9122         Context.getCanonicalType(Context.getRecordType(Base)));
9123     DeclContext::lookup_result Decls = Derived->lookup(Name);
9124     return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
9125   }
9126 
9127   unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
9128     // C++11 [class.inhctor]p3:
9129     //   [F]or each constructor template in the candidate set of inherited
9130     //   constructors, a constructor template is implicitly declared
9131     if (Ctor->getDescribedFunctionTemplate())
9132       return 0;
9133 
9134     //   For each non-template constructor in the candidate set of inherited
9135     //   constructors other than a constructor having no parameters or a
9136     //   copy/move constructor having a single parameter, a constructor is
9137     //   implicitly declared [...]
9138     if (Ctor->getNumParams() == 0)
9139       return 1;
9140     if (Ctor->isCopyOrMoveConstructor())
9141       return 2;
9142 
9143     // Per discussion on core reflector, never inherit a constructor which
9144     // would become a default, copy, or move constructor of Derived either.
9145     const ParmVarDecl *PD = Ctor->getParamDecl(0);
9146     const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
9147     return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
9148   }
9149 
9150   /// Declare a single inheriting constructor, inheriting the specified
9151   /// constructor, with the given type.
9152   void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
9153                    QualType DerivedType) {
9154     InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
9155 
9156     // C++11 [class.inhctor]p3:
9157     //   ... a constructor is implicitly declared with the same constructor
9158     //   characteristics unless there is a user-declared constructor with
9159     //   the same signature in the class where the using-declaration appears
9160     if (Entry.DeclaredInDerived)
9161       return;
9162 
9163     // C++11 [class.inhctor]p7:
9164     //   If two using-declarations declare inheriting constructors with the
9165     //   same signature, the program is ill-formed
9166     if (Entry.DerivedCtor) {
9167       if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
9168         // Only diagnose this once per constructor.
9169         if (Entry.DerivedCtor->isInvalidDecl())
9170           return;
9171         Entry.DerivedCtor->setInvalidDecl();
9172 
9173         SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
9174         SemaRef.Diag(BaseCtor->getLocation(),
9175                      diag::note_using_decl_constructor_conflict_current_ctor);
9176         SemaRef.Diag(Entry.BaseCtor->getLocation(),
9177                      diag::note_using_decl_constructor_conflict_previous_ctor);
9178         SemaRef.Diag(Entry.DerivedCtor->getLocation(),
9179                      diag::note_using_decl_constructor_conflict_previous_using);
9180       } else {
9181         // Core issue (no number): if the same inheriting constructor is
9182         // produced by multiple base class constructors from the same base
9183         // class, the inheriting constructor is defined as deleted.
9184         SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
9185       }
9186 
9187       return;
9188     }
9189 
9190     ASTContext &Context = SemaRef.Context;
9191     DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
9192         Context.getCanonicalType(Context.getRecordType(Derived)));
9193     DeclarationNameInfo NameInfo(Name, UsingLoc);
9194 
9195     TemplateParameterList *TemplateParams = nullptr;
9196     if (const FunctionTemplateDecl *FTD =
9197             BaseCtor->getDescribedFunctionTemplate()) {
9198       TemplateParams = FTD->getTemplateParameters();
9199       // We're reusing template parameters from a different DeclContext. This
9200       // is questionable at best, but works out because the template depth in
9201       // both places is guaranteed to be 0.
9202       // FIXME: Rebuild the template parameters in the new context, and
9203       // transform the function type to refer to them.
9204     }
9205 
9206     // Build type source info pointing at the using-declaration. This is
9207     // required by template instantiation.
9208     TypeSourceInfo *TInfo =
9209         Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9210     FunctionProtoTypeLoc ProtoLoc =
9211         TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9212 
9213     CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9214         Context, Derived, UsingLoc, NameInfo, DerivedType,
9215         TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9216         /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9217 
9218     // Build an unevaluated exception specification for this constructor.
9219     const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9220     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9221     EPI.ExceptionSpec.Type = EST_Unevaluated;
9222     EPI.ExceptionSpec.SourceDecl = DerivedCtor;
9223     DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9224                                                  FPT->getParamTypes(), EPI));
9225 
9226     // Build the parameter declarations.
9227     SmallVector<ParmVarDecl *, 16> ParamDecls;
9228     for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
9229       TypeSourceInfo *TInfo =
9230           Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
9231       ParmVarDecl *PD = ParmVarDecl::Create(
9232           Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9233           FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
9234       PD->setScopeInfo(0, I);
9235       PD->setImplicit();
9236       ParamDecls.push_back(PD);
9237       ProtoLoc.setParam(I, PD);
9238     }
9239 
9240     // Set up the new constructor.
9241     DerivedCtor->setAccess(BaseCtor->getAccess());
9242     DerivedCtor->setParams(ParamDecls);
9243     DerivedCtor->setInheritedConstructor(BaseCtor);
9244     if (BaseCtor->isDeleted())
9245       SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9246 
9247     // If this is a constructor template, build the template declaration.
9248     if (TemplateParams) {
9249       FunctionTemplateDecl *DerivedTemplate =
9250           FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9251                                        TemplateParams, DerivedCtor);
9252       DerivedTemplate->setAccess(BaseCtor->getAccess());
9253       DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9254       Derived->addDecl(DerivedTemplate);
9255     } else {
9256       Derived->addDecl(DerivedCtor);
9257     }
9258 
9259     Entry.BaseCtor = BaseCtor;
9260     Entry.DerivedCtor = DerivedCtor;
9261   }
9262 
9263   Sema &SemaRef;
9264   CXXRecordDecl *Derived;
9265   typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9266   MapType Map;
9267 };
9268 }
9269 
9270 void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9271   // Defer declaring the inheriting constructors until the class is
9272   // instantiated.
9273   if (ClassDecl->isDependentContext())
9274     return;
9275 
9276   // Find base classes from which we might inherit constructors.
9277   SmallVector<CXXRecordDecl*, 4> InheritedBases;
9278   for (const auto &BaseIt : ClassDecl->bases())
9279     if (BaseIt.getInheritConstructors())
9280       InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
9281 
9282   // Go no further if we're not inheriting any constructors.
9283   if (InheritedBases.empty())
9284     return;
9285 
9286   // Declare the inherited constructors.
9287   InheritingConstructorInfo ICI(*this, ClassDecl);
9288   for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9289     ICI.inheritAll(InheritedBases[I]);
9290 }
9291 
9292 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9293                                        CXXConstructorDecl *Constructor) {
9294   CXXRecordDecl *ClassDecl = Constructor->getParent();
9295   assert(Constructor->getInheritedConstructor() &&
9296          !Constructor->doesThisDeclarationHaveABody() &&
9297          !Constructor->isDeleted());
9298 
9299   SynthesizedFunctionScope Scope(*this, Constructor);
9300   DiagnosticErrorTrap Trap(Diags);
9301   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9302       Trap.hasErrorOccurred()) {
9303     Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9304       << Context.getTagDeclType(ClassDecl);
9305     Constructor->setInvalidDecl();
9306     return;
9307   }
9308 
9309   SourceLocation Loc = Constructor->getLocation();
9310   Constructor->setBody(new (Context) CompoundStmt(Loc));
9311 
9312   Constructor->markUsed(Context);
9313   MarkVTableUsed(CurrentLocation, ClassDecl);
9314 
9315   if (ASTMutationListener *L = getASTMutationListener()) {
9316     L->CompletedImplicitDefinition(Constructor);
9317   }
9318 }
9319 
9320 
9321 Sema::ImplicitExceptionSpecification
9322 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9323   CXXRecordDecl *ClassDecl = MD->getParent();
9324 
9325   // C++ [except.spec]p14:
9326   //   An implicitly declared special member function (Clause 12) shall have
9327   //   an exception-specification.
9328   ImplicitExceptionSpecification ExceptSpec(*this);
9329   if (ClassDecl->isInvalidDecl())
9330     return ExceptSpec;
9331 
9332   // Direct base-class destructors.
9333   for (const auto &B : ClassDecl->bases()) {
9334     if (B.isVirtual()) // Handled below.
9335       continue;
9336 
9337     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9338       ExceptSpec.CalledDecl(B.getLocStart(),
9339                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9340   }
9341 
9342   // Virtual base-class destructors.
9343   for (const auto &B : ClassDecl->vbases()) {
9344     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9345       ExceptSpec.CalledDecl(B.getLocStart(),
9346                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
9347   }
9348 
9349   // Field destructors.
9350   for (const auto *F : ClassDecl->fields()) {
9351     if (const RecordType *RecordTy
9352         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
9353       ExceptSpec.CalledDecl(F->getLocation(),
9354                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
9355   }
9356 
9357   return ExceptSpec;
9358 }
9359 
9360 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9361   // C++ [class.dtor]p2:
9362   //   If a class has no user-declared destructor, a destructor is
9363   //   declared implicitly. An implicitly-declared destructor is an
9364   //   inline public member of its class.
9365   assert(ClassDecl->needsImplicitDestructor());
9366 
9367   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9368   if (DSM.isAlreadyBeingDeclared())
9369     return nullptr;
9370 
9371   // Create the actual destructor declaration.
9372   CanQualType ClassType
9373     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
9374   SourceLocation ClassLoc = ClassDecl->getLocation();
9375   DeclarationName Name
9376     = Context.DeclarationNames.getCXXDestructorName(ClassType);
9377   DeclarationNameInfo NameInfo(Name, ClassLoc);
9378   CXXDestructorDecl *Destructor
9379       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
9380                                   QualType(), nullptr, /*isInline=*/true,
9381                                   /*isImplicitlyDeclared=*/true);
9382   Destructor->setAccess(AS_public);
9383   Destructor->setDefaulted();
9384 
9385   if (getLangOpts().CUDA) {
9386     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9387                                             Destructor,
9388                                             /* ConstRHS */ false,
9389                                             /* Diagnose */ false);
9390   }
9391 
9392   // Build an exception specification pointing back at this destructor.
9393   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
9394   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9395 
9396   AddOverriddenMethods(ClassDecl, Destructor);
9397 
9398   // We don't need to use SpecialMemberIsTrivial here; triviality for
9399   // destructors is easy to compute.
9400   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9401 
9402   if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
9403     SetDeclDeleted(Destructor, ClassLoc);
9404 
9405   // Note that we have declared this destructor.
9406   ++ASTContext::NumImplicitDestructorsDeclared;
9407 
9408   // Introduce this destructor into its scope.
9409   if (Scope *S = getScopeForContext(ClassDecl))
9410     PushOnScopeChains(Destructor, S, false);
9411   ClassDecl->addDecl(Destructor);
9412 
9413   return Destructor;
9414 }
9415 
9416 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
9417                                     CXXDestructorDecl *Destructor) {
9418   assert((Destructor->isDefaulted() &&
9419           !Destructor->doesThisDeclarationHaveABody() &&
9420           !Destructor->isDeleted()) &&
9421          "DefineImplicitDestructor - call it for implicit default dtor");
9422   CXXRecordDecl *ClassDecl = Destructor->getParent();
9423   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
9424 
9425   if (Destructor->isInvalidDecl())
9426     return;
9427 
9428   SynthesizedFunctionScope Scope(*this, Destructor);
9429 
9430   DiagnosticErrorTrap Trap(Diags);
9431   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9432                                          Destructor->getParent());
9433 
9434   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
9435     Diag(CurrentLocation, diag::note_member_synthesized_at)
9436       << CXXDestructor << Context.getTagDeclType(ClassDecl);
9437 
9438     Destructor->setInvalidDecl();
9439     return;
9440   }
9441 
9442   // The exception specification is needed because we are defining the
9443   // function.
9444   ResolveExceptionSpec(CurrentLocation,
9445                        Destructor->getType()->castAs<FunctionProtoType>());
9446 
9447   SourceLocation Loc = Destructor->getLocEnd().isValid()
9448                            ? Destructor->getLocEnd()
9449                            : Destructor->getLocation();
9450   Destructor->setBody(new (Context) CompoundStmt(Loc));
9451   Destructor->markUsed(Context);
9452   MarkVTableUsed(CurrentLocation, ClassDecl);
9453 
9454   if (ASTMutationListener *L = getASTMutationListener()) {
9455     L->CompletedImplicitDefinition(Destructor);
9456   }
9457 }
9458 
9459 /// \brief Perform any semantic analysis which needs to be delayed until all
9460 /// pending class member declarations have been parsed.
9461 void Sema::ActOnFinishCXXMemberDecls() {
9462   // If the context is an invalid C++ class, just suppress these checks.
9463   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9464     if (Record->isInvalidDecl()) {
9465       DelayedDefaultedMemberExceptionSpecs.clear();
9466       DelayedExceptionSpecChecks.clear();
9467       return;
9468     }
9469   }
9470 }
9471 
9472 static void getDefaultArgExprsForConstructors(Sema &S, CXXRecordDecl *Class) {
9473   // Don't do anything for template patterns.
9474   if (Class->getDescribedClassTemplate())
9475     return;
9476 
9477   for (Decl *Member : Class->decls()) {
9478     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
9479     if (!CD) {
9480       // Recurse on nested classes.
9481       if (auto *NestedRD = dyn_cast<CXXRecordDecl>(Member))
9482         getDefaultArgExprsForConstructors(S, NestedRD);
9483       continue;
9484     } else if (!CD->isDefaultConstructor() || !CD->hasAttr<DLLExportAttr>()) {
9485       continue;
9486     }
9487 
9488     for (unsigned I = 0, E = CD->getNumParams(); I != E; ++I) {
9489       // Skip any default arguments that we've already instantiated.
9490       if (S.Context.getDefaultArgExprForConstructor(CD, I))
9491         continue;
9492 
9493       Expr *DefaultArg = S.BuildCXXDefaultArgExpr(Class->getLocation(), CD,
9494                                                   CD->getParamDecl(I)).get();
9495       S.DiscardCleanupsInEvaluationContext();
9496       S.Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
9497     }
9498   }
9499 }
9500 
9501 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
9502   auto *RD = dyn_cast<CXXRecordDecl>(D);
9503 
9504   // Default constructors that are annotated with __declspec(dllexport) which
9505   // have default arguments or don't use the standard calling convention are
9506   // wrapped with a thunk called the default constructor closure.
9507   if (RD && Context.getTargetInfo().getCXXABI().isMicrosoft())
9508     getDefaultArgExprsForConstructors(*this, RD);
9509 
9510   if (!DelayedDllExportClasses.empty()) {
9511     // Calling ReferenceDllExportedMethods might cause the current function to
9512     // be called again, so use a local copy of DelayedDllExportClasses.
9513     SmallVector<CXXRecordDecl *, 4> WorkList;
9514     std::swap(DelayedDllExportClasses, WorkList);
9515     for (CXXRecordDecl *Class : WorkList)
9516       ReferenceDllExportedMethods(*this, Class);
9517   }
9518 }
9519 
9520 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9521                                          CXXDestructorDecl *Destructor) {
9522   assert(getLangOpts().CPlusPlus11 &&
9523          "adjusting dtor exception specs was introduced in c++11");
9524 
9525   // C++11 [class.dtor]p3:
9526   //   A declaration of a destructor that does not have an exception-
9527   //   specification is implicitly considered to have the same exception-
9528   //   specification as an implicit declaration.
9529   const FunctionProtoType *DtorType = Destructor->getType()->
9530                                         getAs<FunctionProtoType>();
9531   if (DtorType->hasExceptionSpec())
9532     return;
9533 
9534   // Replace the destructor's type, building off the existing one. Fortunately,
9535   // the only thing of interest in the destructor type is its extended info.
9536   // The return and arguments are fixed.
9537   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
9538   EPI.ExceptionSpec.Type = EST_Unevaluated;
9539   EPI.ExceptionSpec.SourceDecl = Destructor;
9540   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
9541 
9542   // FIXME: If the destructor has a body that could throw, and the newly created
9543   // spec doesn't allow exceptions, we should emit a warning, because this
9544   // change in behavior can break conforming C++03 programs at runtime.
9545   // However, we don't have a body or an exception specification yet, so it
9546   // needs to be done somewhere else.
9547 }
9548 
9549 namespace {
9550 /// \brief An abstract base class for all helper classes used in building the
9551 //  copy/move operators. These classes serve as factory functions and help us
9552 //  avoid using the same Expr* in the AST twice.
9553 class ExprBuilder {
9554   ExprBuilder(const ExprBuilder&) = delete;
9555   ExprBuilder &operator=(const ExprBuilder&) = delete;
9556 
9557 protected:
9558   static Expr *assertNotNull(Expr *E) {
9559     assert(E && "Expression construction must not fail.");
9560     return E;
9561   }
9562 
9563 public:
9564   ExprBuilder() {}
9565   virtual ~ExprBuilder() {}
9566 
9567   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9568 };
9569 
9570 class RefBuilder: public ExprBuilder {
9571   VarDecl *Var;
9572   QualType VarType;
9573 
9574 public:
9575   Expr *build(Sema &S, SourceLocation Loc) const override {
9576     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
9577   }
9578 
9579   RefBuilder(VarDecl *Var, QualType VarType)
9580       : Var(Var), VarType(VarType) {}
9581 };
9582 
9583 class ThisBuilder: public ExprBuilder {
9584 public:
9585   Expr *build(Sema &S, SourceLocation Loc) const override {
9586     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
9587   }
9588 };
9589 
9590 class CastBuilder: public ExprBuilder {
9591   const ExprBuilder &Builder;
9592   QualType Type;
9593   ExprValueKind Kind;
9594   const CXXCastPath &Path;
9595 
9596 public:
9597   Expr *build(Sema &S, SourceLocation Loc) const override {
9598     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9599                                              CK_UncheckedDerivedToBase, Kind,
9600                                              &Path).get());
9601   }
9602 
9603   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9604               const CXXCastPath &Path)
9605       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9606 };
9607 
9608 class DerefBuilder: public ExprBuilder {
9609   const ExprBuilder &Builder;
9610 
9611 public:
9612   Expr *build(Sema &S, SourceLocation Loc) const override {
9613     return assertNotNull(
9614         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
9615   }
9616 
9617   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9618 };
9619 
9620 class MemberBuilder: public ExprBuilder {
9621   const ExprBuilder &Builder;
9622   QualType Type;
9623   CXXScopeSpec SS;
9624   bool IsArrow;
9625   LookupResult &MemberLookup;
9626 
9627 public:
9628   Expr *build(Sema &S, SourceLocation Loc) const override {
9629     return assertNotNull(S.BuildMemberReferenceExpr(
9630         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
9631         nullptr, MemberLookup, nullptr).get());
9632   }
9633 
9634   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9635                 LookupResult &MemberLookup)
9636       : Builder(Builder), Type(Type), IsArrow(IsArrow),
9637         MemberLookup(MemberLookup) {}
9638 };
9639 
9640 class MoveCastBuilder: public ExprBuilder {
9641   const ExprBuilder &Builder;
9642 
9643 public:
9644   Expr *build(Sema &S, SourceLocation Loc) const override {
9645     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9646   }
9647 
9648   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9649 };
9650 
9651 class LvalueConvBuilder: public ExprBuilder {
9652   const ExprBuilder &Builder;
9653 
9654 public:
9655   Expr *build(Sema &S, SourceLocation Loc) const override {
9656     return assertNotNull(
9657         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
9658   }
9659 
9660   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9661 };
9662 
9663 class SubscriptBuilder: public ExprBuilder {
9664   const ExprBuilder &Base;
9665   const ExprBuilder &Index;
9666 
9667 public:
9668   Expr *build(Sema &S, SourceLocation Loc) const override {
9669     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
9670         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
9671   }
9672 
9673   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9674       : Base(Base), Index(Index) {}
9675 };
9676 
9677 } // end anonymous namespace
9678 
9679 /// When generating a defaulted copy or move assignment operator, if a field
9680 /// should be copied with __builtin_memcpy rather than via explicit assignments,
9681 /// do so. This optimization only applies for arrays of scalars, and for arrays
9682 /// of class type where the selected copy/move-assignment operator is trivial.
9683 static StmtResult
9684 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
9685                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
9686   // Compute the size of the memory buffer to be copied.
9687   QualType SizeType = S.Context.getSizeType();
9688   llvm::APInt Size(S.Context.getTypeSize(SizeType),
9689                    S.Context.getTypeSizeInChars(T).getQuantity());
9690 
9691   // Take the address of the field references for "from" and "to". We
9692   // directly construct UnaryOperators here because semantic analysis
9693   // does not permit us to take the address of an xvalue.
9694   Expr *From = FromB.build(S, Loc);
9695   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9696                          S.Context.getPointerType(From->getType()),
9697                          VK_RValue, OK_Ordinary, Loc);
9698   Expr *To = ToB.build(S, Loc);
9699   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9700                        S.Context.getPointerType(To->getType()),
9701                        VK_RValue, OK_Ordinary, Loc);
9702 
9703   const Type *E = T->getBaseElementTypeUnsafe();
9704   bool NeedsCollectableMemCpy =
9705     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9706 
9707   // Create a reference to the __builtin_objc_memmove_collectable function
9708   StringRef MemCpyName = NeedsCollectableMemCpy ?
9709     "__builtin_objc_memmove_collectable" :
9710     "__builtin_memcpy";
9711   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9712                  Sema::LookupOrdinaryName);
9713   S.LookupName(R, S.TUScope, true);
9714 
9715   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9716   if (!MemCpy)
9717     // Something went horribly wrong earlier, and we will have complained
9718     // about it.
9719     return StmtError();
9720 
9721   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
9722                                             VK_RValue, Loc, nullptr);
9723   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9724 
9725   Expr *CallArgs[] = {
9726     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9727   };
9728   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
9729                                     Loc, CallArgs, Loc);
9730 
9731   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
9732   return Call.getAs<Stmt>();
9733 }
9734 
9735 /// \brief Builds a statement that copies/moves the given entity from \p From to
9736 /// \c To.
9737 ///
9738 /// This routine is used to copy/move the members of a class with an
9739 /// implicitly-declared copy/move assignment operator. When the entities being
9740 /// copied are arrays, this routine builds for loops to copy them.
9741 ///
9742 /// \param S The Sema object used for type-checking.
9743 ///
9744 /// \param Loc The location where the implicit copy/move is being generated.
9745 ///
9746 /// \param T The type of the expressions being copied/moved. Both expressions
9747 /// must have this type.
9748 ///
9749 /// \param To The expression we are copying/moving to.
9750 ///
9751 /// \param From The expression we are copying/moving from.
9752 ///
9753 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
9754 /// Otherwise, it's a non-static member subobject.
9755 ///
9756 /// \param Copying Whether we're copying or moving.
9757 ///
9758 /// \param Depth Internal parameter recording the depth of the recursion.
9759 ///
9760 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9761 /// if a memcpy should be used instead.
9762 static StmtResult
9763 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
9764                                  const ExprBuilder &To, const ExprBuilder &From,
9765                                  bool CopyingBaseSubobject, bool Copying,
9766                                  unsigned Depth = 0) {
9767   // C++11 [class.copy]p28:
9768   //   Each subobject is assigned in the manner appropriate to its type:
9769   //
9770   //     - if the subobject is of class type, as if by a call to operator= with
9771   //       the subobject as the object expression and the corresponding
9772   //       subobject of x as a single function argument (as if by explicit
9773   //       qualification; that is, ignoring any possible virtual overriding
9774   //       functions in more derived classes);
9775   //
9776   // C++03 [class.copy]p13:
9777   //     - if the subobject is of class type, the copy assignment operator for
9778   //       the class is used (as if by explicit qualification; that is,
9779   //       ignoring any possible virtual overriding functions in more derived
9780   //       classes);
9781   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9782     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9783 
9784     // Look for operator=.
9785     DeclarationName Name
9786       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9787     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9788     S.LookupQualifiedName(OpLookup, ClassDecl, false);
9789 
9790     // Prior to C++11, filter out any result that isn't a copy/move-assignment
9791     // operator.
9792     if (!S.getLangOpts().CPlusPlus11) {
9793       LookupResult::Filter F = OpLookup.makeFilter();
9794       while (F.hasNext()) {
9795         NamedDecl *D = F.next();
9796         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9797           if (Method->isCopyAssignmentOperator() ||
9798               (!Copying && Method->isMoveAssignmentOperator()))
9799             continue;
9800 
9801         F.erase();
9802       }
9803       F.done();
9804     }
9805 
9806     // Suppress the protected check (C++ [class.protected]) for each of the
9807     // assignment operators we found. This strange dance is required when
9808     // we're assigning via a base classes's copy-assignment operator. To
9809     // ensure that we're getting the right base class subobject (without
9810     // ambiguities), we need to cast "this" to that subobject type; to
9811     // ensure that we don't go through the virtual call mechanism, we need
9812     // to qualify the operator= name with the base class (see below). However,
9813     // this means that if the base class has a protected copy assignment
9814     // operator, the protected member access check will fail. So, we
9815     // rewrite "protected" access to "public" access in this case, since we
9816     // know by construction that we're calling from a derived class.
9817     if (CopyingBaseSubobject) {
9818       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9819            L != LEnd; ++L) {
9820         if (L.getAccess() == AS_protected)
9821           L.setAccess(AS_public);
9822       }
9823     }
9824 
9825     // Create the nested-name-specifier that will be used to qualify the
9826     // reference to operator=; this is required to suppress the virtual
9827     // call mechanism.
9828     CXXScopeSpec SS;
9829     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
9830     SS.MakeTrivial(S.Context,
9831                    NestedNameSpecifier::Create(S.Context, nullptr, false,
9832                                                CanonicalT),
9833                    Loc);
9834 
9835     // Create the reference to operator=.
9836     ExprResult OpEqualRef
9837       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9838                                    SS, /*TemplateKWLoc=*/SourceLocation(),
9839                                    /*FirstQualifierInScope=*/nullptr,
9840                                    OpLookup,
9841                                    /*TemplateArgs=*/nullptr,
9842                                    /*SuppressQualifierCheck=*/true);
9843     if (OpEqualRef.isInvalid())
9844       return StmtError();
9845 
9846     // Build the call to the assignment operator.
9847 
9848     Expr *FromInst = From.build(S, Loc);
9849     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
9850                                                   OpEqualRef.getAs<Expr>(),
9851                                                   Loc, FromInst, Loc);
9852     if (Call.isInvalid())
9853       return StmtError();
9854 
9855     // If we built a call to a trivial 'operator=' while copying an array,
9856     // bail out. We'll replace the whole shebang with a memcpy.
9857     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9858     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9859       return StmtResult((Stmt*)nullptr);
9860 
9861     // Convert to an expression-statement, and clean up any produced
9862     // temporaries.
9863     return S.ActOnExprStmt(Call);
9864   }
9865 
9866   //     - if the subobject is of scalar type, the built-in assignment
9867   //       operator is used.
9868   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9869   if (!ArrayTy) {
9870     ExprResult Assignment = S.CreateBuiltinBinOp(
9871         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9872     if (Assignment.isInvalid())
9873       return StmtError();
9874     return S.ActOnExprStmt(Assignment);
9875   }
9876 
9877   //     - if the subobject is an array, each element is assigned, in the
9878   //       manner appropriate to the element type;
9879 
9880   // Construct a loop over the array bounds, e.g.,
9881   //
9882   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9883   //
9884   // that will copy each of the array elements.
9885   QualType SizeType = S.Context.getSizeType();
9886 
9887   // Create the iteration variable.
9888   IdentifierInfo *IterationVarName = nullptr;
9889   {
9890     SmallString<8> Str;
9891     llvm::raw_svector_ostream OS(Str);
9892     OS << "__i" << Depth;
9893     IterationVarName = &S.Context.Idents.get(OS.str());
9894   }
9895   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9896                                           IterationVarName, SizeType,
9897                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9898                                           SC_None);
9899 
9900   // Initialize the iteration variable to zero.
9901   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9902   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9903 
9904   // Creates a reference to the iteration variable.
9905   RefBuilder IterationVarRef(IterationVar, SizeType);
9906   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9907 
9908   // Create the DeclStmt that holds the iteration variable.
9909   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9910 
9911   // Subscript the "from" and "to" expressions with the iteration variable.
9912   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9913   MoveCastBuilder FromIndexMove(FromIndexCopy);
9914   const ExprBuilder *FromIndex;
9915   if (Copying)
9916     FromIndex = &FromIndexCopy;
9917   else
9918     FromIndex = &FromIndexMove;
9919 
9920   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9921 
9922   // Build the copy/move for an individual element of the array.
9923   StmtResult Copy =
9924     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9925                                      ToIndex, *FromIndex, CopyingBaseSubobject,
9926                                      Copying, Depth + 1);
9927   // Bail out if copying fails or if we determined that we should use memcpy.
9928   if (Copy.isInvalid() || !Copy.get())
9929     return Copy;
9930 
9931   // Create the comparison against the array bound.
9932   llvm::APInt Upper
9933     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9934   Expr *Comparison
9935     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9936                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9937                                      BO_NE, S.Context.BoolTy,
9938                                      VK_RValue, OK_Ordinary, Loc, false);
9939 
9940   // Create the pre-increment of the iteration variable.
9941   Expr *Increment
9942     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9943                                     SizeType, VK_LValue, OK_Ordinary, Loc);
9944 
9945   // Construct the loop that copies all elements of this array.
9946   return S.ActOnForStmt(Loc, Loc, InitStmt,
9947                         S.MakeFullExpr(Comparison),
9948                         nullptr, S.MakeFullDiscardedValueExpr(Increment),
9949                         Loc, Copy.get());
9950 }
9951 
9952 static StmtResult
9953 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9954                       const ExprBuilder &To, const ExprBuilder &From,
9955                       bool CopyingBaseSubobject, bool Copying) {
9956   // Maybe we should use a memcpy?
9957   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9958       T.isTriviallyCopyableType(S.Context))
9959     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9960 
9961   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9962                                                      CopyingBaseSubobject,
9963                                                      Copying, 0));
9964 
9965   // If we ended up picking a trivial assignment operator for an array of a
9966   // non-trivially-copyable class type, just emit a memcpy.
9967   if (!Result.isInvalid() && !Result.get())
9968     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9969 
9970   return Result;
9971 }
9972 
9973 Sema::ImplicitExceptionSpecification
9974 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9975   CXXRecordDecl *ClassDecl = MD->getParent();
9976 
9977   ImplicitExceptionSpecification ExceptSpec(*this);
9978   if (ClassDecl->isInvalidDecl())
9979     return ExceptSpec;
9980 
9981   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9982   assert(T->getNumParams() == 1 && "not a copy assignment op");
9983   unsigned ArgQuals =
9984       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
9985 
9986   // C++ [except.spec]p14:
9987   //   An implicitly declared special member function (Clause 12) shall have an
9988   //   exception-specification. [...]
9989 
9990   // It is unspecified whether or not an implicit copy assignment operator
9991   // attempts to deduplicate calls to assignment operators of virtual bases are
9992   // made. As such, this exception specification is effectively unspecified.
9993   // Based on a similar decision made for constness in C++0x, we're erring on
9994   // the side of assuming such calls to be made regardless of whether they
9995   // actually happen.
9996   for (const auto &Base : ClassDecl->bases()) {
9997     if (Base.isVirtual())
9998       continue;
9999 
10000     CXXRecordDecl *BaseClassDecl
10001       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10002     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10003                                                             ArgQuals, false, 0))
10004       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10005   }
10006 
10007   for (const auto &Base : ClassDecl->vbases()) {
10008     CXXRecordDecl *BaseClassDecl
10009       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10010     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10011                                                             ArgQuals, false, 0))
10012       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10013   }
10014 
10015   for (const auto *Field : ClassDecl->fields()) {
10016     QualType FieldType = Context.getBaseElementType(Field->getType());
10017     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10018       if (CXXMethodDecl *CopyAssign =
10019           LookupCopyingAssignment(FieldClassDecl,
10020                                   ArgQuals | FieldType.getCVRQualifiers(),
10021                                   false, 0))
10022         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10023     }
10024   }
10025 
10026   return ExceptSpec;
10027 }
10028 
10029 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10030   // Note: The following rules are largely analoguous to the copy
10031   // constructor rules. Note that virtual bases are not taken into account
10032   // for determining the argument type of the operator. Note also that
10033   // operators taking an object instead of a reference are allowed.
10034   assert(ClassDecl->needsImplicitCopyAssignment());
10035 
10036   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10037   if (DSM.isAlreadyBeingDeclared())
10038     return nullptr;
10039 
10040   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10041   QualType RetType = Context.getLValueReferenceType(ArgType);
10042   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10043   if (Const)
10044     ArgType = ArgType.withConst();
10045   ArgType = Context.getLValueReferenceType(ArgType);
10046 
10047   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10048                                                      CXXCopyAssignment,
10049                                                      Const);
10050 
10051   //   An implicitly-declared copy assignment operator is an inline public
10052   //   member of its class.
10053   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10054   SourceLocation ClassLoc = ClassDecl->getLocation();
10055   DeclarationNameInfo NameInfo(Name, ClassLoc);
10056   CXXMethodDecl *CopyAssignment =
10057       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10058                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10059                             /*isInline=*/true, Constexpr, SourceLocation());
10060   CopyAssignment->setAccess(AS_public);
10061   CopyAssignment->setDefaulted();
10062   CopyAssignment->setImplicit();
10063 
10064   if (getLangOpts().CUDA) {
10065     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10066                                             CopyAssignment,
10067                                             /* ConstRHS */ Const,
10068                                             /* Diagnose */ false);
10069   }
10070 
10071   // Build an exception specification pointing back at this member.
10072   FunctionProtoType::ExtProtoInfo EPI =
10073       getImplicitMethodEPI(*this, CopyAssignment);
10074   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10075 
10076   // Add the parameter to the operator.
10077   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
10078                                                ClassLoc, ClassLoc,
10079                                                /*Id=*/nullptr, ArgType,
10080                                                /*TInfo=*/nullptr, SC_None,
10081                                                nullptr);
10082   CopyAssignment->setParams(FromParam);
10083 
10084   AddOverriddenMethods(ClassDecl, CopyAssignment);
10085 
10086   CopyAssignment->setTrivial(
10087     ClassDecl->needsOverloadResolutionForCopyAssignment()
10088       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
10089       : ClassDecl->hasTrivialCopyAssignment());
10090 
10091   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
10092     SetDeclDeleted(CopyAssignment, ClassLoc);
10093 
10094   // Note that we have added this copy-assignment operator.
10095   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
10096 
10097   if (Scope *S = getScopeForContext(ClassDecl))
10098     PushOnScopeChains(CopyAssignment, S, false);
10099   ClassDecl->addDecl(CopyAssignment);
10100 
10101   return CopyAssignment;
10102 }
10103 
10104 /// Diagnose an implicit copy operation for a class which is odr-used, but
10105 /// which is deprecated because the class has a user-declared copy constructor,
10106 /// copy assignment operator, or destructor.
10107 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
10108                                             SourceLocation UseLoc) {
10109   assert(CopyOp->isImplicit());
10110 
10111   CXXRecordDecl *RD = CopyOp->getParent();
10112   CXXMethodDecl *UserDeclaredOperation = nullptr;
10113 
10114   // In Microsoft mode, assignment operations don't affect constructors and
10115   // vice versa.
10116   if (RD->hasUserDeclaredDestructor()) {
10117     UserDeclaredOperation = RD->getDestructor();
10118   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
10119              RD->hasUserDeclaredCopyConstructor() &&
10120              !S.getLangOpts().MSVCCompat) {
10121     // Find any user-declared copy constructor.
10122     for (auto *I : RD->ctors()) {
10123       if (I->isCopyConstructor()) {
10124         UserDeclaredOperation = I;
10125         break;
10126       }
10127     }
10128     assert(UserDeclaredOperation);
10129   } else if (isa<CXXConstructorDecl>(CopyOp) &&
10130              RD->hasUserDeclaredCopyAssignment() &&
10131              !S.getLangOpts().MSVCCompat) {
10132     // Find any user-declared move assignment operator.
10133     for (auto *I : RD->methods()) {
10134       if (I->isCopyAssignmentOperator()) {
10135         UserDeclaredOperation = I;
10136         break;
10137       }
10138     }
10139     assert(UserDeclaredOperation);
10140   }
10141 
10142   if (UserDeclaredOperation) {
10143     S.Diag(UserDeclaredOperation->getLocation(),
10144          diag::warn_deprecated_copy_operation)
10145       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
10146       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
10147     S.Diag(UseLoc, diag::note_member_synthesized_at)
10148       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
10149                                           : Sema::CXXCopyAssignment)
10150       << RD;
10151   }
10152 }
10153 
10154 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
10155                                         CXXMethodDecl *CopyAssignOperator) {
10156   assert((CopyAssignOperator->isDefaulted() &&
10157           CopyAssignOperator->isOverloadedOperator() &&
10158           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
10159           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
10160           !CopyAssignOperator->isDeleted()) &&
10161          "DefineImplicitCopyAssignment called for wrong function");
10162 
10163   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
10164 
10165   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
10166     CopyAssignOperator->setInvalidDecl();
10167     return;
10168   }
10169 
10170   // C++11 [class.copy]p18:
10171   //   The [definition of an implicitly declared copy assignment operator] is
10172   //   deprecated if the class has a user-declared copy constructor or a
10173   //   user-declared destructor.
10174   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
10175     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
10176 
10177   CopyAssignOperator->markUsed(Context);
10178 
10179   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
10180   DiagnosticErrorTrap Trap(Diags);
10181 
10182   // C++0x [class.copy]p30:
10183   //   The implicitly-defined or explicitly-defaulted copy assignment operator
10184   //   for a non-union class X performs memberwise copy assignment of its
10185   //   subobjects. The direct base classes of X are assigned first, in the
10186   //   order of their declaration in the base-specifier-list, and then the
10187   //   immediate non-static data members of X are assigned, in the order in
10188   //   which they were declared in the class definition.
10189 
10190   // The statements that form the synthesized function body.
10191   SmallVector<Stmt*, 8> Statements;
10192 
10193   // The parameter for the "other" object, which we are copying from.
10194   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
10195   Qualifiers OtherQuals = Other->getType().getQualifiers();
10196   QualType OtherRefType = Other->getType();
10197   if (const LValueReferenceType *OtherRef
10198                                 = OtherRefType->getAs<LValueReferenceType>()) {
10199     OtherRefType = OtherRef->getPointeeType();
10200     OtherQuals = OtherRefType.getQualifiers();
10201   }
10202 
10203   // Our location for everything implicitly-generated.
10204   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
10205                            ? CopyAssignOperator->getLocEnd()
10206                            : CopyAssignOperator->getLocation();
10207 
10208   // Builds a DeclRefExpr for the "other" object.
10209   RefBuilder OtherRef(Other, OtherRefType);
10210 
10211   // Builds the "this" pointer.
10212   ThisBuilder This;
10213 
10214   // Assign base classes.
10215   bool Invalid = false;
10216   for (auto &Base : ClassDecl->bases()) {
10217     // Form the assignment:
10218     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
10219     QualType BaseType = Base.getType().getUnqualifiedType();
10220     if (!BaseType->isRecordType()) {
10221       Invalid = true;
10222       continue;
10223     }
10224 
10225     CXXCastPath BasePath;
10226     BasePath.push_back(&Base);
10227 
10228     // Construct the "from" expression, which is an implicit cast to the
10229     // appropriately-qualified base type.
10230     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
10231                      VK_LValue, BasePath);
10232 
10233     // Dereference "this".
10234     DerefBuilder DerefThis(This);
10235     CastBuilder To(DerefThis,
10236                    Context.getCVRQualifiedType(
10237                        BaseType, CopyAssignOperator->getTypeQualifiers()),
10238                    VK_LValue, BasePath);
10239 
10240     // Build the copy.
10241     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
10242                                             To, From,
10243                                             /*CopyingBaseSubobject=*/true,
10244                                             /*Copying=*/true);
10245     if (Copy.isInvalid()) {
10246       Diag(CurrentLocation, diag::note_member_synthesized_at)
10247         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10248       CopyAssignOperator->setInvalidDecl();
10249       return;
10250     }
10251 
10252     // Success! Record the copy.
10253     Statements.push_back(Copy.getAs<Expr>());
10254   }
10255 
10256   // Assign non-static members.
10257   for (auto *Field : ClassDecl->fields()) {
10258     // FIXME: We should form some kind of AST representation for the implied
10259     // memcpy in a union copy operation.
10260     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10261       continue;
10262 
10263     if (Field->isInvalidDecl()) {
10264       Invalid = true;
10265       continue;
10266     }
10267 
10268     // Check for members of reference type; we can't copy those.
10269     if (Field->getType()->isReferenceType()) {
10270       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10271         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10272       Diag(Field->getLocation(), diag::note_declared_at);
10273       Diag(CurrentLocation, diag::note_member_synthesized_at)
10274         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10275       Invalid = true;
10276       continue;
10277     }
10278 
10279     // Check for members of const-qualified, non-class type.
10280     QualType BaseType = Context.getBaseElementType(Field->getType());
10281     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10282       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10283         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10284       Diag(Field->getLocation(), diag::note_declared_at);
10285       Diag(CurrentLocation, diag::note_member_synthesized_at)
10286         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10287       Invalid = true;
10288       continue;
10289     }
10290 
10291     // Suppress assigning zero-width bitfields.
10292     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10293       continue;
10294 
10295     QualType FieldType = Field->getType().getNonReferenceType();
10296     if (FieldType->isIncompleteArrayType()) {
10297       assert(ClassDecl->hasFlexibleArrayMember() &&
10298              "Incomplete array type is not valid");
10299       continue;
10300     }
10301 
10302     // Build references to the field in the object we're copying from and to.
10303     CXXScopeSpec SS; // Intentionally empty
10304     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10305                               LookupMemberName);
10306     MemberLookup.addDecl(Field);
10307     MemberLookup.resolveKind();
10308 
10309     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10310 
10311     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
10312 
10313     // Build the copy of this field.
10314     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
10315                                             To, From,
10316                                             /*CopyingBaseSubobject=*/false,
10317                                             /*Copying=*/true);
10318     if (Copy.isInvalid()) {
10319       Diag(CurrentLocation, diag::note_member_synthesized_at)
10320         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10321       CopyAssignOperator->setInvalidDecl();
10322       return;
10323     }
10324 
10325     // Success! Record the copy.
10326     Statements.push_back(Copy.getAs<Stmt>());
10327   }
10328 
10329   if (!Invalid) {
10330     // Add a "return *this;"
10331     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10332 
10333     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10334     if (Return.isInvalid())
10335       Invalid = true;
10336     else {
10337       Statements.push_back(Return.getAs<Stmt>());
10338 
10339       if (Trap.hasErrorOccurred()) {
10340         Diag(CurrentLocation, diag::note_member_synthesized_at)
10341           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10342         Invalid = true;
10343       }
10344     }
10345   }
10346 
10347   // The exception specification is needed because we are defining the
10348   // function.
10349   ResolveExceptionSpec(CurrentLocation,
10350                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10351 
10352   if (Invalid) {
10353     CopyAssignOperator->setInvalidDecl();
10354     return;
10355   }
10356 
10357   StmtResult Body;
10358   {
10359     CompoundScopeRAII CompoundScope(*this);
10360     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10361                              /*isStmtExpr=*/false);
10362     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10363   }
10364   CopyAssignOperator->setBody(Body.getAs<Stmt>());
10365 
10366   if (ASTMutationListener *L = getASTMutationListener()) {
10367     L->CompletedImplicitDefinition(CopyAssignOperator);
10368   }
10369 }
10370 
10371 Sema::ImplicitExceptionSpecification
10372 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10373   CXXRecordDecl *ClassDecl = MD->getParent();
10374 
10375   ImplicitExceptionSpecification ExceptSpec(*this);
10376   if (ClassDecl->isInvalidDecl())
10377     return ExceptSpec;
10378 
10379   // C++0x [except.spec]p14:
10380   //   An implicitly declared special member function (Clause 12) shall have an
10381   //   exception-specification. [...]
10382 
10383   // It is unspecified whether or not an implicit move assignment operator
10384   // attempts to deduplicate calls to assignment operators of virtual bases are
10385   // made. As such, this exception specification is effectively unspecified.
10386   // Based on a similar decision made for constness in C++0x, we're erring on
10387   // the side of assuming such calls to be made regardless of whether they
10388   // actually happen.
10389   // Note that a move constructor is not implicitly declared when there are
10390   // virtual bases, but it can still be user-declared and explicitly defaulted.
10391   for (const auto &Base : ClassDecl->bases()) {
10392     if (Base.isVirtual())
10393       continue;
10394 
10395     CXXRecordDecl *BaseClassDecl
10396       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10397     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10398                                                            0, false, 0))
10399       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10400   }
10401 
10402   for (const auto &Base : ClassDecl->vbases()) {
10403     CXXRecordDecl *BaseClassDecl
10404       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10405     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
10406                                                            0, false, 0))
10407       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
10408   }
10409 
10410   for (const auto *Field : ClassDecl->fields()) {
10411     QualType FieldType = Context.getBaseElementType(Field->getType());
10412     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10413       if (CXXMethodDecl *MoveAssign =
10414               LookupMovingAssignment(FieldClassDecl,
10415                                      FieldType.getCVRQualifiers(),
10416                                      false, 0))
10417         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
10418     }
10419   }
10420 
10421   return ExceptSpec;
10422 }
10423 
10424 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
10425   assert(ClassDecl->needsImplicitMoveAssignment());
10426 
10427   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10428   if (DSM.isAlreadyBeingDeclared())
10429     return nullptr;
10430 
10431   // Note: The following rules are largely analoguous to the move
10432   // constructor rules.
10433 
10434   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10435   QualType RetType = Context.getLValueReferenceType(ArgType);
10436   ArgType = Context.getRValueReferenceType(ArgType);
10437 
10438   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10439                                                      CXXMoveAssignment,
10440                                                      false);
10441 
10442   //   An implicitly-declared move assignment operator is an inline public
10443   //   member of its class.
10444   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10445   SourceLocation ClassLoc = ClassDecl->getLocation();
10446   DeclarationNameInfo NameInfo(Name, ClassLoc);
10447   CXXMethodDecl *MoveAssignment =
10448       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10449                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10450                             /*isInline=*/true, Constexpr, SourceLocation());
10451   MoveAssignment->setAccess(AS_public);
10452   MoveAssignment->setDefaulted();
10453   MoveAssignment->setImplicit();
10454 
10455   if (getLangOpts().CUDA) {
10456     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10457                                             MoveAssignment,
10458                                             /* ConstRHS */ false,
10459                                             /* Diagnose */ false);
10460   }
10461 
10462   // Build an exception specification pointing back at this member.
10463   FunctionProtoType::ExtProtoInfo EPI =
10464       getImplicitMethodEPI(*this, MoveAssignment);
10465   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
10466 
10467   // Add the parameter to the operator.
10468   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
10469                                                ClassLoc, ClassLoc,
10470                                                /*Id=*/nullptr, ArgType,
10471                                                /*TInfo=*/nullptr, SC_None,
10472                                                nullptr);
10473   MoveAssignment->setParams(FromParam);
10474 
10475   AddOverriddenMethods(ClassDecl, MoveAssignment);
10476 
10477   MoveAssignment->setTrivial(
10478     ClassDecl->needsOverloadResolutionForMoveAssignment()
10479       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10480       : ClassDecl->hasTrivialMoveAssignment());
10481 
10482   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
10483     ClassDecl->setImplicitMoveAssignmentIsDeleted();
10484     SetDeclDeleted(MoveAssignment, ClassLoc);
10485   }
10486 
10487   // Note that we have added this copy-assignment operator.
10488   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10489 
10490   if (Scope *S = getScopeForContext(ClassDecl))
10491     PushOnScopeChains(MoveAssignment, S, false);
10492   ClassDecl->addDecl(MoveAssignment);
10493 
10494   return MoveAssignment;
10495 }
10496 
10497 /// Check if we're implicitly defining a move assignment operator for a class
10498 /// with virtual bases. Such a move assignment might move-assign the virtual
10499 /// base multiple times.
10500 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10501                                                SourceLocation CurrentLocation) {
10502   assert(!Class->isDependentContext() && "should not define dependent move");
10503 
10504   // Only a virtual base could get implicitly move-assigned multiple times.
10505   // Only a non-trivial move assignment can observe this. We only want to
10506   // diagnose if we implicitly define an assignment operator that assigns
10507   // two base classes, both of which move-assign the same virtual base.
10508   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10509       Class->getNumBases() < 2)
10510     return;
10511 
10512   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10513   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10514   VBaseMap VBases;
10515 
10516   for (auto &BI : Class->bases()) {
10517     Worklist.push_back(&BI);
10518     while (!Worklist.empty()) {
10519       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10520       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10521 
10522       // If the base has no non-trivial move assignment operators,
10523       // we don't care about moves from it.
10524       if (!Base->hasNonTrivialMoveAssignment())
10525         continue;
10526 
10527       // If there's nothing virtual here, skip it.
10528       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10529         continue;
10530 
10531       // If we're not actually going to call a move assignment for this base,
10532       // or the selected move assignment is trivial, skip it.
10533       Sema::SpecialMemberOverloadResult *SMOR =
10534         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10535                               /*ConstArg*/false, /*VolatileArg*/false,
10536                               /*RValueThis*/true, /*ConstThis*/false,
10537                               /*VolatileThis*/false);
10538       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10539           !SMOR->getMethod()->isMoveAssignmentOperator())
10540         continue;
10541 
10542       if (BaseSpec->isVirtual()) {
10543         // We're going to move-assign this virtual base, and its move
10544         // assignment operator is not trivial. If this can happen for
10545         // multiple distinct direct bases of Class, diagnose it. (If it
10546         // only happens in one base, we'll diagnose it when synthesizing
10547         // that base class's move assignment operator.)
10548         CXXBaseSpecifier *&Existing =
10549             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
10550                 .first->second;
10551         if (Existing && Existing != &BI) {
10552           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10553             << Class << Base;
10554           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10555             << (Base->getCanonicalDecl() ==
10556                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10557             << Base << Existing->getType() << Existing->getSourceRange();
10558           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
10559             << (Base->getCanonicalDecl() ==
10560                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10561             << Base << BI.getType() << BaseSpec->getSourceRange();
10562 
10563           // Only diagnose each vbase once.
10564           Existing = nullptr;
10565         }
10566       } else {
10567         // Only walk over bases that have defaulted move assignment operators.
10568         // We assume that any user-provided move assignment operator handles
10569         // the multiple-moves-of-vbase case itself somehow.
10570         if (!SMOR->getMethod()->isDefaulted())
10571           continue;
10572 
10573         // We're going to move the base classes of Base. Add them to the list.
10574         for (auto &BI : Base->bases())
10575           Worklist.push_back(&BI);
10576       }
10577     }
10578   }
10579 }
10580 
10581 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10582                                         CXXMethodDecl *MoveAssignOperator) {
10583   assert((MoveAssignOperator->isDefaulted() &&
10584           MoveAssignOperator->isOverloadedOperator() &&
10585           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
10586           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10587           !MoveAssignOperator->isDeleted()) &&
10588          "DefineImplicitMoveAssignment called for wrong function");
10589 
10590   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10591 
10592   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10593     MoveAssignOperator->setInvalidDecl();
10594     return;
10595   }
10596 
10597   MoveAssignOperator->markUsed(Context);
10598 
10599   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
10600   DiagnosticErrorTrap Trap(Diags);
10601 
10602   // C++0x [class.copy]p28:
10603   //   The implicitly-defined or move assignment operator for a non-union class
10604   //   X performs memberwise move assignment of its subobjects. The direct base
10605   //   classes of X are assigned first, in the order of their declaration in the
10606   //   base-specifier-list, and then the immediate non-static data members of X
10607   //   are assigned, in the order in which they were declared in the class
10608   //   definition.
10609 
10610   // Issue a warning if our implicit move assignment operator will move
10611   // from a virtual base more than once.
10612   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
10613 
10614   // The statements that form the synthesized function body.
10615   SmallVector<Stmt*, 8> Statements;
10616 
10617   // The parameter for the "other" object, which we are move from.
10618   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10619   QualType OtherRefType = Other->getType()->
10620       getAs<RValueReferenceType>()->getPointeeType();
10621   assert(!OtherRefType.getQualifiers() &&
10622          "Bad argument type of defaulted move assignment");
10623 
10624   // Our location for everything implicitly-generated.
10625   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10626                            ? MoveAssignOperator->getLocEnd()
10627                            : MoveAssignOperator->getLocation();
10628 
10629   // Builds a reference to the "other" object.
10630   RefBuilder OtherRef(Other, OtherRefType);
10631   // Cast to rvalue.
10632   MoveCastBuilder MoveOther(OtherRef);
10633 
10634   // Builds the "this" pointer.
10635   ThisBuilder This;
10636 
10637   // Assign base classes.
10638   bool Invalid = false;
10639   for (auto &Base : ClassDecl->bases()) {
10640     // C++11 [class.copy]p28:
10641     //   It is unspecified whether subobjects representing virtual base classes
10642     //   are assigned more than once by the implicitly-defined copy assignment
10643     //   operator.
10644     // FIXME: Do not assign to a vbase that will be assigned by some other base
10645     // class. For a move-assignment, this can result in the vbase being moved
10646     // multiple times.
10647 
10648     // Form the assignment:
10649     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
10650     QualType BaseType = Base.getType().getUnqualifiedType();
10651     if (!BaseType->isRecordType()) {
10652       Invalid = true;
10653       continue;
10654     }
10655 
10656     CXXCastPath BasePath;
10657     BasePath.push_back(&Base);
10658 
10659     // Construct the "from" expression, which is an implicit cast to the
10660     // appropriately-qualified base type.
10661     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
10662 
10663     // Dereference "this".
10664     DerefBuilder DerefThis(This);
10665 
10666     // Implicitly cast "this" to the appropriately-qualified base type.
10667     CastBuilder To(DerefThis,
10668                    Context.getCVRQualifiedType(
10669                        BaseType, MoveAssignOperator->getTypeQualifiers()),
10670                    VK_LValue, BasePath);
10671 
10672     // Build the move.
10673     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
10674                                             To, From,
10675                                             /*CopyingBaseSubobject=*/true,
10676                                             /*Copying=*/false);
10677     if (Move.isInvalid()) {
10678       Diag(CurrentLocation, diag::note_member_synthesized_at)
10679         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10680       MoveAssignOperator->setInvalidDecl();
10681       return;
10682     }
10683 
10684     // Success! Record the move.
10685     Statements.push_back(Move.getAs<Expr>());
10686   }
10687 
10688   // Assign non-static members.
10689   for (auto *Field : ClassDecl->fields()) {
10690     // FIXME: We should form some kind of AST representation for the implied
10691     // memcpy in a union copy operation.
10692     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
10693       continue;
10694 
10695     if (Field->isInvalidDecl()) {
10696       Invalid = true;
10697       continue;
10698     }
10699 
10700     // Check for members of reference type; we can't move those.
10701     if (Field->getType()->isReferenceType()) {
10702       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10703         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10704       Diag(Field->getLocation(), diag::note_declared_at);
10705       Diag(CurrentLocation, diag::note_member_synthesized_at)
10706         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10707       Invalid = true;
10708       continue;
10709     }
10710 
10711     // Check for members of const-qualified, non-class type.
10712     QualType BaseType = Context.getBaseElementType(Field->getType());
10713     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10714       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10715         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10716       Diag(Field->getLocation(), diag::note_declared_at);
10717       Diag(CurrentLocation, diag::note_member_synthesized_at)
10718         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10719       Invalid = true;
10720       continue;
10721     }
10722 
10723     // Suppress assigning zero-width bitfields.
10724     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10725       continue;
10726 
10727     QualType FieldType = Field->getType().getNonReferenceType();
10728     if (FieldType->isIncompleteArrayType()) {
10729       assert(ClassDecl->hasFlexibleArrayMember() &&
10730              "Incomplete array type is not valid");
10731       continue;
10732     }
10733 
10734     // Build references to the field in the object we're copying from and to.
10735     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10736                               LookupMemberName);
10737     MemberLookup.addDecl(Field);
10738     MemberLookup.resolveKind();
10739     MemberBuilder From(MoveOther, OtherRefType,
10740                        /*IsArrow=*/false, MemberLookup);
10741     MemberBuilder To(This, getCurrentThisType(),
10742                      /*IsArrow=*/true, MemberLookup);
10743 
10744     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
10745         "Member reference with rvalue base must be rvalue except for reference "
10746         "members, which aren't allowed for move assignment.");
10747 
10748     // Build the move of this field.
10749     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
10750                                             To, From,
10751                                             /*CopyingBaseSubobject=*/false,
10752                                             /*Copying=*/false);
10753     if (Move.isInvalid()) {
10754       Diag(CurrentLocation, diag::note_member_synthesized_at)
10755         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10756       MoveAssignOperator->setInvalidDecl();
10757       return;
10758     }
10759 
10760     // Success! Record the copy.
10761     Statements.push_back(Move.getAs<Stmt>());
10762   }
10763 
10764   if (!Invalid) {
10765     // Add a "return *this;"
10766     ExprResult ThisObj =
10767         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10768 
10769     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
10770     if (Return.isInvalid())
10771       Invalid = true;
10772     else {
10773       Statements.push_back(Return.getAs<Stmt>());
10774 
10775       if (Trap.hasErrorOccurred()) {
10776         Diag(CurrentLocation, diag::note_member_synthesized_at)
10777           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10778         Invalid = true;
10779       }
10780     }
10781   }
10782 
10783   // The exception specification is needed because we are defining the
10784   // function.
10785   ResolveExceptionSpec(CurrentLocation,
10786                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10787 
10788   if (Invalid) {
10789     MoveAssignOperator->setInvalidDecl();
10790     return;
10791   }
10792 
10793   StmtResult Body;
10794   {
10795     CompoundScopeRAII CompoundScope(*this);
10796     Body = ActOnCompoundStmt(Loc, Loc, Statements,
10797                              /*isStmtExpr=*/false);
10798     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10799   }
10800   MoveAssignOperator->setBody(Body.getAs<Stmt>());
10801 
10802   if (ASTMutationListener *L = getASTMutationListener()) {
10803     L->CompletedImplicitDefinition(MoveAssignOperator);
10804   }
10805 }
10806 
10807 Sema::ImplicitExceptionSpecification
10808 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10809   CXXRecordDecl *ClassDecl = MD->getParent();
10810 
10811   ImplicitExceptionSpecification ExceptSpec(*this);
10812   if (ClassDecl->isInvalidDecl())
10813     return ExceptSpec;
10814 
10815   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10816   assert(T->getNumParams() >= 1 && "not a copy ctor");
10817   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10818 
10819   // C++ [except.spec]p14:
10820   //   An implicitly declared special member function (Clause 12) shall have an
10821   //   exception-specification. [...]
10822   for (const auto &Base : ClassDecl->bases()) {
10823     // Virtual bases are handled below.
10824     if (Base.isVirtual())
10825       continue;
10826 
10827     CXXRecordDecl *BaseClassDecl
10828       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10829     if (CXXConstructorDecl *CopyConstructor =
10830           LookupCopyingConstructor(BaseClassDecl, Quals))
10831       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10832   }
10833   for (const auto &Base : ClassDecl->vbases()) {
10834     CXXRecordDecl *BaseClassDecl
10835       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10836     if (CXXConstructorDecl *CopyConstructor =
10837           LookupCopyingConstructor(BaseClassDecl, Quals))
10838       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
10839   }
10840   for (const auto *Field : ClassDecl->fields()) {
10841     QualType FieldType = Context.getBaseElementType(Field->getType());
10842     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10843       if (CXXConstructorDecl *CopyConstructor =
10844               LookupCopyingConstructor(FieldClassDecl,
10845                                        Quals | FieldType.getCVRQualifiers()))
10846       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10847     }
10848   }
10849 
10850   return ExceptSpec;
10851 }
10852 
10853 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10854                                                     CXXRecordDecl *ClassDecl) {
10855   // C++ [class.copy]p4:
10856   //   If the class definition does not explicitly declare a copy
10857   //   constructor, one is declared implicitly.
10858   assert(ClassDecl->needsImplicitCopyConstructor());
10859 
10860   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10861   if (DSM.isAlreadyBeingDeclared())
10862     return nullptr;
10863 
10864   QualType ClassType = Context.getTypeDeclType(ClassDecl);
10865   QualType ArgType = ClassType;
10866   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10867   if (Const)
10868     ArgType = ArgType.withConst();
10869   ArgType = Context.getLValueReferenceType(ArgType);
10870 
10871   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10872                                                      CXXCopyConstructor,
10873                                                      Const);
10874 
10875   DeclarationName Name
10876     = Context.DeclarationNames.getCXXConstructorName(
10877                                            Context.getCanonicalType(ClassType));
10878   SourceLocation ClassLoc = ClassDecl->getLocation();
10879   DeclarationNameInfo NameInfo(Name, ClassLoc);
10880 
10881   //   An implicitly-declared copy constructor is an inline public
10882   //   member of its class.
10883   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10884       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
10885       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10886       Constexpr);
10887   CopyConstructor->setAccess(AS_public);
10888   CopyConstructor->setDefaulted();
10889 
10890   if (getLangOpts().CUDA) {
10891     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10892                                             CopyConstructor,
10893                                             /* ConstRHS */ Const,
10894                                             /* Diagnose */ false);
10895   }
10896 
10897   // Build an exception specification pointing back at this member.
10898   FunctionProtoType::ExtProtoInfo EPI =
10899       getImplicitMethodEPI(*this, CopyConstructor);
10900   CopyConstructor->setType(
10901       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10902 
10903   // Add the parameter to the constructor.
10904   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10905                                                ClassLoc, ClassLoc,
10906                                                /*IdentifierInfo=*/nullptr,
10907                                                ArgType, /*TInfo=*/nullptr,
10908                                                SC_None, nullptr);
10909   CopyConstructor->setParams(FromParam);
10910 
10911   CopyConstructor->setTrivial(
10912     ClassDecl->needsOverloadResolutionForCopyConstructor()
10913       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10914       : ClassDecl->hasTrivialCopyConstructor());
10915 
10916   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10917     SetDeclDeleted(CopyConstructor, ClassLoc);
10918 
10919   // Note that we have declared this constructor.
10920   ++ASTContext::NumImplicitCopyConstructorsDeclared;
10921 
10922   if (Scope *S = getScopeForContext(ClassDecl))
10923     PushOnScopeChains(CopyConstructor, S, false);
10924   ClassDecl->addDecl(CopyConstructor);
10925 
10926   return CopyConstructor;
10927 }
10928 
10929 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10930                                    CXXConstructorDecl *CopyConstructor) {
10931   assert((CopyConstructor->isDefaulted() &&
10932           CopyConstructor->isCopyConstructor() &&
10933           !CopyConstructor->doesThisDeclarationHaveABody() &&
10934           !CopyConstructor->isDeleted()) &&
10935          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10936 
10937   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10938   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10939 
10940   // C++11 [class.copy]p7:
10941   //   The [definition of an implicitly declared copy constructor] is
10942   //   deprecated if the class has a user-declared copy assignment operator
10943   //   or a user-declared destructor.
10944   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10945     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10946 
10947   SynthesizedFunctionScope Scope(*this, CopyConstructor);
10948   DiagnosticErrorTrap Trap(Diags);
10949 
10950   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10951       Trap.hasErrorOccurred()) {
10952     Diag(CurrentLocation, diag::note_member_synthesized_at)
10953       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10954     CopyConstructor->setInvalidDecl();
10955   }  else {
10956     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10957                              ? CopyConstructor->getLocEnd()
10958                              : CopyConstructor->getLocation();
10959     Sema::CompoundScopeRAII CompoundScope(*this);
10960     CopyConstructor->setBody(
10961         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
10962   }
10963 
10964   // The exception specification is needed because we are defining the
10965   // function.
10966   ResolveExceptionSpec(CurrentLocation,
10967                        CopyConstructor->getType()->castAs<FunctionProtoType>());
10968 
10969   CopyConstructor->markUsed(Context);
10970   MarkVTableUsed(CurrentLocation, ClassDecl);
10971 
10972   if (ASTMutationListener *L = getASTMutationListener()) {
10973     L->CompletedImplicitDefinition(CopyConstructor);
10974   }
10975 }
10976 
10977 Sema::ImplicitExceptionSpecification
10978 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10979   CXXRecordDecl *ClassDecl = MD->getParent();
10980 
10981   // C++ [except.spec]p14:
10982   //   An implicitly declared special member function (Clause 12) shall have an
10983   //   exception-specification. [...]
10984   ImplicitExceptionSpecification ExceptSpec(*this);
10985   if (ClassDecl->isInvalidDecl())
10986     return ExceptSpec;
10987 
10988   // Direct base-class constructors.
10989   for (const auto &B : ClassDecl->bases()) {
10990     if (B.isVirtual()) // Handled below.
10991       continue;
10992 
10993     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10994       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10995       CXXConstructorDecl *Constructor =
10996           LookupMovingConstructor(BaseClassDecl, 0);
10997       // If this is a deleted function, add it anyway. This might be conformant
10998       // with the standard. This might not. I'm not sure. It might not matter.
10999       if (Constructor)
11000         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11001     }
11002   }
11003 
11004   // Virtual base-class constructors.
11005   for (const auto &B : ClassDecl->vbases()) {
11006     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11007       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11008       CXXConstructorDecl *Constructor =
11009           LookupMovingConstructor(BaseClassDecl, 0);
11010       // If this is a deleted function, add it anyway. This might be conformant
11011       // with the standard. This might not. I'm not sure. It might not matter.
11012       if (Constructor)
11013         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11014     }
11015   }
11016 
11017   // Field constructors.
11018   for (const auto *F : ClassDecl->fields()) {
11019     QualType FieldType = Context.getBaseElementType(F->getType());
11020     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11021       CXXConstructorDecl *Constructor =
11022           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11023       // If this is a deleted function, add it anyway. This might be conformant
11024       // with the standard. This might not. I'm not sure. It might not matter.
11025       // In particular, the problem is that this function never gets called. It
11026       // might just be ill-formed because this function attempts to refer to
11027       // a deleted function here.
11028       if (Constructor)
11029         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11030     }
11031   }
11032 
11033   return ExceptSpec;
11034 }
11035 
11036 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11037                                                     CXXRecordDecl *ClassDecl) {
11038   assert(ClassDecl->needsImplicitMoveConstructor());
11039 
11040   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11041   if (DSM.isAlreadyBeingDeclared())
11042     return nullptr;
11043 
11044   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11045   QualType ArgType = Context.getRValueReferenceType(ClassType);
11046 
11047   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11048                                                      CXXMoveConstructor,
11049                                                      false);
11050 
11051   DeclarationName Name
11052     = Context.DeclarationNames.getCXXConstructorName(
11053                                            Context.getCanonicalType(ClassType));
11054   SourceLocation ClassLoc = ClassDecl->getLocation();
11055   DeclarationNameInfo NameInfo(Name, ClassLoc);
11056 
11057   // C++11 [class.copy]p11:
11058   //   An implicitly-declared copy/move constructor is an inline public
11059   //   member of its class.
11060   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11061       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11062       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11063       Constexpr);
11064   MoveConstructor->setAccess(AS_public);
11065   MoveConstructor->setDefaulted();
11066 
11067   if (getLangOpts().CUDA) {
11068     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
11069                                             MoveConstructor,
11070                                             /* ConstRHS */ false,
11071                                             /* Diagnose */ false);
11072   }
11073 
11074   // Build an exception specification pointing back at this member.
11075   FunctionProtoType::ExtProtoInfo EPI =
11076       getImplicitMethodEPI(*this, MoveConstructor);
11077   MoveConstructor->setType(
11078       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11079 
11080   // Add the parameter to the constructor.
11081   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
11082                                                ClassLoc, ClassLoc,
11083                                                /*IdentifierInfo=*/nullptr,
11084                                                ArgType, /*TInfo=*/nullptr,
11085                                                SC_None, nullptr);
11086   MoveConstructor->setParams(FromParam);
11087 
11088   MoveConstructor->setTrivial(
11089     ClassDecl->needsOverloadResolutionForMoveConstructor()
11090       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
11091       : ClassDecl->hasTrivialMoveConstructor());
11092 
11093   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
11094     ClassDecl->setImplicitMoveConstructorIsDeleted();
11095     SetDeclDeleted(MoveConstructor, ClassLoc);
11096   }
11097 
11098   // Note that we have declared this constructor.
11099   ++ASTContext::NumImplicitMoveConstructorsDeclared;
11100 
11101   if (Scope *S = getScopeForContext(ClassDecl))
11102     PushOnScopeChains(MoveConstructor, S, false);
11103   ClassDecl->addDecl(MoveConstructor);
11104 
11105   return MoveConstructor;
11106 }
11107 
11108 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
11109                                    CXXConstructorDecl *MoveConstructor) {
11110   assert((MoveConstructor->isDefaulted() &&
11111           MoveConstructor->isMoveConstructor() &&
11112           !MoveConstructor->doesThisDeclarationHaveABody() &&
11113           !MoveConstructor->isDeleted()) &&
11114          "DefineImplicitMoveConstructor - call it for implicit move ctor");
11115 
11116   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
11117   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
11118 
11119   SynthesizedFunctionScope Scope(*this, MoveConstructor);
11120   DiagnosticErrorTrap Trap(Diags);
11121 
11122   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
11123       Trap.hasErrorOccurred()) {
11124     Diag(CurrentLocation, diag::note_member_synthesized_at)
11125       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
11126     MoveConstructor->setInvalidDecl();
11127   }  else {
11128     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
11129                              ? MoveConstructor->getLocEnd()
11130                              : MoveConstructor->getLocation();
11131     Sema::CompoundScopeRAII CompoundScope(*this);
11132     MoveConstructor->setBody(ActOnCompoundStmt(
11133         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
11134   }
11135 
11136   // The exception specification is needed because we are defining the
11137   // function.
11138   ResolveExceptionSpec(CurrentLocation,
11139                        MoveConstructor->getType()->castAs<FunctionProtoType>());
11140 
11141   MoveConstructor->markUsed(Context);
11142   MarkVTableUsed(CurrentLocation, ClassDecl);
11143 
11144   if (ASTMutationListener *L = getASTMutationListener()) {
11145     L->CompletedImplicitDefinition(MoveConstructor);
11146   }
11147 }
11148 
11149 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
11150   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
11151 }
11152 
11153 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
11154                             SourceLocation CurrentLocation,
11155                             CXXConversionDecl *Conv) {
11156   CXXRecordDecl *Lambda = Conv->getParent();
11157   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
11158   // If we are defining a specialization of a conversion to function-ptr
11159   // cache the deduced template arguments for this specialization
11160   // so that we can use them to retrieve the corresponding call-operator
11161   // and static-invoker.
11162   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
11163 
11164   // Retrieve the corresponding call-operator specialization.
11165   if (Lambda->isGenericLambda()) {
11166     assert(Conv->isFunctionTemplateSpecialization());
11167     FunctionTemplateDecl *CallOpTemplate =
11168         CallOp->getDescribedFunctionTemplate();
11169     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
11170     void *InsertPos = nullptr;
11171     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
11172                                                 DeducedTemplateArgs->asArray(),
11173                                                 InsertPos);
11174     assert(CallOpSpec &&
11175           "Conversion operator must have a corresponding call operator");
11176     CallOp = cast<CXXMethodDecl>(CallOpSpec);
11177   }
11178   // Mark the call operator referenced (and add to pending instantiations
11179   // if necessary).
11180   // For both the conversion and static-invoker template specializations
11181   // we construct their body's in this function, so no need to add them
11182   // to the PendingInstantiations.
11183   MarkFunctionReferenced(CurrentLocation, CallOp);
11184 
11185   SynthesizedFunctionScope Scope(*this, Conv);
11186   DiagnosticErrorTrap Trap(Diags);
11187 
11188   // Retrieve the static invoker...
11189   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
11190   // ... and get the corresponding specialization for a generic lambda.
11191   if (Lambda->isGenericLambda()) {
11192     assert(DeducedTemplateArgs &&
11193       "Must have deduced template arguments from Conversion Operator");
11194     FunctionTemplateDecl *InvokeTemplate =
11195                           Invoker->getDescribedFunctionTemplate();
11196     void *InsertPos = nullptr;
11197     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
11198                                                 DeducedTemplateArgs->asArray(),
11199                                                 InsertPos);
11200     assert(InvokeSpec &&
11201       "Must have a corresponding static invoker specialization");
11202     Invoker = cast<CXXMethodDecl>(InvokeSpec);
11203   }
11204   // Construct the body of the conversion function { return __invoke; }.
11205   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
11206                                         VK_LValue, Conv->getLocation()).get();
11207    assert(FunctionRef && "Can't refer to __invoke function?");
11208    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
11209    Conv->setBody(new (Context) CompoundStmt(Context, Return,
11210                                             Conv->getLocation(),
11211                                             Conv->getLocation()));
11212 
11213   Conv->markUsed(Context);
11214   Conv->setReferenced();
11215 
11216   // Fill in the __invoke function with a dummy implementation. IR generation
11217   // will fill in the actual details.
11218   Invoker->markUsed(Context);
11219   Invoker->setReferenced();
11220   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
11221 
11222   if (ASTMutationListener *L = getASTMutationListener()) {
11223     L->CompletedImplicitDefinition(Conv);
11224     L->CompletedImplicitDefinition(Invoker);
11225    }
11226 }
11227 
11228 
11229 
11230 void Sema::DefineImplicitLambdaToBlockPointerConversion(
11231        SourceLocation CurrentLocation,
11232        CXXConversionDecl *Conv)
11233 {
11234   assert(!Conv->getParent()->isGenericLambda());
11235 
11236   Conv->markUsed(Context);
11237 
11238   SynthesizedFunctionScope Scope(*this, Conv);
11239   DiagnosticErrorTrap Trap(Diags);
11240 
11241   // Copy-initialize the lambda object as needed to capture it.
11242   Expr *This = ActOnCXXThis(CurrentLocation).get();
11243   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
11244 
11245   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11246                                                         Conv->getLocation(),
11247                                                         Conv, DerefThis);
11248 
11249   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11250   // behavior.  Note that only the general conversion function does this
11251   // (since it's unusable otherwise); in the case where we inline the
11252   // block literal, it has block literal lifetime semantics.
11253   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
11254     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11255                                           CK_CopyAndAutoreleaseBlockObject,
11256                                           BuildBlock.get(), nullptr, VK_RValue);
11257 
11258   if (BuildBlock.isInvalid()) {
11259     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11260     Conv->setInvalidDecl();
11261     return;
11262   }
11263 
11264   // Create the return statement that returns the block from the conversion
11265   // function.
11266   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
11267   if (Return.isInvalid()) {
11268     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11269     Conv->setInvalidDecl();
11270     return;
11271   }
11272 
11273   // Set the body of the conversion function.
11274   Stmt *ReturnS = Return.get();
11275   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
11276                                            Conv->getLocation(),
11277                                            Conv->getLocation()));
11278 
11279   // We're done; notify the mutation listener, if any.
11280   if (ASTMutationListener *L = getASTMutationListener()) {
11281     L->CompletedImplicitDefinition(Conv);
11282   }
11283 }
11284 
11285 /// \brief Determine whether the given list arguments contains exactly one
11286 /// "real" (non-default) argument.
11287 static bool hasOneRealArgument(MultiExprArg Args) {
11288   switch (Args.size()) {
11289   case 0:
11290     return false;
11291 
11292   default:
11293     if (!Args[1]->isDefaultArgument())
11294       return false;
11295 
11296     // fall through
11297   case 1:
11298     return !Args[0]->isDefaultArgument();
11299   }
11300 
11301   return false;
11302 }
11303 
11304 ExprResult
11305 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11306                             CXXConstructorDecl *Constructor,
11307                             MultiExprArg ExprArgs,
11308                             bool HadMultipleCandidates,
11309                             bool IsListInitialization,
11310                             bool IsStdInitListInitialization,
11311                             bool RequiresZeroInit,
11312                             unsigned ConstructKind,
11313                             SourceRange ParenRange) {
11314   bool Elidable = false;
11315 
11316   // C++0x [class.copy]p34:
11317   //   When certain criteria are met, an implementation is allowed to
11318   //   omit the copy/move construction of a class object, even if the
11319   //   copy/move constructor and/or destructor for the object have
11320   //   side effects. [...]
11321   //     - when a temporary class object that has not been bound to a
11322   //       reference (12.2) would be copied/moved to a class object
11323   //       with the same cv-unqualified type, the copy/move operation
11324   //       can be omitted by constructing the temporary object
11325   //       directly into the target of the omitted copy/move
11326   if (ConstructKind == CXXConstructExpr::CK_Complete &&
11327       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
11328     Expr *SubExpr = ExprArgs[0];
11329     Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
11330   }
11331 
11332   return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
11333                                Elidable, ExprArgs, HadMultipleCandidates,
11334                                IsListInitialization,
11335                                IsStdInitListInitialization, RequiresZeroInit,
11336                                ConstructKind, ParenRange);
11337 }
11338 
11339 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
11340 /// including handling of its default argument expressions.
11341 ExprResult
11342 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11343                             CXXConstructorDecl *Constructor, bool Elidable,
11344                             MultiExprArg ExprArgs,
11345                             bool HadMultipleCandidates,
11346                             bool IsListInitialization,
11347                             bool IsStdInitListInitialization,
11348                             bool RequiresZeroInit,
11349                             unsigned ConstructKind,
11350                             SourceRange ParenRange) {
11351   MarkFunctionReferenced(ConstructLoc, Constructor);
11352   return CXXConstructExpr::Create(
11353       Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
11354       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11355       RequiresZeroInit,
11356       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11357       ParenRange);
11358 }
11359 
11360 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11361   assert(Field->hasInClassInitializer());
11362 
11363   // If we already have the in-class initializer nothing needs to be done.
11364   if (Field->getInClassInitializer())
11365     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11366 
11367   // Maybe we haven't instantiated the in-class initializer. Go check the
11368   // pattern FieldDecl to see if it has one.
11369   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11370 
11371   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11372     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11373     DeclContext::lookup_result Lookup =
11374         ClassPattern->lookup(Field->getDeclName());
11375     assert(Lookup.size() == 1);
11376     FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11377     if (InstantiateInClassInitializer(Loc, Field, Pattern,
11378                                       getTemplateInstantiationArgs(Field)))
11379       return ExprError();
11380     return CXXDefaultInitExpr::Create(Context, Loc, Field);
11381   }
11382 
11383   // DR1351:
11384   //   If the brace-or-equal-initializer of a non-static data member
11385   //   invokes a defaulted default constructor of its class or of an
11386   //   enclosing class in a potentially evaluated subexpression, the
11387   //   program is ill-formed.
11388   //
11389   // This resolution is unworkable: the exception specification of the
11390   // default constructor can be needed in an unevaluated context, in
11391   // particular, in the operand of a noexcept-expression, and we can be
11392   // unable to compute an exception specification for an enclosed class.
11393   //
11394   // Any attempt to resolve the exception specification of a defaulted default
11395   // constructor before the initializer is lexically complete will ultimately
11396   // come here at which point we can diagnose it.
11397   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11398   if (OutermostClass == ParentRD) {
11399     Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11400         << ParentRD << Field;
11401   } else {
11402     Diag(Field->getLocEnd(),
11403          diag::err_in_class_initializer_not_yet_parsed_outer_class)
11404         << ParentRD << OutermostClass << Field;
11405   }
11406 
11407   return ExprError();
11408 }
11409 
11410 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
11411   if (VD->isInvalidDecl()) return;
11412 
11413   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
11414   if (ClassDecl->isInvalidDecl()) return;
11415   if (ClassDecl->hasIrrelevantDestructor()) return;
11416   if (ClassDecl->isDependentContext()) return;
11417 
11418   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
11419   MarkFunctionReferenced(VD->getLocation(), Destructor);
11420   CheckDestructorAccess(VD->getLocation(), Destructor,
11421                         PDiag(diag::err_access_dtor_var)
11422                         << VD->getDeclName()
11423                         << VD->getType());
11424   DiagnoseUseOfDecl(Destructor, VD->getLocation());
11425 
11426   if (Destructor->isTrivial()) return;
11427   if (!VD->hasGlobalStorage()) return;
11428 
11429   // Emit warning for non-trivial dtor in global scope (a real global,
11430   // class-static, function-static).
11431   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11432 
11433   // TODO: this should be re-enabled for static locals by !CXAAtExit
11434   if (!VD->isStaticLocal())
11435     Diag(VD->getLocation(), diag::warn_global_destructor);
11436 }
11437 
11438 /// \brief Given a constructor and the set of arguments provided for the
11439 /// constructor, convert the arguments and add any required default arguments
11440 /// to form a proper call to this constructor.
11441 ///
11442 /// \returns true if an error occurred, false otherwise.
11443 bool
11444 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11445                               MultiExprArg ArgsPtr,
11446                               SourceLocation Loc,
11447                               SmallVectorImpl<Expr*> &ConvertedArgs,
11448                               bool AllowExplicit,
11449                               bool IsListInitialization) {
11450   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11451   unsigned NumArgs = ArgsPtr.size();
11452   Expr **Args = ArgsPtr.data();
11453 
11454   const FunctionProtoType *Proto
11455     = Constructor->getType()->getAs<FunctionProtoType>();
11456   assert(Proto && "Constructor without a prototype?");
11457   unsigned NumParams = Proto->getNumParams();
11458 
11459   // If too few arguments are available, we'll fill in the rest with defaults.
11460   if (NumArgs < NumParams)
11461     ConvertedArgs.reserve(NumParams);
11462   else
11463     ConvertedArgs.reserve(NumArgs);
11464 
11465   VariadicCallType CallType =
11466     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
11467   SmallVector<Expr *, 8> AllArgs;
11468   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
11469                                         Proto, 0,
11470                                         llvm::makeArrayRef(Args, NumArgs),
11471                                         AllArgs,
11472                                         CallType, AllowExplicit,
11473                                         IsListInitialization);
11474   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
11475 
11476   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
11477 
11478   CheckConstructorCall(Constructor,
11479                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
11480                        Proto, Loc);
11481 
11482   return Invalid;
11483 }
11484 
11485 static inline bool
11486 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11487                                        const FunctionDecl *FnDecl) {
11488   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
11489   if (isa<NamespaceDecl>(DC)) {
11490     return SemaRef.Diag(FnDecl->getLocation(),
11491                         diag::err_operator_new_delete_declared_in_namespace)
11492       << FnDecl->getDeclName();
11493   }
11494 
11495   if (isa<TranslationUnitDecl>(DC) &&
11496       FnDecl->getStorageClass() == SC_Static) {
11497     return SemaRef.Diag(FnDecl->getLocation(),
11498                         diag::err_operator_new_delete_declared_static)
11499       << FnDecl->getDeclName();
11500   }
11501 
11502   return false;
11503 }
11504 
11505 static inline bool
11506 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11507                             CanQualType ExpectedResultType,
11508                             CanQualType ExpectedFirstParamType,
11509                             unsigned DependentParamTypeDiag,
11510                             unsigned InvalidParamTypeDiag) {
11511   QualType ResultType =
11512       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
11513 
11514   // Check that the result type is not dependent.
11515   if (ResultType->isDependentType())
11516     return SemaRef.Diag(FnDecl->getLocation(),
11517                         diag::err_operator_new_delete_dependent_result_type)
11518     << FnDecl->getDeclName() << ExpectedResultType;
11519 
11520   // Check that the result type is what we expect.
11521   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11522     return SemaRef.Diag(FnDecl->getLocation(),
11523                         diag::err_operator_new_delete_invalid_result_type)
11524     << FnDecl->getDeclName() << ExpectedResultType;
11525 
11526   // A function template must have at least 2 parameters.
11527   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11528     return SemaRef.Diag(FnDecl->getLocation(),
11529                       diag::err_operator_new_delete_template_too_few_parameters)
11530         << FnDecl->getDeclName();
11531 
11532   // The function decl must have at least 1 parameter.
11533   if (FnDecl->getNumParams() == 0)
11534     return SemaRef.Diag(FnDecl->getLocation(),
11535                         diag::err_operator_new_delete_too_few_parameters)
11536       << FnDecl->getDeclName();
11537 
11538   // Check the first parameter type is not dependent.
11539   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11540   if (FirstParamType->isDependentType())
11541     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11542       << FnDecl->getDeclName() << ExpectedFirstParamType;
11543 
11544   // Check that the first parameter type is what we expect.
11545   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
11546       ExpectedFirstParamType)
11547     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11548     << FnDecl->getDeclName() << ExpectedFirstParamType;
11549 
11550   return false;
11551 }
11552 
11553 static bool
11554 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
11555   // C++ [basic.stc.dynamic.allocation]p1:
11556   //   A program is ill-formed if an allocation function is declared in a
11557   //   namespace scope other than global scope or declared static in global
11558   //   scope.
11559   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11560     return true;
11561 
11562   CanQualType SizeTy =
11563     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11564 
11565   // C++ [basic.stc.dynamic.allocation]p1:
11566   //  The return type shall be void*. The first parameter shall have type
11567   //  std::size_t.
11568   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11569                                   SizeTy,
11570                                   diag::err_operator_new_dependent_param_type,
11571                                   diag::err_operator_new_param_type))
11572     return true;
11573 
11574   // C++ [basic.stc.dynamic.allocation]p1:
11575   //  The first parameter shall not have an associated default argument.
11576   if (FnDecl->getParamDecl(0)->hasDefaultArg())
11577     return SemaRef.Diag(FnDecl->getLocation(),
11578                         diag::err_operator_new_default_arg)
11579       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11580 
11581   return false;
11582 }
11583 
11584 static bool
11585 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
11586   // C++ [basic.stc.dynamic.deallocation]p1:
11587   //   A program is ill-formed if deallocation functions are declared in a
11588   //   namespace scope other than global scope or declared static in global
11589   //   scope.
11590   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11591     return true;
11592 
11593   // C++ [basic.stc.dynamic.deallocation]p2:
11594   //   Each deallocation function shall return void and its first parameter
11595   //   shall be void*.
11596   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11597                                   SemaRef.Context.VoidPtrTy,
11598                                  diag::err_operator_delete_dependent_param_type,
11599                                  diag::err_operator_delete_param_type))
11600     return true;
11601 
11602   return false;
11603 }
11604 
11605 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
11606 /// of this overloaded operator is well-formed. If so, returns false;
11607 /// otherwise, emits appropriate diagnostics and returns true.
11608 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
11609   assert(FnDecl && FnDecl->isOverloadedOperator() &&
11610          "Expected an overloaded operator declaration");
11611 
11612   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11613 
11614   // C++ [over.oper]p5:
11615   //   The allocation and deallocation functions, operator new,
11616   //   operator new[], operator delete and operator delete[], are
11617   //   described completely in 3.7.3. The attributes and restrictions
11618   //   found in the rest of this subclause do not apply to them unless
11619   //   explicitly stated in 3.7.3.
11620   if (Op == OO_Delete || Op == OO_Array_Delete)
11621     return CheckOperatorDeleteDeclaration(*this, FnDecl);
11622 
11623   if (Op == OO_New || Op == OO_Array_New)
11624     return CheckOperatorNewDeclaration(*this, FnDecl);
11625 
11626   // C++ [over.oper]p6:
11627   //   An operator function shall either be a non-static member
11628   //   function or be a non-member function and have at least one
11629   //   parameter whose type is a class, a reference to a class, an
11630   //   enumeration, or a reference to an enumeration.
11631   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11632     if (MethodDecl->isStatic())
11633       return Diag(FnDecl->getLocation(),
11634                   diag::err_operator_overload_static) << FnDecl->getDeclName();
11635   } else {
11636     bool ClassOrEnumParam = false;
11637     for (auto Param : FnDecl->params()) {
11638       QualType ParamType = Param->getType().getNonReferenceType();
11639       if (ParamType->isDependentType() || ParamType->isRecordType() ||
11640           ParamType->isEnumeralType()) {
11641         ClassOrEnumParam = true;
11642         break;
11643       }
11644     }
11645 
11646     if (!ClassOrEnumParam)
11647       return Diag(FnDecl->getLocation(),
11648                   diag::err_operator_overload_needs_class_or_enum)
11649         << FnDecl->getDeclName();
11650   }
11651 
11652   // C++ [over.oper]p8:
11653   //   An operator function cannot have default arguments (8.3.6),
11654   //   except where explicitly stated below.
11655   //
11656   // Only the function-call operator allows default arguments
11657   // (C++ [over.call]p1).
11658   if (Op != OO_Call) {
11659     for (auto Param : FnDecl->params()) {
11660       if (Param->hasDefaultArg())
11661         return Diag(Param->getLocation(),
11662                     diag::err_operator_overload_default_arg)
11663           << FnDecl->getDeclName() << Param->getDefaultArgRange();
11664     }
11665   }
11666 
11667   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11668     { false, false, false }
11669 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11670     , { Unary, Binary, MemberOnly }
11671 #include "clang/Basic/OperatorKinds.def"
11672   };
11673 
11674   bool CanBeUnaryOperator = OperatorUses[Op][0];
11675   bool CanBeBinaryOperator = OperatorUses[Op][1];
11676   bool MustBeMemberOperator = OperatorUses[Op][2];
11677 
11678   // C++ [over.oper]p8:
11679   //   [...] Operator functions cannot have more or fewer parameters
11680   //   than the number required for the corresponding operator, as
11681   //   described in the rest of this subclause.
11682   unsigned NumParams = FnDecl->getNumParams()
11683                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
11684   if (Op != OO_Call &&
11685       ((NumParams == 1 && !CanBeUnaryOperator) ||
11686        (NumParams == 2 && !CanBeBinaryOperator) ||
11687        (NumParams < 1) || (NumParams > 2))) {
11688     // We have the wrong number of parameters.
11689     unsigned ErrorKind;
11690     if (CanBeUnaryOperator && CanBeBinaryOperator) {
11691       ErrorKind = 2;  // 2 -> unary or binary.
11692     } else if (CanBeUnaryOperator) {
11693       ErrorKind = 0;  // 0 -> unary
11694     } else {
11695       assert(CanBeBinaryOperator &&
11696              "All non-call overloaded operators are unary or binary!");
11697       ErrorKind = 1;  // 1 -> binary
11698     }
11699 
11700     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
11701       << FnDecl->getDeclName() << NumParams << ErrorKind;
11702   }
11703 
11704   // Overloaded operators other than operator() cannot be variadic.
11705   if (Op != OO_Call &&
11706       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
11707     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
11708       << FnDecl->getDeclName();
11709   }
11710 
11711   // Some operators must be non-static member functions.
11712   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11713     return Diag(FnDecl->getLocation(),
11714                 diag::err_operator_overload_must_be_member)
11715       << FnDecl->getDeclName();
11716   }
11717 
11718   // C++ [over.inc]p1:
11719   //   The user-defined function called operator++ implements the
11720   //   prefix and postfix ++ operator. If this function is a member
11721   //   function with no parameters, or a non-member function with one
11722   //   parameter of class or enumeration type, it defines the prefix
11723   //   increment operator ++ for objects of that type. If the function
11724   //   is a member function with one parameter (which shall be of type
11725   //   int) or a non-member function with two parameters (the second
11726   //   of which shall be of type int), it defines the postfix
11727   //   increment operator ++ for objects of that type.
11728   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11729     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
11730     QualType ParamType = LastParam->getType();
11731 
11732     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11733         !ParamType->isDependentType())
11734       return Diag(LastParam->getLocation(),
11735                   diag::err_operator_overload_post_incdec_must_be_int)
11736         << LastParam->getType() << (Op == OO_MinusMinus);
11737   }
11738 
11739   return false;
11740 }
11741 
11742 /// CheckLiteralOperatorDeclaration - Check whether the declaration
11743 /// of this literal operator function is well-formed. If so, returns
11744 /// false; otherwise, emits appropriate diagnostics and returns true.
11745 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
11746   if (isa<CXXMethodDecl>(FnDecl)) {
11747     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11748       << FnDecl->getDeclName();
11749     return true;
11750   }
11751 
11752   if (FnDecl->isExternC()) {
11753     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11754     return true;
11755   }
11756 
11757   bool Valid = false;
11758 
11759   // This might be the definition of a literal operator template.
11760   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11761   // This might be a specialization of a literal operator template.
11762   if (!TpDecl)
11763     TpDecl = FnDecl->getPrimaryTemplate();
11764 
11765   // template <char...> type operator "" name() and
11766   // template <class T, T...> type operator "" name() are the only valid
11767   // template signatures, and the only valid signatures with no parameters.
11768   if (TpDecl) {
11769     if (FnDecl->param_size() == 0) {
11770       // Must have one or two template parameters
11771       TemplateParameterList *Params = TpDecl->getTemplateParameters();
11772       if (Params->size() == 1) {
11773         NonTypeTemplateParmDecl *PmDecl =
11774           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
11775 
11776         // The template parameter must be a char parameter pack.
11777         if (PmDecl && PmDecl->isTemplateParameterPack() &&
11778             Context.hasSameType(PmDecl->getType(), Context.CharTy))
11779           Valid = true;
11780       } else if (Params->size() == 2) {
11781         TemplateTypeParmDecl *PmType =
11782           dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11783         NonTypeTemplateParmDecl *PmArgs =
11784           dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11785 
11786         // The second template parameter must be a parameter pack with the
11787         // first template parameter as its type.
11788         if (PmType && PmArgs &&
11789             !PmType->isTemplateParameterPack() &&
11790             PmArgs->isTemplateParameterPack()) {
11791           const TemplateTypeParmType *TArgs =
11792             PmArgs->getType()->getAs<TemplateTypeParmType>();
11793           if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11794               TArgs->getIndex() == PmType->getIndex()) {
11795             Valid = true;
11796             if (ActiveTemplateInstantiations.empty())
11797               Diag(FnDecl->getLocation(),
11798                    diag::ext_string_literal_operator_template);
11799           }
11800         }
11801       }
11802     }
11803   } else if (FnDecl->param_size()) {
11804     // Check the first parameter
11805     FunctionDecl::param_iterator Param = FnDecl->param_begin();
11806 
11807     QualType T = (*Param)->getType().getUnqualifiedType();
11808 
11809     // unsigned long long int, long double, and any character type are allowed
11810     // as the only parameters.
11811     if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11812         Context.hasSameType(T, Context.LongDoubleTy) ||
11813         Context.hasSameType(T, Context.CharTy) ||
11814         Context.hasSameType(T, Context.WideCharTy) ||
11815         Context.hasSameType(T, Context.Char16Ty) ||
11816         Context.hasSameType(T, Context.Char32Ty)) {
11817       if (++Param == FnDecl->param_end())
11818         Valid = true;
11819       goto FinishedParams;
11820     }
11821 
11822     // Otherwise it must be a pointer to const; let's strip those qualifiers.
11823     const PointerType *PT = T->getAs<PointerType>();
11824     if (!PT)
11825       goto FinishedParams;
11826     T = PT->getPointeeType();
11827     if (!T.isConstQualified() || T.isVolatileQualified())
11828       goto FinishedParams;
11829     T = T.getUnqualifiedType();
11830 
11831     // Move on to the second parameter;
11832     ++Param;
11833 
11834     // If there is no second parameter, the first must be a const char *
11835     if (Param == FnDecl->param_end()) {
11836       if (Context.hasSameType(T, Context.CharTy))
11837         Valid = true;
11838       goto FinishedParams;
11839     }
11840 
11841     // const char *, const wchar_t*, const char16_t*, and const char32_t*
11842     // are allowed as the first parameter to a two-parameter function
11843     if (!(Context.hasSameType(T, Context.CharTy) ||
11844           Context.hasSameType(T, Context.WideCharTy) ||
11845           Context.hasSameType(T, Context.Char16Ty) ||
11846           Context.hasSameType(T, Context.Char32Ty)))
11847       goto FinishedParams;
11848 
11849     // The second and final parameter must be an std::size_t
11850     T = (*Param)->getType().getUnqualifiedType();
11851     if (Context.hasSameType(T, Context.getSizeType()) &&
11852         ++Param == FnDecl->param_end())
11853       Valid = true;
11854   }
11855 
11856   // FIXME: This diagnostic is absolutely terrible.
11857 FinishedParams:
11858   if (!Valid) {
11859     Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11860       << FnDecl->getDeclName();
11861     return true;
11862   }
11863 
11864   // A parameter-declaration-clause containing a default argument is not
11865   // equivalent to any of the permitted forms.
11866   for (auto Param : FnDecl->params()) {
11867     if (Param->hasDefaultArg()) {
11868       Diag(Param->getDefaultArgRange().getBegin(),
11869            diag::err_literal_operator_default_argument)
11870         << Param->getDefaultArgRange();
11871       break;
11872     }
11873   }
11874 
11875   StringRef LiteralName
11876     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11877   if (LiteralName[0] != '_') {
11878     // C++11 [usrlit.suffix]p1:
11879     //   Literal suffix identifiers that do not start with an underscore
11880     //   are reserved for future standardization.
11881     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11882       << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
11883   }
11884 
11885   return false;
11886 }
11887 
11888 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11889 /// linkage specification, including the language and (if present)
11890 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
11891 /// language string literal. LBraceLoc, if valid, provides the location of
11892 /// the '{' brace. Otherwise, this linkage specification does not
11893 /// have any braces.
11894 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11895                                            Expr *LangStr,
11896                                            SourceLocation LBraceLoc) {
11897   StringLiteral *Lit = cast<StringLiteral>(LangStr);
11898   if (!Lit->isAscii()) {
11899     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11900       << LangStr->getSourceRange();
11901     return nullptr;
11902   }
11903 
11904   StringRef Lang = Lit->getString();
11905   LinkageSpecDecl::LanguageIDs Language;
11906   if (Lang == "C")
11907     Language = LinkageSpecDecl::lang_c;
11908   else if (Lang == "C++")
11909     Language = LinkageSpecDecl::lang_cxx;
11910   else {
11911     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11912       << LangStr->getSourceRange();
11913     return nullptr;
11914   }
11915 
11916   // FIXME: Add all the various semantics of linkage specifications
11917 
11918   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11919                                                LangStr->getExprLoc(), Language,
11920                                                LBraceLoc.isValid());
11921   CurContext->addDecl(D);
11922   PushDeclContext(S, D);
11923   return D;
11924 }
11925 
11926 /// ActOnFinishLinkageSpecification - Complete the definition of
11927 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
11928 /// valid, it's the position of the closing '}' brace in a linkage
11929 /// specification that uses braces.
11930 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11931                                             Decl *LinkageSpec,
11932                                             SourceLocation RBraceLoc) {
11933   if (RBraceLoc.isValid()) {
11934     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11935     LSDecl->setRBraceLoc(RBraceLoc);
11936   }
11937   PopDeclContext();
11938   return LinkageSpec;
11939 }
11940 
11941 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11942                                   AttributeList *AttrList,
11943                                   SourceLocation SemiLoc) {
11944   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11945   // Attribute declarations appertain to empty declaration so we handle
11946   // them here.
11947   if (AttrList)
11948     ProcessDeclAttributeList(S, ED, AttrList);
11949 
11950   CurContext->addDecl(ED);
11951   return ED;
11952 }
11953 
11954 /// \brief Perform semantic analysis for the variable declaration that
11955 /// occurs within a C++ catch clause, returning the newly-created
11956 /// variable.
11957 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11958                                          TypeSourceInfo *TInfo,
11959                                          SourceLocation StartLoc,
11960                                          SourceLocation Loc,
11961                                          IdentifierInfo *Name) {
11962   bool Invalid = false;
11963   QualType ExDeclType = TInfo->getType();
11964 
11965   // Arrays and functions decay.
11966   if (ExDeclType->isArrayType())
11967     ExDeclType = Context.getArrayDecayedType(ExDeclType);
11968   else if (ExDeclType->isFunctionType())
11969     ExDeclType = Context.getPointerType(ExDeclType);
11970 
11971   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11972   // The exception-declaration shall not denote a pointer or reference to an
11973   // incomplete type, other than [cv] void*.
11974   // N2844 forbids rvalue references.
11975   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11976     Diag(Loc, diag::err_catch_rvalue_ref);
11977     Invalid = true;
11978   }
11979 
11980   QualType BaseType = ExDeclType;
11981   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11982   unsigned DK = diag::err_catch_incomplete;
11983   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11984     BaseType = Ptr->getPointeeType();
11985     Mode = 1;
11986     DK = diag::err_catch_incomplete_ptr;
11987   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11988     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11989     BaseType = Ref->getPointeeType();
11990     Mode = 2;
11991     DK = diag::err_catch_incomplete_ref;
11992   }
11993   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11994       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11995     Invalid = true;
11996 
11997   if (!Invalid && !ExDeclType->isDependentType() &&
11998       RequireNonAbstractType(Loc, ExDeclType,
11999                              diag::err_abstract_type_in_decl,
12000                              AbstractVariableType))
12001     Invalid = true;
12002 
12003   // Only the non-fragile NeXT runtime currently supports C++ catches
12004   // of ObjC types, and no runtime supports catching ObjC types by value.
12005   if (!Invalid && getLangOpts().ObjC1) {
12006     QualType T = ExDeclType;
12007     if (const ReferenceType *RT = T->getAs<ReferenceType>())
12008       T = RT->getPointeeType();
12009 
12010     if (T->isObjCObjectType()) {
12011       Diag(Loc, diag::err_objc_object_catch);
12012       Invalid = true;
12013     } else if (T->isObjCObjectPointerType()) {
12014       // FIXME: should this be a test for macosx-fragile specifically?
12015       if (getLangOpts().ObjCRuntime.isFragile())
12016         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
12017     }
12018   }
12019 
12020   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
12021                                     ExDeclType, TInfo, SC_None);
12022   ExDecl->setExceptionVariable(true);
12023 
12024   // In ARC, infer 'retaining' for variables of retainable type.
12025   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
12026     Invalid = true;
12027 
12028   if (!Invalid && !ExDeclType->isDependentType()) {
12029     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
12030       // Insulate this from anything else we might currently be parsing.
12031       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
12032 
12033       // C++ [except.handle]p16:
12034       //   The object declared in an exception-declaration or, if the
12035       //   exception-declaration does not specify a name, a temporary (12.2) is
12036       //   copy-initialized (8.5) from the exception object. [...]
12037       //   The object is destroyed when the handler exits, after the destruction
12038       //   of any automatic objects initialized within the handler.
12039       //
12040       // We just pretend to initialize the object with itself, then make sure
12041       // it can be destroyed later.
12042       QualType initType = Context.getExceptionObjectType(ExDeclType);
12043 
12044       InitializedEntity entity =
12045         InitializedEntity::InitializeVariable(ExDecl);
12046       InitializationKind initKind =
12047         InitializationKind::CreateCopy(Loc, SourceLocation());
12048 
12049       Expr *opaqueValue =
12050         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
12051       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
12052       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
12053       if (result.isInvalid())
12054         Invalid = true;
12055       else {
12056         // If the constructor used was non-trivial, set this as the
12057         // "initializer".
12058         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
12059         if (!construct->getConstructor()->isTrivial()) {
12060           Expr *init = MaybeCreateExprWithCleanups(construct);
12061           ExDecl->setInit(init);
12062         }
12063 
12064         // And make sure it's destructable.
12065         FinalizeVarWithDestructor(ExDecl, recordType);
12066       }
12067     }
12068   }
12069 
12070   if (Invalid)
12071     ExDecl->setInvalidDecl();
12072 
12073   return ExDecl;
12074 }
12075 
12076 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
12077 /// handler.
12078 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
12079   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12080   bool Invalid = D.isInvalidType();
12081 
12082   // Check for unexpanded parameter packs.
12083   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12084                                       UPPC_ExceptionType)) {
12085     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12086                                              D.getIdentifierLoc());
12087     Invalid = true;
12088   }
12089 
12090   IdentifierInfo *II = D.getIdentifier();
12091   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
12092                                              LookupOrdinaryName,
12093                                              ForRedeclaration)) {
12094     // The scope should be freshly made just for us. There is just no way
12095     // it contains any previous declaration, except for function parameters in
12096     // a function-try-block's catch statement.
12097     assert(!S->isDeclScope(PrevDecl));
12098     if (isDeclInScope(PrevDecl, CurContext, S)) {
12099       Diag(D.getIdentifierLoc(), diag::err_redefinition)
12100         << D.getIdentifier();
12101       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12102       Invalid = true;
12103     } else if (PrevDecl->isTemplateParameter())
12104       // Maybe we will complain about the shadowed template parameter.
12105       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12106   }
12107 
12108   if (D.getCXXScopeSpec().isSet() && !Invalid) {
12109     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
12110       << D.getCXXScopeSpec().getRange();
12111     Invalid = true;
12112   }
12113 
12114   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
12115                                               D.getLocStart(),
12116                                               D.getIdentifierLoc(),
12117                                               D.getIdentifier());
12118   if (Invalid)
12119     ExDecl->setInvalidDecl();
12120 
12121   // Add the exception declaration into this scope.
12122   if (II)
12123     PushOnScopeChains(ExDecl, S);
12124   else
12125     CurContext->addDecl(ExDecl);
12126 
12127   ProcessDeclAttributes(S, ExDecl, D);
12128   return ExDecl;
12129 }
12130 
12131 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12132                                          Expr *AssertExpr,
12133                                          Expr *AssertMessageExpr,
12134                                          SourceLocation RParenLoc) {
12135   StringLiteral *AssertMessage =
12136       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
12137 
12138   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
12139     return nullptr;
12140 
12141   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
12142                                       AssertMessage, RParenLoc, false);
12143 }
12144 
12145 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
12146                                          Expr *AssertExpr,
12147                                          StringLiteral *AssertMessage,
12148                                          SourceLocation RParenLoc,
12149                                          bool Failed) {
12150   assert(AssertExpr != nullptr && "Expected non-null condition");
12151   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
12152       !Failed) {
12153     // In a static_assert-declaration, the constant-expression shall be a
12154     // constant expression that can be contextually converted to bool.
12155     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
12156     if (Converted.isInvalid())
12157       Failed = true;
12158 
12159     llvm::APSInt Cond;
12160     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
12161           diag::err_static_assert_expression_is_not_constant,
12162           /*AllowFold=*/false).isInvalid())
12163       Failed = true;
12164 
12165     if (!Failed && !Cond) {
12166       SmallString<256> MsgBuffer;
12167       llvm::raw_svector_ostream Msg(MsgBuffer);
12168       if (AssertMessage)
12169         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
12170       Diag(StaticAssertLoc, diag::err_static_assert_failed)
12171         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
12172       Failed = true;
12173     }
12174   }
12175 
12176   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
12177                                         AssertExpr, AssertMessage, RParenLoc,
12178                                         Failed);
12179 
12180   CurContext->addDecl(Decl);
12181   return Decl;
12182 }
12183 
12184 /// \brief Perform semantic analysis of the given friend type declaration.
12185 ///
12186 /// \returns A friend declaration that.
12187 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
12188                                       SourceLocation FriendLoc,
12189                                       TypeSourceInfo *TSInfo) {
12190   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
12191 
12192   QualType T = TSInfo->getType();
12193   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
12194 
12195   // C++03 [class.friend]p2:
12196   //   An elaborated-type-specifier shall be used in a friend declaration
12197   //   for a class.*
12198   //
12199   //   * The class-key of the elaborated-type-specifier is required.
12200   if (!ActiveTemplateInstantiations.empty()) {
12201     // Do not complain about the form of friend template types during
12202     // template instantiation; we will already have complained when the
12203     // template was declared.
12204   } else {
12205     if (!T->isElaboratedTypeSpecifier()) {
12206       // If we evaluated the type to a record type, suggest putting
12207       // a tag in front.
12208       if (const RecordType *RT = T->getAs<RecordType>()) {
12209         RecordDecl *RD = RT->getDecl();
12210 
12211         SmallString<16> InsertionText(" ");
12212         InsertionText += RD->getKindName();
12213 
12214         Diag(TypeRange.getBegin(),
12215              getLangOpts().CPlusPlus11 ?
12216                diag::warn_cxx98_compat_unelaborated_friend_type :
12217                diag::ext_unelaborated_friend_type)
12218           << (unsigned) RD->getTagKind()
12219           << T
12220           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
12221                                         InsertionText);
12222       } else {
12223         Diag(FriendLoc,
12224              getLangOpts().CPlusPlus11 ?
12225                diag::warn_cxx98_compat_nonclass_type_friend :
12226                diag::ext_nonclass_type_friend)
12227           << T
12228           << TypeRange;
12229       }
12230     } else if (T->getAs<EnumType>()) {
12231       Diag(FriendLoc,
12232            getLangOpts().CPlusPlus11 ?
12233              diag::warn_cxx98_compat_enum_friend :
12234              diag::ext_enum_friend)
12235         << T
12236         << TypeRange;
12237     }
12238 
12239     // C++11 [class.friend]p3:
12240     //   A friend declaration that does not declare a function shall have one
12241     //   of the following forms:
12242     //     friend elaborated-type-specifier ;
12243     //     friend simple-type-specifier ;
12244     //     friend typename-specifier ;
12245     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12246       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12247   }
12248 
12249   //   If the type specifier in a friend declaration designates a (possibly
12250   //   cv-qualified) class type, that class is declared as a friend; otherwise,
12251   //   the friend declaration is ignored.
12252   return FriendDecl::Create(Context, CurContext,
12253                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
12254                             FriendLoc);
12255 }
12256 
12257 /// Handle a friend tag declaration where the scope specifier was
12258 /// templated.
12259 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12260                                     unsigned TagSpec, SourceLocation TagLoc,
12261                                     CXXScopeSpec &SS,
12262                                     IdentifierInfo *Name,
12263                                     SourceLocation NameLoc,
12264                                     AttributeList *Attr,
12265                                     MultiTemplateParamsArg TempParamLists) {
12266   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12267 
12268   bool isExplicitSpecialization = false;
12269   bool Invalid = false;
12270 
12271   if (TemplateParameterList *TemplateParams =
12272           MatchTemplateParametersToScopeSpecifier(
12273               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
12274               isExplicitSpecialization, Invalid)) {
12275     if (TemplateParams->size() > 0) {
12276       // This is a declaration of a class template.
12277       if (Invalid)
12278         return nullptr;
12279 
12280       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12281                                 NameLoc, Attr, TemplateParams, AS_public,
12282                                 /*ModulePrivateLoc=*/SourceLocation(),
12283                                 FriendLoc, TempParamLists.size() - 1,
12284                                 TempParamLists.data()).get();
12285     } else {
12286       // The "template<>" header is extraneous.
12287       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12288         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12289       isExplicitSpecialization = true;
12290     }
12291   }
12292 
12293   if (Invalid) return nullptr;
12294 
12295   bool isAllExplicitSpecializations = true;
12296   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
12297     if (TempParamLists[I]->size()) {
12298       isAllExplicitSpecializations = false;
12299       break;
12300     }
12301   }
12302 
12303   // FIXME: don't ignore attributes.
12304 
12305   // If it's explicit specializations all the way down, just forget
12306   // about the template header and build an appropriate non-templated
12307   // friend.  TODO: for source fidelity, remember the headers.
12308   if (isAllExplicitSpecializations) {
12309     if (SS.isEmpty()) {
12310       bool Owned = false;
12311       bool IsDependent = false;
12312       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
12313                       Attr, AS_public,
12314                       /*ModulePrivateLoc=*/SourceLocation(),
12315                       MultiTemplateParamsArg(), Owned, IsDependent,
12316                       /*ScopedEnumKWLoc=*/SourceLocation(),
12317                       /*ScopedEnumUsesClassTag=*/false,
12318                       /*UnderlyingType=*/TypeResult(),
12319                       /*IsTypeSpecifier=*/false);
12320     }
12321 
12322     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12323     ElaboratedTypeKeyword Keyword
12324       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12325     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
12326                                    *Name, NameLoc);
12327     if (T.isNull())
12328       return nullptr;
12329 
12330     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12331     if (isa<DependentNameType>(T)) {
12332       DependentNameTypeLoc TL =
12333           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12334       TL.setElaboratedKeywordLoc(TagLoc);
12335       TL.setQualifierLoc(QualifierLoc);
12336       TL.setNameLoc(NameLoc);
12337     } else {
12338       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
12339       TL.setElaboratedKeywordLoc(TagLoc);
12340       TL.setQualifierLoc(QualifierLoc);
12341       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
12342     }
12343 
12344     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12345                                             TSI, FriendLoc, TempParamLists);
12346     Friend->setAccess(AS_public);
12347     CurContext->addDecl(Friend);
12348     return Friend;
12349   }
12350 
12351   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12352 
12353 
12354 
12355   // Handle the case of a templated-scope friend class.  e.g.
12356   //   template <class T> class A<T>::B;
12357   // FIXME: we don't support these right now.
12358   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12359     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
12360   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12361   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12362   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12363   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
12364   TL.setElaboratedKeywordLoc(TagLoc);
12365   TL.setQualifierLoc(SS.getWithLocInContext(Context));
12366   TL.setNameLoc(NameLoc);
12367 
12368   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
12369                                           TSI, FriendLoc, TempParamLists);
12370   Friend->setAccess(AS_public);
12371   Friend->setUnsupportedFriend(true);
12372   CurContext->addDecl(Friend);
12373   return Friend;
12374 }
12375 
12376 
12377 /// Handle a friend type declaration.  This works in tandem with
12378 /// ActOnTag.
12379 ///
12380 /// Notes on friend class templates:
12381 ///
12382 /// We generally treat friend class declarations as if they were
12383 /// declaring a class.  So, for example, the elaborated type specifier
12384 /// in a friend declaration is required to obey the restrictions of a
12385 /// class-head (i.e. no typedefs in the scope chain), template
12386 /// parameters are required to match up with simple template-ids, &c.
12387 /// However, unlike when declaring a template specialization, it's
12388 /// okay to refer to a template specialization without an empty
12389 /// template parameter declaration, e.g.
12390 ///   friend class A<T>::B<unsigned>;
12391 /// We permit this as a special case; if there are any template
12392 /// parameters present at all, require proper matching, i.e.
12393 ///   template <> template \<class T> friend class A<int>::B;
12394 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
12395                                 MultiTemplateParamsArg TempParams) {
12396   SourceLocation Loc = DS.getLocStart();
12397 
12398   assert(DS.isFriendSpecified());
12399   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12400 
12401   // Try to convert the decl specifier to a type.  This works for
12402   // friend templates because ActOnTag never produces a ClassTemplateDecl
12403   // for a TUK_Friend.
12404   Declarator TheDeclarator(DS, Declarator::MemberContext);
12405   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12406   QualType T = TSI->getType();
12407   if (TheDeclarator.isInvalidType())
12408     return nullptr;
12409 
12410   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
12411     return nullptr;
12412 
12413   // This is definitely an error in C++98.  It's probably meant to
12414   // be forbidden in C++0x, too, but the specification is just
12415   // poorly written.
12416   //
12417   // The problem is with declarations like the following:
12418   //   template <T> friend A<T>::foo;
12419   // where deciding whether a class C is a friend or not now hinges
12420   // on whether there exists an instantiation of A that causes
12421   // 'foo' to equal C.  There are restrictions on class-heads
12422   // (which we declare (by fiat) elaborated friend declarations to
12423   // be) that makes this tractable.
12424   //
12425   // FIXME: handle "template <> friend class A<T>;", which
12426   // is possibly well-formed?  Who even knows?
12427   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
12428     Diag(Loc, diag::err_tagless_friend_type_template)
12429       << DS.getSourceRange();
12430     return nullptr;
12431   }
12432 
12433   // C++98 [class.friend]p1: A friend of a class is a function
12434   //   or class that is not a member of the class . . .
12435   // This is fixed in DR77, which just barely didn't make the C++03
12436   // deadline.  It's also a very silly restriction that seriously
12437   // affects inner classes and which nobody else seems to implement;
12438   // thus we never diagnose it, not even in -pedantic.
12439   //
12440   // But note that we could warn about it: it's always useless to
12441   // friend one of your own members (it's not, however, worthless to
12442   // friend a member of an arbitrary specialization of your template).
12443 
12444   Decl *D;
12445   if (unsigned NumTempParamLists = TempParams.size())
12446     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
12447                                    NumTempParamLists,
12448                                    TempParams.data(),
12449                                    TSI,
12450                                    DS.getFriendSpecLoc());
12451   else
12452     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
12453 
12454   if (!D)
12455     return nullptr;
12456 
12457   D->setAccess(AS_public);
12458   CurContext->addDecl(D);
12459 
12460   return D;
12461 }
12462 
12463 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12464                                         MultiTemplateParamsArg TemplateParams) {
12465   const DeclSpec &DS = D.getDeclSpec();
12466 
12467   assert(DS.isFriendSpecified());
12468   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12469 
12470   SourceLocation Loc = D.getIdentifierLoc();
12471   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12472 
12473   // C++ [class.friend]p1
12474   //   A friend of a class is a function or class....
12475   // Note that this sees through typedefs, which is intended.
12476   // It *doesn't* see through dependent types, which is correct
12477   // according to [temp.arg.type]p3:
12478   //   If a declaration acquires a function type through a
12479   //   type dependent on a template-parameter and this causes
12480   //   a declaration that does not use the syntactic form of a
12481   //   function declarator to have a function type, the program
12482   //   is ill-formed.
12483   if (!TInfo->getType()->isFunctionType()) {
12484     Diag(Loc, diag::err_unexpected_friend);
12485 
12486     // It might be worthwhile to try to recover by creating an
12487     // appropriate declaration.
12488     return nullptr;
12489   }
12490 
12491   // C++ [namespace.memdef]p3
12492   //  - If a friend declaration in a non-local class first declares a
12493   //    class or function, the friend class or function is a member
12494   //    of the innermost enclosing namespace.
12495   //  - The name of the friend is not found by simple name lookup
12496   //    until a matching declaration is provided in that namespace
12497   //    scope (either before or after the class declaration granting
12498   //    friendship).
12499   //  - If a friend function is called, its name may be found by the
12500   //    name lookup that considers functions from namespaces and
12501   //    classes associated with the types of the function arguments.
12502   //  - When looking for a prior declaration of a class or a function
12503   //    declared as a friend, scopes outside the innermost enclosing
12504   //    namespace scope are not considered.
12505 
12506   CXXScopeSpec &SS = D.getCXXScopeSpec();
12507   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12508   DeclarationName Name = NameInfo.getName();
12509   assert(Name);
12510 
12511   // Check for unexpanded parameter packs.
12512   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12513       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12514       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
12515     return nullptr;
12516 
12517   // The context we found the declaration in, or in which we should
12518   // create the declaration.
12519   DeclContext *DC;
12520   Scope *DCScope = S;
12521   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12522                         ForRedeclaration);
12523 
12524   // There are five cases here.
12525   //   - There's no scope specifier and we're in a local class. Only look
12526   //     for functions declared in the immediately-enclosing block scope.
12527   // We recover from invalid scope qualifiers as if they just weren't there.
12528   FunctionDecl *FunctionContainingLocalClass = nullptr;
12529   if ((SS.isInvalid() || !SS.isSet()) &&
12530       (FunctionContainingLocalClass =
12531            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12532     // C++11 [class.friend]p11:
12533     //   If a friend declaration appears in a local class and the name
12534     //   specified is an unqualified name, a prior declaration is
12535     //   looked up without considering scopes that are outside the
12536     //   innermost enclosing non-class scope. For a friend function
12537     //   declaration, if there is no prior declaration, the program is
12538     //   ill-formed.
12539 
12540     // Find the innermost enclosing non-class scope. This is the block
12541     // scope containing the local class definition (or for a nested class,
12542     // the outer local class).
12543     DCScope = S->getFnParent();
12544 
12545     // Look up the function name in the scope.
12546     Previous.clear(LookupLocalFriendName);
12547     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12548 
12549     if (!Previous.empty()) {
12550       // All possible previous declarations must have the same context:
12551       // either they were declared at block scope or they are members of
12552       // one of the enclosing local classes.
12553       DC = Previous.getRepresentativeDecl()->getDeclContext();
12554     } else {
12555       // This is ill-formed, but provide the context that we would have
12556       // declared the function in, if we were permitted to, for error recovery.
12557       DC = FunctionContainingLocalClass;
12558     }
12559     adjustContextForLocalExternDecl(DC);
12560 
12561     // C++ [class.friend]p6:
12562     //   A function can be defined in a friend declaration of a class if and
12563     //   only if the class is a non-local class (9.8), the function name is
12564     //   unqualified, and the function has namespace scope.
12565     if (D.isFunctionDefinition()) {
12566       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12567     }
12568 
12569   //   - There's no scope specifier, in which case we just go to the
12570   //     appropriate scope and look for a function or function template
12571   //     there as appropriate.
12572   } else if (SS.isInvalid() || !SS.isSet()) {
12573     // C++11 [namespace.memdef]p3:
12574     //   If the name in a friend declaration is neither qualified nor
12575     //   a template-id and the declaration is a function or an
12576     //   elaborated-type-specifier, the lookup to determine whether
12577     //   the entity has been previously declared shall not consider
12578     //   any scopes outside the innermost enclosing namespace.
12579     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
12580 
12581     // Find the appropriate context according to the above.
12582     DC = CurContext;
12583 
12584     // Skip class contexts.  If someone can cite chapter and verse
12585     // for this behavior, that would be nice --- it's what GCC and
12586     // EDG do, and it seems like a reasonable intent, but the spec
12587     // really only says that checks for unqualified existing
12588     // declarations should stop at the nearest enclosing namespace,
12589     // not that they should only consider the nearest enclosing
12590     // namespace.
12591     while (DC->isRecord())
12592       DC = DC->getParent();
12593 
12594     DeclContext *LookupDC = DC;
12595     while (LookupDC->isTransparentContext())
12596       LookupDC = LookupDC->getParent();
12597 
12598     while (true) {
12599       LookupQualifiedName(Previous, LookupDC);
12600 
12601       if (!Previous.empty()) {
12602         DC = LookupDC;
12603         break;
12604       }
12605 
12606       if (isTemplateId) {
12607         if (isa<TranslationUnitDecl>(LookupDC)) break;
12608       } else {
12609         if (LookupDC->isFileContext()) break;
12610       }
12611       LookupDC = LookupDC->getParent();
12612     }
12613 
12614     DCScope = getScopeForDeclContext(S, DC);
12615 
12616   //   - There's a non-dependent scope specifier, in which case we
12617   //     compute it and do a previous lookup there for a function
12618   //     or function template.
12619   } else if (!SS.getScopeRep()->isDependent()) {
12620     DC = computeDeclContext(SS);
12621     if (!DC) return nullptr;
12622 
12623     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
12624 
12625     LookupQualifiedName(Previous, DC);
12626 
12627     // Ignore things found implicitly in the wrong scope.
12628     // TODO: better diagnostics for this case.  Suggesting the right
12629     // qualified scope would be nice...
12630     LookupResult::Filter F = Previous.makeFilter();
12631     while (F.hasNext()) {
12632       NamedDecl *D = F.next();
12633       if (!DC->InEnclosingNamespaceSetOf(
12634               D->getDeclContext()->getRedeclContext()))
12635         F.erase();
12636     }
12637     F.done();
12638 
12639     if (Previous.empty()) {
12640       D.setInvalidType();
12641       Diag(Loc, diag::err_qualified_friend_not_found)
12642           << Name << TInfo->getType();
12643       return nullptr;
12644     }
12645 
12646     // C++ [class.friend]p1: A friend of a class is a function or
12647     //   class that is not a member of the class . . .
12648     if (DC->Equals(CurContext))
12649       Diag(DS.getFriendSpecLoc(),
12650            getLangOpts().CPlusPlus11 ?
12651              diag::warn_cxx98_compat_friend_is_member :
12652              diag::err_friend_is_member);
12653 
12654     if (D.isFunctionDefinition()) {
12655       // C++ [class.friend]p6:
12656       //   A function can be defined in a friend declaration of a class if and
12657       //   only if the class is a non-local class (9.8), the function name is
12658       //   unqualified, and the function has namespace scope.
12659       SemaDiagnosticBuilder DB
12660         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12661 
12662       DB << SS.getScopeRep();
12663       if (DC->isFileContext())
12664         DB << FixItHint::CreateRemoval(SS.getRange());
12665       SS.clear();
12666     }
12667 
12668   //   - There's a scope specifier that does not match any template
12669   //     parameter lists, in which case we use some arbitrary context,
12670   //     create a method or method template, and wait for instantiation.
12671   //   - There's a scope specifier that does match some template
12672   //     parameter lists, which we don't handle right now.
12673   } else {
12674     if (D.isFunctionDefinition()) {
12675       // C++ [class.friend]p6:
12676       //   A function can be defined in a friend declaration of a class if and
12677       //   only if the class is a non-local class (9.8), the function name is
12678       //   unqualified, and the function has namespace scope.
12679       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12680         << SS.getScopeRep();
12681     }
12682 
12683     DC = CurContext;
12684     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
12685   }
12686 
12687   if (!DC->isRecord()) {
12688     // This implies that it has to be an operator or function.
12689     if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12690         D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12691         D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
12692       Diag(Loc, diag::err_introducing_special_friend) <<
12693         (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12694          D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
12695       return nullptr;
12696     }
12697   }
12698 
12699   // FIXME: This is an egregious hack to cope with cases where the scope stack
12700   // does not contain the declaration context, i.e., in an out-of-line
12701   // definition of a class.
12702   Scope FakeDCScope(S, Scope::DeclScope, Diags);
12703   if (!DCScope) {
12704     FakeDCScope.setEntity(DC);
12705     DCScope = &FakeDCScope;
12706   }
12707 
12708   bool AddToScope = true;
12709   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
12710                                           TemplateParams, AddToScope);
12711   if (!ND) return nullptr;
12712 
12713   assert(ND->getLexicalDeclContext() == CurContext);
12714 
12715   // If we performed typo correction, we might have added a scope specifier
12716   // and changed the decl context.
12717   DC = ND->getDeclContext();
12718 
12719   // Add the function declaration to the appropriate lookup tables,
12720   // adjusting the redeclarations list as necessary.  We don't
12721   // want to do this yet if the friending class is dependent.
12722   //
12723   // Also update the scope-based lookup if the target context's
12724   // lookup context is in lexical scope.
12725   if (!CurContext->isDependentContext()) {
12726     DC = DC->getRedeclContext();
12727     DC->makeDeclVisibleInContext(ND);
12728     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12729       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
12730   }
12731 
12732   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
12733                                        D.getIdentifierLoc(), ND,
12734                                        DS.getFriendSpecLoc());
12735   FrD->setAccess(AS_public);
12736   CurContext->addDecl(FrD);
12737 
12738   if (ND->isInvalidDecl()) {
12739     FrD->setInvalidDecl();
12740   } else {
12741     if (DC->isRecord()) CheckFriendAccess(ND);
12742 
12743     FunctionDecl *FD;
12744     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12745       FD = FTD->getTemplatedDecl();
12746     else
12747       FD = cast<FunctionDecl>(ND);
12748 
12749     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12750     // default argument expression, that declaration shall be a definition
12751     // and shall be the only declaration of the function or function
12752     // template in the translation unit.
12753     if (functionDeclHasDefaultArgument(FD)) {
12754       if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12755         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12756         Diag(OldFD->getLocation(), diag::note_previous_declaration);
12757       } else if (!D.isFunctionDefinition())
12758         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12759     }
12760 
12761     // Mark templated-scope function declarations as unsupported.
12762     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12763       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12764         << SS.getScopeRep() << SS.getRange()
12765         << cast<CXXRecordDecl>(CurContext);
12766       FrD->setUnsupportedFriend(true);
12767     }
12768   }
12769 
12770   return ND;
12771 }
12772 
12773 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12774   AdjustDeclIfTemplate(Dcl);
12775 
12776   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
12777   if (!Fn) {
12778     Diag(DelLoc, diag::err_deleted_non_function);
12779     return;
12780   }
12781 
12782   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
12783     // Don't consider the implicit declaration we generate for explicit
12784     // specializations. FIXME: Do not generate these implicit declarations.
12785     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12786          Prev->getPreviousDecl()) &&
12787         !Prev->isDefined()) {
12788       Diag(DelLoc, diag::err_deleted_decl_not_first);
12789       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12790            Prev->isImplicit() ? diag::note_previous_implicit_declaration
12791                               : diag::note_previous_declaration);
12792     }
12793     // If the declaration wasn't the first, we delete the function anyway for
12794     // recovery.
12795     Fn = Fn->getCanonicalDecl();
12796   }
12797 
12798   // dllimport/dllexport cannot be deleted.
12799   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12800     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12801     Fn->setInvalidDecl();
12802   }
12803 
12804   if (Fn->isDeleted())
12805     return;
12806 
12807   // See if we're deleting a function which is already known to override a
12808   // non-deleted virtual function.
12809   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12810     bool IssuedDiagnostic = false;
12811     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12812                                         E = MD->end_overridden_methods();
12813          I != E; ++I) {
12814       if (!(*MD->begin_overridden_methods())->isDeleted()) {
12815         if (!IssuedDiagnostic) {
12816           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12817           IssuedDiagnostic = true;
12818         }
12819         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12820       }
12821     }
12822   }
12823 
12824   // C++11 [basic.start.main]p3:
12825   //   A program that defines main as deleted [...] is ill-formed.
12826   if (Fn->isMain())
12827     Diag(DelLoc, diag::err_deleted_main);
12828 
12829   Fn->setDeletedAsWritten();
12830 }
12831 
12832 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
12833   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
12834 
12835   if (MD) {
12836     if (MD->getParent()->isDependentType()) {
12837       MD->setDefaulted();
12838       MD->setExplicitlyDefaulted();
12839       return;
12840     }
12841 
12842     CXXSpecialMember Member = getSpecialMember(MD);
12843     if (Member == CXXInvalid) {
12844       if (!MD->isInvalidDecl())
12845         Diag(DefaultLoc, diag::err_default_special_members);
12846       return;
12847     }
12848 
12849     MD->setDefaulted();
12850     MD->setExplicitlyDefaulted();
12851 
12852     // If this definition appears within the record, do the checking when
12853     // the record is complete.
12854     const FunctionDecl *Primary = MD;
12855     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
12856       // Find the uninstantiated declaration that actually had the '= default'
12857       // on it.
12858       Pattern->isDefined(Primary);
12859 
12860     // If the method was defaulted on its first declaration, we will have
12861     // already performed the checking in CheckCompletedCXXClass. Such a
12862     // declaration doesn't trigger an implicit definition.
12863     if (Primary == Primary->getCanonicalDecl())
12864       return;
12865 
12866     CheckExplicitlyDefaultedSpecialMember(MD);
12867 
12868     if (MD->isInvalidDecl())
12869       return;
12870 
12871     switch (Member) {
12872     case CXXDefaultConstructor:
12873       DefineImplicitDefaultConstructor(DefaultLoc,
12874                                        cast<CXXConstructorDecl>(MD));
12875       break;
12876     case CXXCopyConstructor:
12877       DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12878       break;
12879     case CXXCopyAssignment:
12880       DefineImplicitCopyAssignment(DefaultLoc, MD);
12881       break;
12882     case CXXDestructor:
12883       DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
12884       break;
12885     case CXXMoveConstructor:
12886       DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
12887       break;
12888     case CXXMoveAssignment:
12889       DefineImplicitMoveAssignment(DefaultLoc, MD);
12890       break;
12891     case CXXInvalid:
12892       llvm_unreachable("Invalid special member.");
12893     }
12894   } else {
12895     Diag(DefaultLoc, diag::err_default_special_members);
12896   }
12897 }
12898 
12899 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
12900   for (Stmt *SubStmt : S->children()) {
12901     if (!SubStmt)
12902       continue;
12903     if (isa<ReturnStmt>(SubStmt))
12904       Self.Diag(SubStmt->getLocStart(),
12905            diag::err_return_in_constructor_handler);
12906     if (!isa<Expr>(SubStmt))
12907       SearchForReturnInStmt(Self, SubStmt);
12908   }
12909 }
12910 
12911 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12912   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12913     CXXCatchStmt *Handler = TryBlock->getHandler(I);
12914     SearchForReturnInStmt(*this, Handler);
12915   }
12916 }
12917 
12918 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12919                                              const CXXMethodDecl *Old) {
12920   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12921   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12922 
12923   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12924 
12925   // If the calling conventions match, everything is fine
12926   if (NewCC == OldCC)
12927     return false;
12928 
12929   // If the calling conventions mismatch because the new function is static,
12930   // suppress the calling convention mismatch error; the error about static
12931   // function override (err_static_overrides_virtual from
12932   // Sema::CheckFunctionDeclaration) is more clear.
12933   if (New->getStorageClass() == SC_Static)
12934     return false;
12935 
12936   Diag(New->getLocation(),
12937        diag::err_conflicting_overriding_cc_attributes)
12938     << New->getDeclName() << New->getType() << Old->getType();
12939   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12940   return true;
12941 }
12942 
12943 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12944                                              const CXXMethodDecl *Old) {
12945   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12946   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
12947 
12948   if (Context.hasSameType(NewTy, OldTy) ||
12949       NewTy->isDependentType() || OldTy->isDependentType())
12950     return false;
12951 
12952   // Check if the return types are covariant
12953   QualType NewClassTy, OldClassTy;
12954 
12955   /// Both types must be pointers or references to classes.
12956   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12957     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12958       NewClassTy = NewPT->getPointeeType();
12959       OldClassTy = OldPT->getPointeeType();
12960     }
12961   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12962     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12963       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12964         NewClassTy = NewRT->getPointeeType();
12965         OldClassTy = OldRT->getPointeeType();
12966       }
12967     }
12968   }
12969 
12970   // The return types aren't either both pointers or references to a class type.
12971   if (NewClassTy.isNull()) {
12972     Diag(New->getLocation(),
12973          diag::err_different_return_type_for_overriding_virtual_function)
12974         << New->getDeclName() << NewTy << OldTy
12975         << New->getReturnTypeSourceRange();
12976     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12977         << Old->getReturnTypeSourceRange();
12978 
12979     return true;
12980   }
12981 
12982   // C++ [class.virtual]p6:
12983   //   If the return type of D::f differs from the return type of B::f, the
12984   //   class type in the return type of D::f shall be complete at the point of
12985   //   declaration of D::f or shall be the class type D.
12986   if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12987     if (!RT->isBeingDefined() &&
12988         RequireCompleteType(New->getLocation(), NewClassTy,
12989                             diag::err_covariant_return_incomplete,
12990                             New->getDeclName()))
12991     return true;
12992   }
12993 
12994   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12995     // Check if the new class derives from the old class.
12996     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12997       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12998           << New->getDeclName() << NewTy << OldTy
12999           << New->getReturnTypeSourceRange();
13000       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13001           << Old->getReturnTypeSourceRange();
13002       return true;
13003     }
13004 
13005     // Check if we the conversion from derived to base is valid.
13006     if (CheckDerivedToBaseConversion(
13007             NewClassTy, OldClassTy,
13008             diag::err_covariant_return_inaccessible_base,
13009             diag::err_covariant_return_ambiguous_derived_to_base_conv,
13010             New->getLocation(), New->getReturnTypeSourceRange(),
13011             New->getDeclName(), nullptr)) {
13012       // FIXME: this note won't trigger for delayed access control
13013       // diagnostics, and it's impossible to get an undelayed error
13014       // here from access control during the original parse because
13015       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
13016       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13017           << Old->getReturnTypeSourceRange();
13018       return true;
13019     }
13020   }
13021 
13022   // The qualifiers of the return types must be the same.
13023   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
13024     Diag(New->getLocation(),
13025          diag::err_covariant_return_type_different_qualifications)
13026         << New->getDeclName() << NewTy << OldTy
13027         << New->getReturnTypeSourceRange();
13028     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13029         << Old->getReturnTypeSourceRange();
13030     return true;
13031   };
13032 
13033 
13034   // The new class type must have the same or less qualifiers as the old type.
13035   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
13036     Diag(New->getLocation(),
13037          diag::err_covariant_return_type_class_type_more_qualified)
13038         << New->getDeclName() << NewTy << OldTy
13039         << New->getReturnTypeSourceRange();
13040     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
13041         << Old->getReturnTypeSourceRange();
13042     return true;
13043   };
13044 
13045   return false;
13046 }
13047 
13048 /// \brief Mark the given method pure.
13049 ///
13050 /// \param Method the method to be marked pure.
13051 ///
13052 /// \param InitRange the source range that covers the "0" initializer.
13053 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
13054   SourceLocation EndLoc = InitRange.getEnd();
13055   if (EndLoc.isValid())
13056     Method->setRangeEnd(EndLoc);
13057 
13058   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
13059     Method->setPure();
13060     return false;
13061   }
13062 
13063   if (!Method->isInvalidDecl())
13064     Diag(Method->getLocation(), diag::err_non_virtual_pure)
13065       << Method->getDeclName() << InitRange;
13066   return true;
13067 }
13068 
13069 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
13070   if (D->getFriendObjectKind())
13071     Diag(D->getLocation(), diag::err_pure_friend);
13072   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
13073     CheckPureMethod(M, ZeroLoc);
13074   else
13075     Diag(D->getLocation(), diag::err_illegal_initializer);
13076 }
13077 
13078 /// \brief Determine whether the given declaration is a static data member.
13079 static bool isStaticDataMember(const Decl *D) {
13080   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
13081     return Var->isStaticDataMember();
13082 
13083   return false;
13084 }
13085 
13086 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
13087 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
13088 /// is a fresh scope pushed for just this purpose.
13089 ///
13090 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
13091 /// static data member of class X, names should be looked up in the scope of
13092 /// class X.
13093 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
13094   // If there is no declaration, there was an error parsing it.
13095   if (!D || D->isInvalidDecl())
13096     return;
13097 
13098   // We will always have a nested name specifier here, but this declaration
13099   // might not be out of line if the specifier names the current namespace:
13100   //   extern int n;
13101   //   int ::n = 0;
13102   if (D->isOutOfLine())
13103     EnterDeclaratorContext(S, D->getDeclContext());
13104 
13105   // If we are parsing the initializer for a static data member, push a
13106   // new expression evaluation context that is associated with this static
13107   // data member.
13108   if (isStaticDataMember(D))
13109     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
13110 }
13111 
13112 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
13113 /// initializer for the out-of-line declaration 'D'.
13114 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
13115   // If there is no declaration, there was an error parsing it.
13116   if (!D || D->isInvalidDecl())
13117     return;
13118 
13119   if (isStaticDataMember(D))
13120     PopExpressionEvaluationContext();
13121 
13122   if (D->isOutOfLine())
13123     ExitDeclaratorContext(S);
13124 }
13125 
13126 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
13127 /// C++ if/switch/while/for statement.
13128 /// e.g: "if (int x = f()) {...}"
13129 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
13130   // C++ 6.4p2:
13131   // The declarator shall not specify a function or an array.
13132   // The type-specifier-seq shall not contain typedef and shall not declare a
13133   // new class or enumeration.
13134   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
13135          "Parser allowed 'typedef' as storage class of condition decl.");
13136 
13137   Decl *Dcl = ActOnDeclarator(S, D);
13138   if (!Dcl)
13139     return true;
13140 
13141   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
13142     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
13143       << D.getSourceRange();
13144     return true;
13145   }
13146 
13147   return Dcl;
13148 }
13149 
13150 void Sema::LoadExternalVTableUses() {
13151   if (!ExternalSource)
13152     return;
13153 
13154   SmallVector<ExternalVTableUse, 4> VTables;
13155   ExternalSource->ReadUsedVTables(VTables);
13156   SmallVector<VTableUse, 4> NewUses;
13157   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
13158     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
13159       = VTablesUsed.find(VTables[I].Record);
13160     // Even if a definition wasn't required before, it may be required now.
13161     if (Pos != VTablesUsed.end()) {
13162       if (!Pos->second && VTables[I].DefinitionRequired)
13163         Pos->second = true;
13164       continue;
13165     }
13166 
13167     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
13168     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
13169   }
13170 
13171   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
13172 }
13173 
13174 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
13175                           bool DefinitionRequired) {
13176   // Ignore any vtable uses in unevaluated operands or for classes that do
13177   // not have a vtable.
13178   if (!Class->isDynamicClass() || Class->isDependentContext() ||
13179       CurContext->isDependentContext() || isUnevaluatedContext())
13180     return;
13181 
13182   // Try to insert this class into the map.
13183   LoadExternalVTableUses();
13184   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13185   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
13186     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
13187   if (!Pos.second) {
13188     // If we already had an entry, check to see if we are promoting this vtable
13189     // to require a definition. If so, we need to reappend to the VTableUses
13190     // list, since we may have already processed the first entry.
13191     if (DefinitionRequired && !Pos.first->second) {
13192       Pos.first->second = true;
13193     } else {
13194       // Otherwise, we can early exit.
13195       return;
13196     }
13197   } else {
13198     // The Microsoft ABI requires that we perform the destructor body
13199     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
13200     // the deleting destructor is emitted with the vtable, not with the
13201     // destructor definition as in the Itanium ABI.
13202     // If it has a definition, we do the check at that point instead.
13203     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13204         Class->hasUserDeclaredDestructor() &&
13205         !Class->getDestructor()->isDefined() &&
13206         !Class->getDestructor()->isDeleted()) {
13207       CXXDestructorDecl *DD = Class->getDestructor();
13208       ContextRAII SavedContext(*this, DD);
13209       CheckDestructor(DD);
13210     }
13211   }
13212 
13213   // Local classes need to have their virtual members marked
13214   // immediately. For all other classes, we mark their virtual members
13215   // at the end of the translation unit.
13216   if (Class->isLocalClass())
13217     MarkVirtualMembersReferenced(Loc, Class);
13218   else
13219     VTableUses.push_back(std::make_pair(Class, Loc));
13220 }
13221 
13222 bool Sema::DefineUsedVTables() {
13223   LoadExternalVTableUses();
13224   if (VTableUses.empty())
13225     return false;
13226 
13227   // Note: The VTableUses vector could grow as a result of marking
13228   // the members of a class as "used", so we check the size each
13229   // time through the loop and prefer indices (which are stable) to
13230   // iterators (which are not).
13231   bool DefinedAnything = false;
13232   for (unsigned I = 0; I != VTableUses.size(); ++I) {
13233     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
13234     if (!Class)
13235       continue;
13236 
13237     SourceLocation Loc = VTableUses[I].second;
13238 
13239     bool DefineVTable = true;
13240 
13241     // If this class has a key function, but that key function is
13242     // defined in another translation unit, we don't need to emit the
13243     // vtable even though we're using it.
13244     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
13245     if (KeyFunction && !KeyFunction->hasBody()) {
13246       // The key function is in another translation unit.
13247       DefineVTable = false;
13248       TemplateSpecializationKind TSK =
13249           KeyFunction->getTemplateSpecializationKind();
13250       assert(TSK != TSK_ExplicitInstantiationDefinition &&
13251              TSK != TSK_ImplicitInstantiation &&
13252              "Instantiations don't have key functions");
13253       (void)TSK;
13254     } else if (!KeyFunction) {
13255       // If we have a class with no key function that is the subject
13256       // of an explicit instantiation declaration, suppress the
13257       // vtable; it will live with the explicit instantiation
13258       // definition.
13259       bool IsExplicitInstantiationDeclaration
13260         = Class->getTemplateSpecializationKind()
13261                                       == TSK_ExplicitInstantiationDeclaration;
13262       for (auto R : Class->redecls()) {
13263         TemplateSpecializationKind TSK
13264           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
13265         if (TSK == TSK_ExplicitInstantiationDeclaration)
13266           IsExplicitInstantiationDeclaration = true;
13267         else if (TSK == TSK_ExplicitInstantiationDefinition) {
13268           IsExplicitInstantiationDeclaration = false;
13269           break;
13270         }
13271       }
13272 
13273       if (IsExplicitInstantiationDeclaration)
13274         DefineVTable = false;
13275     }
13276 
13277     // The exception specifications for all virtual members may be needed even
13278     // if we are not providing an authoritative form of the vtable in this TU.
13279     // We may choose to emit it available_externally anyway.
13280     if (!DefineVTable) {
13281       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13282       continue;
13283     }
13284 
13285     // Mark all of the virtual members of this class as referenced, so
13286     // that we can build a vtable. Then, tell the AST consumer that a
13287     // vtable for this class is required.
13288     DefinedAnything = true;
13289     MarkVirtualMembersReferenced(Loc, Class);
13290     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13291     if (VTablesUsed[Canonical])
13292       Consumer.HandleVTable(Class);
13293 
13294     // Optionally warn if we're emitting a weak vtable.
13295     if (Class->isExternallyVisible() &&
13296         Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
13297       const FunctionDecl *KeyFunctionDef = nullptr;
13298       if (!KeyFunction ||
13299           (KeyFunction->hasBody(KeyFunctionDef) &&
13300            KeyFunctionDef->isInlined()))
13301         Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13302              TSK_ExplicitInstantiationDefinition
13303              ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13304           << Class;
13305     }
13306   }
13307   VTableUses.clear();
13308 
13309   return DefinedAnything;
13310 }
13311 
13312 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13313                                                  const CXXRecordDecl *RD) {
13314   for (const auto *I : RD->methods())
13315     if (I->isVirtual() && !I->isPure())
13316       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
13317 }
13318 
13319 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13320                                         const CXXRecordDecl *RD) {
13321   // Mark all functions which will appear in RD's vtable as used.
13322   CXXFinalOverriderMap FinalOverriders;
13323   RD->getFinalOverriders(FinalOverriders);
13324   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13325                                             E = FinalOverriders.end();
13326        I != E; ++I) {
13327     for (OverridingMethods::const_iterator OI = I->second.begin(),
13328                                            OE = I->second.end();
13329          OI != OE; ++OI) {
13330       assert(OI->second.size() > 0 && "no final overrider");
13331       CXXMethodDecl *Overrider = OI->second.front().Method;
13332 
13333       // C++ [basic.def.odr]p2:
13334       //   [...] A virtual member function is used if it is not pure. [...]
13335       if (!Overrider->isPure())
13336         MarkFunctionReferenced(Loc, Overrider);
13337     }
13338   }
13339 
13340   // Only classes that have virtual bases need a VTT.
13341   if (RD->getNumVBases() == 0)
13342     return;
13343 
13344   for (const auto &I : RD->bases()) {
13345     const CXXRecordDecl *Base =
13346         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
13347     if (Base->getNumVBases() == 0)
13348       continue;
13349     MarkVirtualMembersReferenced(Loc, Base);
13350   }
13351 }
13352 
13353 /// SetIvarInitializers - This routine builds initialization ASTs for the
13354 /// Objective-C implementation whose ivars need be initialized.
13355 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
13356   if (!getLangOpts().CPlusPlus)
13357     return;
13358   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
13359     SmallVector<ObjCIvarDecl*, 8> ivars;
13360     CollectIvarsToConstructOrDestruct(OID, ivars);
13361     if (ivars.empty())
13362       return;
13363     SmallVector<CXXCtorInitializer*, 32> AllToInit;
13364     for (unsigned i = 0; i < ivars.size(); i++) {
13365       FieldDecl *Field = ivars[i];
13366       if (Field->isInvalidDecl())
13367         continue;
13368 
13369       CXXCtorInitializer *Member;
13370       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13371       InitializationKind InitKind =
13372         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
13373 
13374       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13375       ExprResult MemberInit =
13376         InitSeq.Perform(*this, InitEntity, InitKind, None);
13377       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
13378       // Note, MemberInit could actually come back empty if no initialization
13379       // is required (e.g., because it would call a trivial default constructor)
13380       if (!MemberInit.get() || MemberInit.isInvalid())
13381         continue;
13382 
13383       Member =
13384         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13385                                          SourceLocation(),
13386                                          MemberInit.getAs<Expr>(),
13387                                          SourceLocation());
13388       AllToInit.push_back(Member);
13389 
13390       // Be sure that the destructor is accessible and is marked as referenced.
13391       if (const RecordType *RecordTy =
13392               Context.getBaseElementType(Field->getType())
13393                   ->getAs<RecordType>()) {
13394         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
13395         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
13396           MarkFunctionReferenced(Field->getLocation(), Destructor);
13397           CheckDestructorAccess(Field->getLocation(), Destructor,
13398                             PDiag(diag::err_access_dtor_ivar)
13399                               << Context.getBaseElementType(Field->getType()));
13400         }
13401       }
13402     }
13403     ObjCImplementation->setIvarInitializers(Context,
13404                                             AllToInit.data(), AllToInit.size());
13405   }
13406 }
13407 
13408 static
13409 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13410                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13411                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13412                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13413                            Sema &S) {
13414   if (Ctor->isInvalidDecl())
13415     return;
13416 
13417   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13418 
13419   // Target may not be determinable yet, for instance if this is a dependent
13420   // call in an uninstantiated template.
13421   if (Target) {
13422     const FunctionDecl *FNTarget = nullptr;
13423     (void)Target->hasBody(FNTarget);
13424     Target = const_cast<CXXConstructorDecl*>(
13425       cast_or_null<CXXConstructorDecl>(FNTarget));
13426   }
13427 
13428   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13429                      // Avoid dereferencing a null pointer here.
13430                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
13431 
13432   if (!Current.insert(Canonical).second)
13433     return;
13434 
13435   // We know that beyond here, we aren't chaining into a cycle.
13436   if (!Target || !Target->isDelegatingConstructor() ||
13437       Target->isInvalidDecl() || Valid.count(TCanonical)) {
13438     Valid.insert(Current.begin(), Current.end());
13439     Current.clear();
13440   // We've hit a cycle.
13441   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13442              Current.count(TCanonical)) {
13443     // If we haven't diagnosed this cycle yet, do so now.
13444     if (!Invalid.count(TCanonical)) {
13445       S.Diag((*Ctor->init_begin())->getSourceLocation(),
13446              diag::warn_delegating_ctor_cycle)
13447         << Ctor;
13448 
13449       // Don't add a note for a function delegating directly to itself.
13450       if (TCanonical != Canonical)
13451         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13452 
13453       CXXConstructorDecl *C = Target;
13454       while (C->getCanonicalDecl() != Canonical) {
13455         const FunctionDecl *FNTarget = nullptr;
13456         (void)C->getTargetConstructor()->hasBody(FNTarget);
13457         assert(FNTarget && "Ctor cycle through bodiless function");
13458 
13459         C = const_cast<CXXConstructorDecl*>(
13460           cast<CXXConstructorDecl>(FNTarget));
13461         S.Diag(C->getLocation(), diag::note_which_delegates_to);
13462       }
13463     }
13464 
13465     Invalid.insert(Current.begin(), Current.end());
13466     Current.clear();
13467   } else {
13468     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13469   }
13470 }
13471 
13472 
13473 void Sema::CheckDelegatingCtorCycles() {
13474   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13475 
13476   for (DelegatingCtorDeclsType::iterator
13477          I = DelegatingCtorDecls.begin(ExternalSource),
13478          E = DelegatingCtorDecls.end();
13479        I != E; ++I)
13480     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
13481 
13482   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13483                                                          CE = Invalid.end();
13484        CI != CE; ++CI)
13485     (*CI)->setInvalidDecl();
13486 }
13487 
13488 namespace {
13489   /// \brief AST visitor that finds references to the 'this' expression.
13490   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13491     Sema &S;
13492 
13493   public:
13494     explicit FindCXXThisExpr(Sema &S) : S(S) { }
13495 
13496     bool VisitCXXThisExpr(CXXThisExpr *E) {
13497       S.Diag(E->getLocation(), diag::err_this_static_member_func)
13498         << E->isImplicit();
13499       return false;
13500     }
13501   };
13502 }
13503 
13504 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13505   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13506   if (!TSInfo)
13507     return false;
13508 
13509   TypeLoc TL = TSInfo->getTypeLoc();
13510   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13511   if (!ProtoTL)
13512     return false;
13513 
13514   // C++11 [expr.prim.general]p3:
13515   //   [The expression this] shall not appear before the optional
13516   //   cv-qualifier-seq and it shall not appear within the declaration of a
13517   //   static member function (although its type and value category are defined
13518   //   within a static member function as they are within a non-static member
13519   //   function). [ Note: this is because declaration matching does not occur
13520   //  until the complete declarator is known. - end note ]
13521   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13522   FindCXXThisExpr Finder(*this);
13523 
13524   // If the return type came after the cv-qualifier-seq, check it now.
13525   if (Proto->hasTrailingReturn() &&
13526       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
13527     return true;
13528 
13529   // Check the exception specification.
13530   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13531     return true;
13532 
13533   return checkThisInStaticMemberFunctionAttributes(Method);
13534 }
13535 
13536 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13537   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13538   if (!TSInfo)
13539     return false;
13540 
13541   TypeLoc TL = TSInfo->getTypeLoc();
13542   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
13543   if (!ProtoTL)
13544     return false;
13545 
13546   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
13547   FindCXXThisExpr Finder(*this);
13548 
13549   switch (Proto->getExceptionSpecType()) {
13550   case EST_Unparsed:
13551   case EST_Uninstantiated:
13552   case EST_Unevaluated:
13553   case EST_BasicNoexcept:
13554   case EST_DynamicNone:
13555   case EST_MSAny:
13556   case EST_None:
13557     break;
13558 
13559   case EST_ComputedNoexcept:
13560     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13561       return true;
13562 
13563   case EST_Dynamic:
13564     for (const auto &E : Proto->exceptions()) {
13565       if (!Finder.TraverseType(E))
13566         return true;
13567     }
13568     break;
13569   }
13570 
13571   return false;
13572 }
13573 
13574 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13575   FindCXXThisExpr Finder(*this);
13576 
13577   // Check attributes.
13578   for (const auto *A : Method->attrs()) {
13579     // FIXME: This should be emitted by tblgen.
13580     Expr *Arg = nullptr;
13581     ArrayRef<Expr *> Args;
13582     if (const auto *G = dyn_cast<GuardedByAttr>(A))
13583       Arg = G->getArg();
13584     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
13585       Arg = G->getArg();
13586     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
13587       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
13588     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
13589       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
13590     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
13591       Arg = ETLF->getSuccessValue();
13592       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
13593     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
13594       Arg = STLF->getSuccessValue();
13595       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
13596     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
13597       Arg = LR->getArg();
13598     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
13599       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
13600     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
13601       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13602     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
13603       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13604     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
13605       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
13606     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
13607       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
13608 
13609     if (Arg && !Finder.TraverseStmt(Arg))
13610       return true;
13611 
13612     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13613       if (!Finder.TraverseStmt(Args[I]))
13614         return true;
13615     }
13616   }
13617 
13618   return false;
13619 }
13620 
13621 void Sema::checkExceptionSpecification(
13622     bool IsTopLevel, ExceptionSpecificationType EST,
13623     ArrayRef<ParsedType> DynamicExceptions,
13624     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13625     SmallVectorImpl<QualType> &Exceptions,
13626     FunctionProtoType::ExceptionSpecInfo &ESI) {
13627   Exceptions.clear();
13628   ESI.Type = EST;
13629   if (EST == EST_Dynamic) {
13630     Exceptions.reserve(DynamicExceptions.size());
13631     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13632       // FIXME: Preserve type source info.
13633       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13634 
13635       if (IsTopLevel) {
13636         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13637         collectUnexpandedParameterPacks(ET, Unexpanded);
13638         if (!Unexpanded.empty()) {
13639           DiagnoseUnexpandedParameterPacks(
13640               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13641               Unexpanded);
13642           continue;
13643         }
13644       }
13645 
13646       // Check that the type is valid for an exception spec, and
13647       // drop it if not.
13648       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13649         Exceptions.push_back(ET);
13650     }
13651     ESI.Exceptions = Exceptions;
13652     return;
13653   }
13654 
13655   if (EST == EST_ComputedNoexcept) {
13656     // If an error occurred, there's no expression here.
13657     if (NoexceptExpr) {
13658       assert((NoexceptExpr->isTypeDependent() ||
13659               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13660               Context.BoolTy) &&
13661              "Parser should have made sure that the expression is boolean");
13662       if (IsTopLevel && NoexceptExpr &&
13663           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13664         ESI.Type = EST_BasicNoexcept;
13665         return;
13666       }
13667 
13668       if (!NoexceptExpr->isValueDependent())
13669         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
13670                          diag::err_noexcept_needs_constant_expression,
13671                          /*AllowFold*/ false).get();
13672       ESI.NoexceptExpr = NoexceptExpr;
13673     }
13674     return;
13675   }
13676 }
13677 
13678 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13679              ExceptionSpecificationType EST,
13680              SourceRange SpecificationRange,
13681              ArrayRef<ParsedType> DynamicExceptions,
13682              ArrayRef<SourceRange> DynamicExceptionRanges,
13683              Expr *NoexceptExpr) {
13684   if (!MethodD)
13685     return;
13686 
13687   // Dig out the method we're referring to.
13688   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13689     MethodD = FunTmpl->getTemplatedDecl();
13690 
13691   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13692   if (!Method)
13693     return;
13694 
13695   // Check the exception specification.
13696   llvm::SmallVector<QualType, 4> Exceptions;
13697   FunctionProtoType::ExceptionSpecInfo ESI;
13698   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13699                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
13700                               ESI);
13701 
13702   // Update the exception specification on the function type.
13703   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13704 
13705   if (Method->isStatic())
13706     checkThisInStaticMemberFunctionExceptionSpec(Method);
13707 
13708   if (Method->isVirtual()) {
13709     // Check overrides, which we previously had to delay.
13710     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13711                                      OEnd = Method->end_overridden_methods();
13712          O != OEnd; ++O)
13713       CheckOverridingFunctionExceptionSpec(Method, *O);
13714   }
13715 }
13716 
13717 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13718 ///
13719 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13720                                        SourceLocation DeclStart,
13721                                        Declarator &D, Expr *BitWidth,
13722                                        InClassInitStyle InitStyle,
13723                                        AccessSpecifier AS,
13724                                        AttributeList *MSPropertyAttr) {
13725   IdentifierInfo *II = D.getIdentifier();
13726   if (!II) {
13727     Diag(DeclStart, diag::err_anonymous_property);
13728     return nullptr;
13729   }
13730   SourceLocation Loc = D.getIdentifierLoc();
13731 
13732   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13733   QualType T = TInfo->getType();
13734   if (getLangOpts().CPlusPlus) {
13735     CheckExtraCXXDefaultArguments(D);
13736 
13737     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13738                                         UPPC_DataMemberType)) {
13739       D.setInvalidType();
13740       T = Context.IntTy;
13741       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13742     }
13743   }
13744 
13745   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13746 
13747   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13748     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13749          diag::err_invalid_thread)
13750       << DeclSpec::getSpecifierName(TSCS);
13751 
13752   // Check to see if this name was declared as a member previously
13753   NamedDecl *PrevDecl = nullptr;
13754   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13755   LookupName(Previous, S);
13756   switch (Previous.getResultKind()) {
13757   case LookupResult::Found:
13758   case LookupResult::FoundUnresolvedValue:
13759     PrevDecl = Previous.getAsSingle<NamedDecl>();
13760     break;
13761 
13762   case LookupResult::FoundOverloaded:
13763     PrevDecl = Previous.getRepresentativeDecl();
13764     break;
13765 
13766   case LookupResult::NotFound:
13767   case LookupResult::NotFoundInCurrentInstantiation:
13768   case LookupResult::Ambiguous:
13769     break;
13770   }
13771 
13772   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13773     // Maybe we will complain about the shadowed template parameter.
13774     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13775     // Just pretend that we didn't see the previous declaration.
13776     PrevDecl = nullptr;
13777   }
13778 
13779   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13780     PrevDecl = nullptr;
13781 
13782   SourceLocation TSSL = D.getLocStart();
13783   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
13784   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13785       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
13786   ProcessDeclAttributes(TUScope, NewPD, D);
13787   NewPD->setAccess(AS);
13788 
13789   if (NewPD->isInvalidDecl())
13790     Record->setInvalidDecl();
13791 
13792   if (D.getDeclSpec().isModulePrivateSpecified())
13793     NewPD->setModulePrivate();
13794 
13795   if (NewPD->isInvalidDecl() && PrevDecl) {
13796     // Don't introduce NewFD into scope; there's already something
13797     // with the same name in the same scope.
13798   } else if (II) {
13799     PushOnScopeChains(NewPD, S);
13800   } else
13801     Record->addDecl(NewPD);
13802 
13803   return NewPD;
13804 }
13805