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/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include <map>
44 #include <set>
45 
46 using namespace clang;
47 
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54   /// the default argument of a parameter to determine whether it
55   /// contains any ill-formed subexpressions. For example, this will
56   /// diagnose the use of local variables or parameters within the
57   /// default argument expression.
58   class CheckDefaultArgumentVisitor
59     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
60     Expr *DefaultArg;
61     Sema *S;
62 
63   public:
64     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65       : DefaultArg(defarg), S(s) {}
66 
67     bool VisitExpr(Expr *Node);
68     bool VisitDeclRefExpr(DeclRefExpr *DRE);
69     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70     bool VisitLambdaExpr(LambdaExpr *Lambda);
71     bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
72   };
73 
74   /// VisitExpr - Visit all of the children of this expression.
75   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76     bool IsInvalid = false;
77     for (Stmt *SubStmt : Node->children())
78       IsInvalid |= Visit(SubStmt);
79     return IsInvalid;
80   }
81 
82   /// VisitDeclRefExpr - Visit a reference to a declaration, to
83   /// determine whether this declaration can be used in the default
84   /// argument expression.
85   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86     NamedDecl *Decl = DRE->getDecl();
87     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88       // C++ [dcl.fct.default]p9
89       //   Default arguments are evaluated each time the function is
90       //   called. The order of evaluation of function arguments is
91       //   unspecified. Consequently, parameters of a function shall not
92       //   be used in default argument expressions, even if they are not
93       //   evaluated. Parameters of a function declared before a default
94       //   argument expression are in scope and can hide namespace and
95       //   class member names.
96       return S->Diag(DRE->getLocStart(),
97                      diag::err_param_default_argument_references_param)
98          << Param->getDeclName() << DefaultArg->getSourceRange();
99     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100       // C++ [dcl.fct.default]p7
101       //   Local variables shall not be used in default argument
102       //   expressions.
103       if (VDecl->isLocalVarDecl())
104         return S->Diag(DRE->getLocStart(),
105                        diag::err_param_default_argument_references_local)
106           << VDecl->getDeclName() << DefaultArg->getSourceRange();
107     }
108 
109     return false;
110   }
111 
112   /// VisitCXXThisExpr - Visit a C++ "this" expression.
113   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114     // C++ [dcl.fct.default]p8:
115     //   The keyword this shall not be used in a default argument of a
116     //   member function.
117     return S->Diag(ThisE->getLocStart(),
118                    diag::err_param_default_argument_references_this)
119                << ThisE->getSourceRange();
120   }
121 
122   bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123     bool Invalid = false;
124     for (PseudoObjectExpr::semantics_iterator
125            i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
126       Expr *E = *i;
127 
128       // Look through bindings.
129       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130         E = OVE->getSourceExpr();
131         assert(E && "pseudo-object binding without source expression?");
132       }
133 
134       Invalid |= Visit(E);
135     }
136     return Invalid;
137   }
138 
139   bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140     // C++11 [expr.lambda.prim]p13:
141     //   A lambda-expression appearing in a default argument shall not
142     //   implicitly or explicitly capture any entity.
143     if (Lambda->capture_begin() == Lambda->capture_end())
144       return false;
145 
146     return S->Diag(Lambda->getLocStart(),
147                    diag::err_lambda_capture_default_arg);
148   }
149 }
150 
151 void
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153                                                  const CXXMethodDecl *Method) {
154   // If we have an MSAny spec already, don't bother.
155   if (!Method || ComputedEST == EST_MSAny)
156     return;
157 
158   const FunctionProtoType *Proto
159     = Method->getType()->getAs<FunctionProtoType>();
160   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
161   if (!Proto)
162     return;
163 
164   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 
166   // If we have a throw-all spec at this point, ignore the function.
167   if (ComputedEST == EST_None)
168     return;
169 
170   switch(EST) {
171   // If this function can throw any exceptions, make a note of that.
172   case EST_MSAny:
173   case EST_None:
174     ClearExceptions();
175     ComputedEST = EST;
176     return;
177   // FIXME: If the call to this decl is using any of its default arguments, we
178   // need to search them for potentially-throwing calls.
179   // If this function has a basic noexcept, it doesn't affect the outcome.
180   case EST_BasicNoexcept:
181     return;
182   // If we're still at noexcept(true) and there's a nothrow() callee,
183   // change to that specification.
184   case EST_DynamicNone:
185     if (ComputedEST == EST_BasicNoexcept)
186       ComputedEST = EST_DynamicNone;
187     return;
188   // Check out noexcept specs.
189   case EST_ComputedNoexcept:
190   {
191     FunctionProtoType::NoexceptResult NR =
192         Proto->getNoexceptSpec(Self->Context);
193     assert(NR != FunctionProtoType::NR_NoNoexcept &&
194            "Must have noexcept result for EST_ComputedNoexcept.");
195     assert(NR != FunctionProtoType::NR_Dependent &&
196            "Should not generate implicit declarations for dependent cases, "
197            "and don't know how to handle them anyway.");
198     // noexcept(false) -> no spec on the new function
199     if (NR == FunctionProtoType::NR_Throw) {
200       ClearExceptions();
201       ComputedEST = EST_None;
202     }
203     // noexcept(true) won't change anything either.
204     return;
205   }
206   default:
207     break;
208   }
209   assert(EST == EST_Dynamic && "EST case not considered earlier.");
210   assert(ComputedEST != EST_None &&
211          "Shouldn't collect exceptions when throw-all is guaranteed.");
212   ComputedEST = EST_Dynamic;
213   // Record the exceptions in this function's exception specification.
214   for (const auto &E : Proto->exceptions())
215     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216       Exceptions.push_back(E);
217 }
218 
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220   if (!E || ComputedEST == EST_MSAny)
221     return;
222 
223   // FIXME:
224   //
225   // C++0x [except.spec]p14:
226   //   [An] implicit exception-specification specifies the type-id T if and
227   // only if T is allowed by the exception-specification of a function directly
228   // invoked by f's implicit definition; f shall allow all exceptions if any
229   // function it directly invokes allows all exceptions, and f shall allow no
230   // exceptions if every function it directly invokes allows no exceptions.
231   //
232   // Note in particular that if an implicit exception-specification is generated
233   // for a function containing a throw-expression, that specification can still
234   // be noexcept(true).
235   //
236   // Note also that 'directly invoked' is not defined in the standard, and there
237   // is no indication that we should only consider potentially-evaluated calls.
238   //
239   // Ultimately we should implement the intent of the standard: the exception
240   // specification should be the set of exceptions which can be thrown by the
241   // implicit definition. For now, we assume that any non-nothrow expression can
242   // throw any exception.
243 
244   if (Self->canThrow(E))
245     ComputedEST = EST_None;
246 }
247 
248 bool
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250                               SourceLocation EqualLoc) {
251   if (RequireCompleteType(Param->getLocation(), Param->getType(),
252                           diag::err_typecheck_decl_incomplete_type)) {
253     Param->setInvalidDecl();
254     return true;
255   }
256 
257   // C++ [dcl.fct.default]p5
258   //   A default argument expression is implicitly converted (clause
259   //   4) to the parameter type. The default argument expression has
260   //   the same semantic constraints as the initializer expression in
261   //   a declaration of a variable of the parameter type, using the
262   //   copy-initialization semantics (8.5).
263   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
264                                                                     Param);
265   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
266                                                            EqualLoc);
267   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269   if (Result.isInvalid())
270     return true;
271   Arg = Result.getAs<Expr>();
272 
273   CheckCompletedExpr(Arg, EqualLoc);
274   Arg = MaybeCreateExprWithCleanups(Arg);
275 
276   // Okay: add the default argument to the parameter
277   Param->setDefaultArg(Arg);
278 
279   // We have already instantiated this parameter; provide each of the
280   // instantiations with the uninstantiated default argument.
281   UnparsedDefaultArgInstantiationsMap::iterator InstPos
282     = UnparsedDefaultArgInstantiations.find(Param);
283   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
286 
287     // We're done tracking this parameter's instantiations.
288     UnparsedDefaultArgInstantiations.erase(InstPos);
289   }
290 
291   return false;
292 }
293 
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
297 void
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
299                                 Expr *DefaultArg) {
300   if (!param || !DefaultArg)
301     return;
302 
303   ParmVarDecl *Param = cast<ParmVarDecl>(param);
304   UnparsedDefaultArgLocs.erase(Param);
305 
306   // Default arguments are only permitted in C++
307   if (!getLangOpts().CPlusPlus) {
308     Diag(EqualLoc, diag::err_param_default_argument)
309       << DefaultArg->getSourceRange();
310     Param->setInvalidDecl();
311     return;
312   }
313 
314   // Check for unexpanded parameter packs.
315   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316     Param->setInvalidDecl();
317     return;
318   }
319 
320   // C++11 [dcl.fct.default]p3
321   //   A default argument expression [...] shall not be specified for a
322   //   parameter pack.
323   if (Param->isParameterPack()) {
324     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325         << DefaultArg->getSourceRange();
326     return;
327   }
328 
329   // Check that the default argument is well-formed
330   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331   if (DefaultArgChecker.Visit(DefaultArg)) {
332     Param->setInvalidDecl();
333     return;
334   }
335 
336   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
337 }
338 
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344                                              SourceLocation EqualLoc,
345                                              SourceLocation ArgLoc) {
346   if (!param)
347     return;
348 
349   ParmVarDecl *Param = cast<ParmVarDecl>(param);
350   Param->setUnparsedDefaultArg();
351   UnparsedDefaultArgLocs[Param] = ArgLoc;
352 }
353 
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357                                           SourceLocation EqualLoc) {
358   if (!param)
359     return;
360 
361   ParmVarDecl *Param = cast<ParmVarDecl>(param);
362   Param->setInvalidDecl();
363   UnparsedDefaultArgLocs.erase(Param);
364   Param->setDefaultArg(new(Context)
365                        OpaqueValueExpr(EqualLoc,
366                                        Param->getType().getNonReferenceType(),
367                                        VK_RValue));
368 }
369 
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376   // C++ [dcl.fct.default]p3
377   //   A default argument expression shall be specified only in the
378   //   parameter-declaration-clause of a function declaration or in a
379   //   template-parameter (14.1). It shall not be specified for a
380   //   parameter pack. If it is specified in a
381   //   parameter-declaration-clause, it shall not occur within a
382   //   declarator or abstract-declarator of a parameter-declaration.
383   bool MightBeFunction = D.isFunctionDeclarationContext();
384   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385     DeclaratorChunk &chunk = D.getTypeObject(i);
386     if (chunk.Kind == DeclaratorChunk::Function) {
387       if (MightBeFunction) {
388         // This is a function declaration. It can have default arguments, but
389         // keep looking in case its return type is a function type with default
390         // arguments.
391         MightBeFunction = false;
392         continue;
393       }
394       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
395            ++argIdx) {
396         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397         if (Param->hasUnparsedDefaultArg()) {
398           std::unique_ptr<CachedTokens> Toks =
399               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
400           SourceRange SR;
401           if (Toks->size() > 1)
402             SR = SourceRange((*Toks)[1].getLocation(),
403                              Toks->back().getLocation());
404           else
405             SR = UnparsedDefaultArgLocs[Param];
406           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
407             << SR;
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 the right previous declaration.
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   return Invalid;
662 }
663 
664 NamedDecl *
665 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
666                                    MultiTemplateParamsArg TemplateParamLists) {
667   assert(D.isDecompositionDeclarator());
668   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
669 
670   // The syntax only allows a decomposition declarator as a simple-declaration
671   // or a for-range-declaration, but we parse it in more cases than that.
672   if (!D.mayHaveDecompositionDeclarator()) {
673     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
674       << Decomp.getSourceRange();
675     return nullptr;
676   }
677 
678   if (!TemplateParamLists.empty()) {
679     // FIXME: There's no rule against this, but there are also no rules that
680     // would actually make it usable, so we reject it for now.
681     Diag(TemplateParamLists.front()->getTemplateLoc(),
682          diag::err_decomp_decl_template);
683     return nullptr;
684   }
685 
686   Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
687                                    ? diag::warn_cxx14_compat_decomp_decl
688                                    : diag::ext_decomp_decl)
689       << Decomp.getSourceRange();
690 
691   // The semantic context is always just the current context.
692   DeclContext *const DC = CurContext;
693 
694   // C++1z [dcl.dcl]/8:
695   //   The decl-specifier-seq shall contain only the type-specifier auto
696   //   and cv-qualifiers.
697   auto &DS = D.getDeclSpec();
698   {
699     SmallVector<StringRef, 8> BadSpecifiers;
700     SmallVector<SourceLocation, 8> BadSpecifierLocs;
701     if (auto SCS = DS.getStorageClassSpec()) {
702       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
703       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
704     }
705     if (auto TSCS = DS.getThreadStorageClassSpec()) {
706       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
707       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
708     }
709     if (DS.isConstexprSpecified()) {
710       BadSpecifiers.push_back("constexpr");
711       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
712     }
713     if (DS.isInlineSpecified()) {
714       BadSpecifiers.push_back("inline");
715       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
716     }
717     if (!BadSpecifiers.empty()) {
718       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
719       Err << (int)BadSpecifiers.size()
720           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
721       // Don't add FixItHints to remove the specifiers; we do still respect
722       // them when building the underlying variable.
723       for (auto Loc : BadSpecifierLocs)
724         Err << SourceRange(Loc, Loc);
725     }
726     // We can't recover from it being declared as a typedef.
727     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
728       return nullptr;
729   }
730 
731   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
732   QualType R = TInfo->getType();
733 
734   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
735                                       UPPC_DeclarationType))
736     D.setInvalidType();
737 
738   // The syntax only allows a single ref-qualifier prior to the decomposition
739   // declarator. No other declarator chunks are permitted. Also check the type
740   // specifier here.
741   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
742       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
743       (D.getNumTypeObjects() == 1 &&
744        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
745     Diag(Decomp.getLSquareLoc(),
746          (D.hasGroupingParens() ||
747           (D.getNumTypeObjects() &&
748            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
749              ? diag::err_decomp_decl_parens
750              : diag::err_decomp_decl_type)
751         << R;
752 
753     // In most cases, there's no actual problem with an explicitly-specified
754     // type, but a function type won't work here, and ActOnVariableDeclarator
755     // shouldn't be called for such a type.
756     if (R->isFunctionType())
757       D.setInvalidType();
758   }
759 
760   // Build the BindingDecls.
761   SmallVector<BindingDecl*, 8> Bindings;
762 
763   // Build the BindingDecls.
764   for (auto &B : D.getDecompositionDeclarator().bindings()) {
765     // Check for name conflicts.
766     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
767     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
768                           ForRedeclaration);
769     LookupName(Previous, S,
770                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
771 
772     // It's not permitted to shadow a template parameter name.
773     if (Previous.isSingleResult() &&
774         Previous.getFoundDecl()->isTemplateParameter()) {
775       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
776                                       Previous.getFoundDecl());
777       Previous.clear();
778     }
779 
780     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
781                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
782     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
783                          /*AllowInlineNamespace*/false);
784     if (!Previous.empty()) {
785       auto *Old = Previous.getRepresentativeDecl();
786       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
787       Diag(Old->getLocation(), diag::note_previous_definition);
788     }
789 
790     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
791     PushOnScopeChains(BD, S, true);
792     Bindings.push_back(BD);
793     ParsingInitForAutoVars.insert(BD);
794   }
795 
796   // There are no prior lookup results for the variable itself, because it
797   // is unnamed.
798   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
799                                Decomp.getLSquareLoc());
800   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
801 
802   // Build the variable that holds the non-decomposed object.
803   bool AddToScope = true;
804   NamedDecl *New =
805       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
806                               MultiTemplateParamsArg(), AddToScope, Bindings);
807   CurContext->addHiddenDecl(New);
808 
809   if (isInOpenMPDeclareTargetContext())
810     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
811 
812   return New;
813 }
814 
815 static bool checkSimpleDecomposition(
816     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
817     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
818     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
819   if ((int64_t)Bindings.size() != NumElems) {
820     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
821         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
822         << (NumElems < Bindings.size());
823     return true;
824   }
825 
826   unsigned I = 0;
827   for (auto *B : Bindings) {
828     SourceLocation Loc = B->getLocation();
829     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
830     if (E.isInvalid())
831       return true;
832     E = GetInit(Loc, E.get(), I++);
833     if (E.isInvalid())
834       return true;
835     B->setBinding(ElemType, E.get());
836   }
837 
838   return false;
839 }
840 
841 static bool checkArrayLikeDecomposition(Sema &S,
842                                         ArrayRef<BindingDecl *> Bindings,
843                                         ValueDecl *Src, QualType DecompType,
844                                         const llvm::APSInt &NumElems,
845                                         QualType ElemType) {
846   return checkSimpleDecomposition(
847       S, Bindings, Src, DecompType, NumElems, ElemType,
848       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
849         ExprResult E = S.ActOnIntegerConstant(Loc, I);
850         if (E.isInvalid())
851           return ExprError();
852         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
853       });
854 }
855 
856 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
857                                     ValueDecl *Src, QualType DecompType,
858                                     const ConstantArrayType *CAT) {
859   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
860                                      llvm::APSInt(CAT->getSize()),
861                                      CAT->getElementType());
862 }
863 
864 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
865                                      ValueDecl *Src, QualType DecompType,
866                                      const VectorType *VT) {
867   return checkArrayLikeDecomposition(
868       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
869       S.Context.getQualifiedType(VT->getElementType(),
870                                  DecompType.getQualifiers()));
871 }
872 
873 static bool checkComplexDecomposition(Sema &S,
874                                       ArrayRef<BindingDecl *> Bindings,
875                                       ValueDecl *Src, QualType DecompType,
876                                       const ComplexType *CT) {
877   return checkSimpleDecomposition(
878       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
879       S.Context.getQualifiedType(CT->getElementType(),
880                                  DecompType.getQualifiers()),
881       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
882         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
883       });
884 }
885 
886 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
887                                      TemplateArgumentListInfo &Args) {
888   SmallString<128> SS;
889   llvm::raw_svector_ostream OS(SS);
890   bool First = true;
891   for (auto &Arg : Args.arguments()) {
892     if (!First)
893       OS << ", ";
894     Arg.getArgument().print(PrintingPolicy, OS);
895     First = false;
896   }
897   return OS.str();
898 }
899 
900 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
901                                      SourceLocation Loc, StringRef Trait,
902                                      TemplateArgumentListInfo &Args,
903                                      unsigned DiagID) {
904   auto DiagnoseMissing = [&] {
905     if (DiagID)
906       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
907                                                Args);
908     return true;
909   };
910 
911   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
912   NamespaceDecl *Std = S.getStdNamespace();
913   if (!Std)
914     return DiagnoseMissing();
915 
916   // Look up the trait itself, within namespace std. We can diagnose various
917   // problems with this lookup even if we've been asked to not diagnose a
918   // missing specialization, because this can only fail if the user has been
919   // declaring their own names in namespace std or we don't support the
920   // standard library implementation in use.
921   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
922                       Loc, Sema::LookupOrdinaryName);
923   if (!S.LookupQualifiedName(Result, Std))
924     return DiagnoseMissing();
925   if (Result.isAmbiguous())
926     return true;
927 
928   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
929   if (!TraitTD) {
930     Result.suppressDiagnostics();
931     NamedDecl *Found = *Result.begin();
932     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
933     S.Diag(Found->getLocation(), diag::note_declared_at);
934     return true;
935   }
936 
937   // Build the template-id.
938   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
939   if (TraitTy.isNull())
940     return true;
941   if (!S.isCompleteType(Loc, TraitTy)) {
942     if (DiagID)
943       S.RequireCompleteType(
944           Loc, TraitTy, DiagID,
945           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
946     return true;
947   }
948 
949   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
950   assert(RD && "specialization of class template is not a class?");
951 
952   // Look up the member of the trait type.
953   S.LookupQualifiedName(TraitMemberLookup, RD);
954   return TraitMemberLookup.isAmbiguous();
955 }
956 
957 static TemplateArgumentLoc
958 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
959                                    uint64_t I) {
960   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
961   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
962 }
963 
964 static TemplateArgumentLoc
965 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
966   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
967 }
968 
969 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
970 
971 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
972                                llvm::APSInt &Size) {
973   EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
974 
975   DeclarationName Value = S.PP.getIdentifierInfo("value");
976   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
977 
978   // Form template argument list for tuple_size<T>.
979   TemplateArgumentListInfo Args(Loc, Loc);
980   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
981 
982   // If there's no tuple_size specialization, it's not tuple-like.
983   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
984     return IsTupleLike::NotTupleLike;
985 
986   // If we get this far, we've committed to the tuple interpretation, but
987   // we can still fail if there actually isn't a usable ::value.
988 
989   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
990     LookupResult &R;
991     TemplateArgumentListInfo &Args;
992     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
993         : R(R), Args(Args) {}
994     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
995       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
996           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
997     }
998   } Diagnoser(R, Args);
999 
1000   if (R.empty()) {
1001     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1002     return IsTupleLike::Error;
1003   }
1004 
1005   ExprResult E =
1006       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1007   if (E.isInvalid())
1008     return IsTupleLike::Error;
1009 
1010   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1011   if (E.isInvalid())
1012     return IsTupleLike::Error;
1013 
1014   return IsTupleLike::TupleLike;
1015 }
1016 
1017 /// \return std::tuple_element<I, T>::type.
1018 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1019                                         unsigned I, QualType T) {
1020   // Form template argument list for tuple_element<I, T>.
1021   TemplateArgumentListInfo Args(Loc, Loc);
1022   Args.addArgument(
1023       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1024   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1025 
1026   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1027   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1028   if (lookupStdTypeTraitMember(
1029           S, R, Loc, "tuple_element", Args,
1030           diag::err_decomp_decl_std_tuple_element_not_specialized))
1031     return QualType();
1032 
1033   auto *TD = R.getAsSingle<TypeDecl>();
1034   if (!TD) {
1035     R.suppressDiagnostics();
1036     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1037       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1038     if (!R.empty())
1039       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1040     return QualType();
1041   }
1042 
1043   return S.Context.getTypeDeclType(TD);
1044 }
1045 
1046 namespace {
1047 struct BindingDiagnosticTrap {
1048   Sema &S;
1049   DiagnosticErrorTrap Trap;
1050   BindingDecl *BD;
1051 
1052   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1053       : S(S), Trap(S.Diags), BD(BD) {}
1054   ~BindingDiagnosticTrap() {
1055     if (Trap.hasErrorOccurred())
1056       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1057   }
1058 };
1059 }
1060 
1061 static bool checkTupleLikeDecomposition(Sema &S,
1062                                         ArrayRef<BindingDecl *> Bindings,
1063                                         VarDecl *Src, QualType DecompType,
1064                                         const llvm::APSInt &TupleSize) {
1065   if ((int64_t)Bindings.size() != TupleSize) {
1066     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1067         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1068         << (TupleSize < Bindings.size());
1069     return true;
1070   }
1071 
1072   if (Bindings.empty())
1073     return false;
1074 
1075   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1076 
1077   // [dcl.decomp]p3:
1078   //   The unqualified-id get is looked up in the scope of E by class member
1079   //   access lookup
1080   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1081   bool UseMemberGet = false;
1082   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1083     if (auto *RD = DecompType->getAsCXXRecordDecl())
1084       S.LookupQualifiedName(MemberGet, RD);
1085     if (MemberGet.isAmbiguous())
1086       return true;
1087     UseMemberGet = !MemberGet.empty();
1088     S.FilterAcceptableTemplateNames(MemberGet);
1089   }
1090 
1091   unsigned I = 0;
1092   for (auto *B : Bindings) {
1093     BindingDiagnosticTrap Trap(S, B);
1094     SourceLocation Loc = B->getLocation();
1095 
1096     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1097     if (E.isInvalid())
1098       return true;
1099 
1100     //   e is an lvalue if the type of the entity is an lvalue reference and
1101     //   an xvalue otherwise
1102     if (!Src->getType()->isLValueReferenceType())
1103       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1104                                    E.get(), nullptr, VK_XValue);
1105 
1106     TemplateArgumentListInfo Args(Loc, Loc);
1107     Args.addArgument(
1108         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1109 
1110     if (UseMemberGet) {
1111       //   if [lookup of member get] finds at least one declaration, the
1112       //   initializer is e.get<i-1>().
1113       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1114                                      CXXScopeSpec(), SourceLocation(), nullptr,
1115                                      MemberGet, &Args, nullptr);
1116       if (E.isInvalid())
1117         return true;
1118 
1119       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1120     } else {
1121       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1122       //   in the associated namespaces.
1123       Expr *Get = UnresolvedLookupExpr::Create(
1124           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1125           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1126           UnresolvedSetIterator(), UnresolvedSetIterator());
1127 
1128       Expr *Arg = E.get();
1129       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1130     }
1131     if (E.isInvalid())
1132       return true;
1133     Expr *Init = E.get();
1134 
1135     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1136     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1137     if (T.isNull())
1138       return true;
1139 
1140     //   each vi is a variable of type "reference to T" initialized with the
1141     //   initializer, where the reference is an lvalue reference if the
1142     //   initializer is an lvalue and an rvalue reference otherwise
1143     QualType RefType =
1144         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1145     if (RefType.isNull())
1146       return true;
1147     auto *RefVD = VarDecl::Create(
1148         S.Context, Src->getDeclContext(), Loc, Loc,
1149         B->getDeclName().getAsIdentifierInfo(), RefType,
1150         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1151     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1152     RefVD->setTSCSpec(Src->getTSCSpec());
1153     RefVD->setImplicit();
1154     if (Src->isInlineSpecified())
1155       RefVD->setInlineSpecified();
1156     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1157 
1158     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1159     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1160     InitializationSequence Seq(S, Entity, Kind, Init);
1161     E = Seq.Perform(S, Entity, Kind, Init);
1162     if (E.isInvalid())
1163       return true;
1164     E = S.ActOnFinishFullExpr(E.get(), Loc);
1165     if (E.isInvalid())
1166       return true;
1167     RefVD->setInit(E.get());
1168     RefVD->checkInitIsICE();
1169 
1170     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1171                                    DeclarationNameInfo(B->getDeclName(), Loc),
1172                                    RefVD);
1173     if (E.isInvalid())
1174       return true;
1175 
1176     B->setBinding(T, E.get());
1177     I++;
1178   }
1179 
1180   return false;
1181 }
1182 
1183 /// Find the base class to decompose in a built-in decomposition of a class type.
1184 /// This base class search is, unfortunately, not quite like any other that we
1185 /// perform anywhere else in C++.
1186 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1187                                                       SourceLocation Loc,
1188                                                       const CXXRecordDecl *RD,
1189                                                       CXXCastPath &BasePath) {
1190   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1191                           CXXBasePath &Path) {
1192     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1193   };
1194 
1195   const CXXRecordDecl *ClassWithFields = nullptr;
1196   if (RD->hasDirectFields())
1197     // [dcl.decomp]p4:
1198     //   Otherwise, all of E's non-static data members shall be public direct
1199     //   members of E ...
1200     ClassWithFields = RD;
1201   else {
1202     //   ... or of ...
1203     CXXBasePaths Paths;
1204     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1205     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1206       // If no classes have fields, just decompose RD itself. (This will work
1207       // if and only if zero bindings were provided.)
1208       return RD;
1209     }
1210 
1211     CXXBasePath *BestPath = nullptr;
1212     for (auto &P : Paths) {
1213       if (!BestPath)
1214         BestPath = &P;
1215       else if (!S.Context.hasSameType(P.back().Base->getType(),
1216                                       BestPath->back().Base->getType())) {
1217         //   ... the same ...
1218         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1219           << false << RD << BestPath->back().Base->getType()
1220           << P.back().Base->getType();
1221         return nullptr;
1222       } else if (P.Access < BestPath->Access) {
1223         BestPath = &P;
1224       }
1225     }
1226 
1227     //   ... unambiguous ...
1228     QualType BaseType = BestPath->back().Base->getType();
1229     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1230       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1231         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1232       return nullptr;
1233     }
1234 
1235     //   ... public base class of E.
1236     if (BestPath->Access != AS_public) {
1237       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1238         << RD << BaseType;
1239       for (auto &BS : *BestPath) {
1240         if (BS.Base->getAccessSpecifier() != AS_public) {
1241           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1242             << (BS.Base->getAccessSpecifier() == AS_protected)
1243             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1244           break;
1245         }
1246       }
1247       return nullptr;
1248     }
1249 
1250     ClassWithFields = BaseType->getAsCXXRecordDecl();
1251     S.BuildBasePathArray(Paths, BasePath);
1252   }
1253 
1254   // The above search did not check whether the selected class itself has base
1255   // classes with fields, so check that now.
1256   CXXBasePaths Paths;
1257   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1258     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1259       << (ClassWithFields == RD) << RD << ClassWithFields
1260       << Paths.front().back().Base->getType();
1261     return nullptr;
1262   }
1263 
1264   return ClassWithFields;
1265 }
1266 
1267 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1268                                      ValueDecl *Src, QualType DecompType,
1269                                      const CXXRecordDecl *RD) {
1270   CXXCastPath BasePath;
1271   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1272   if (!RD)
1273     return true;
1274   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1275                                                  DecompType.getQualifiers());
1276 
1277   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1278     unsigned NumFields =
1279         std::count_if(RD->field_begin(), RD->field_end(),
1280                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1281     assert(Bindings.size() != NumFields);
1282     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1283         << DecompType << (unsigned)Bindings.size() << NumFields
1284         << (NumFields < Bindings.size());
1285     return true;
1286   };
1287 
1288   //   all of E's non-static data members shall be public [...] members,
1289   //   E shall not have an anonymous union member, ...
1290   unsigned I = 0;
1291   for (auto *FD : RD->fields()) {
1292     if (FD->isUnnamedBitfield())
1293       continue;
1294 
1295     if (FD->isAnonymousStructOrUnion()) {
1296       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1297         << DecompType << FD->getType()->isUnionType();
1298       S.Diag(FD->getLocation(), diag::note_declared_at);
1299       return true;
1300     }
1301 
1302     // We have a real field to bind.
1303     if (I >= Bindings.size())
1304       return DiagnoseBadNumberOfBindings();
1305     auto *B = Bindings[I++];
1306 
1307     SourceLocation Loc = B->getLocation();
1308     if (FD->getAccess() != AS_public) {
1309       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1310 
1311       // Determine whether the access specifier was explicit.
1312       bool Implicit = true;
1313       for (const auto *D : RD->decls()) {
1314         if (declaresSameEntity(D, FD))
1315           break;
1316         if (isa<AccessSpecDecl>(D)) {
1317           Implicit = false;
1318           break;
1319         }
1320       }
1321 
1322       S.Diag(FD->getLocation(), diag::note_access_natural)
1323         << (FD->getAccess() == AS_protected) << Implicit;
1324       return true;
1325     }
1326 
1327     // Initialize the binding to Src.FD.
1328     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1329     if (E.isInvalid())
1330       return true;
1331     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1332                             VK_LValue, &BasePath);
1333     if (E.isInvalid())
1334       return true;
1335     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1336                                   CXXScopeSpec(), FD,
1337                                   DeclAccessPair::make(FD, FD->getAccess()),
1338                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1339     if (E.isInvalid())
1340       return true;
1341 
1342     // If the type of the member is T, the referenced type is cv T, where cv is
1343     // the cv-qualification of the decomposition expression.
1344     //
1345     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1346     // 'const' to the type of the field.
1347     Qualifiers Q = DecompType.getQualifiers();
1348     if (FD->isMutable())
1349       Q.removeConst();
1350     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1351   }
1352 
1353   if (I != Bindings.size())
1354     return DiagnoseBadNumberOfBindings();
1355 
1356   return false;
1357 }
1358 
1359 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1360   QualType DecompType = DD->getType();
1361 
1362   // If the type of the decomposition is dependent, then so is the type of
1363   // each binding.
1364   if (DecompType->isDependentType()) {
1365     for (auto *B : DD->bindings())
1366       B->setType(Context.DependentTy);
1367     return;
1368   }
1369 
1370   DecompType = DecompType.getNonReferenceType();
1371   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1372 
1373   // C++1z [dcl.decomp]/2:
1374   //   If E is an array type [...]
1375   // As an extension, we also support decomposition of built-in complex and
1376   // vector types.
1377   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1378     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1379       DD->setInvalidDecl();
1380     return;
1381   }
1382   if (auto *VT = DecompType->getAs<VectorType>()) {
1383     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1384       DD->setInvalidDecl();
1385     return;
1386   }
1387   if (auto *CT = DecompType->getAs<ComplexType>()) {
1388     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1389       DD->setInvalidDecl();
1390     return;
1391   }
1392 
1393   // C++1z [dcl.decomp]/3:
1394   //   if the expression std::tuple_size<E>::value is a well-formed integral
1395   //   constant expression, [...]
1396   llvm::APSInt TupleSize(32);
1397   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1398   case IsTupleLike::Error:
1399     DD->setInvalidDecl();
1400     return;
1401 
1402   case IsTupleLike::TupleLike:
1403     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1404       DD->setInvalidDecl();
1405     return;
1406 
1407   case IsTupleLike::NotTupleLike:
1408     break;
1409   }
1410 
1411   // C++1z [dcl.dcl]/8:
1412   //   [E shall be of array or non-union class type]
1413   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1414   if (!RD || RD->isUnion()) {
1415     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1416         << DD << !RD << DecompType;
1417     DD->setInvalidDecl();
1418     return;
1419   }
1420 
1421   // C++1z [dcl.decomp]/4:
1422   //   all of E's non-static data members shall be [...] direct members of
1423   //   E or of the same unambiguous public base class of E, ...
1424   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1425     DD->setInvalidDecl();
1426 }
1427 
1428 /// \brief Merge the exception specifications of two variable declarations.
1429 ///
1430 /// This is called when there's a redeclaration of a VarDecl. The function
1431 /// checks if the redeclaration might have an exception specification and
1432 /// validates compatibility and merges the specs if necessary.
1433 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1434   // Shortcut if exceptions are disabled.
1435   if (!getLangOpts().CXXExceptions)
1436     return;
1437 
1438   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1439          "Should only be called if types are otherwise the same.");
1440 
1441   QualType NewType = New->getType();
1442   QualType OldType = Old->getType();
1443 
1444   // We're only interested in pointers and references to functions, as well
1445   // as pointers to member functions.
1446   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1447     NewType = R->getPointeeType();
1448     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1449   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1450     NewType = P->getPointeeType();
1451     OldType = OldType->getAs<PointerType>()->getPointeeType();
1452   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1453     NewType = M->getPointeeType();
1454     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1455   }
1456 
1457   if (!NewType->isFunctionProtoType())
1458     return;
1459 
1460   // There's lots of special cases for functions. For function pointers, system
1461   // libraries are hopefully not as broken so that we don't need these
1462   // workarounds.
1463   if (CheckEquivalentExceptionSpec(
1464         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1465         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1466     New->setInvalidDecl();
1467   }
1468 }
1469 
1470 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1471 /// function declaration are well-formed according to C++
1472 /// [dcl.fct.default].
1473 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1474   unsigned NumParams = FD->getNumParams();
1475   unsigned p;
1476 
1477   // Find first parameter with a default argument
1478   for (p = 0; p < NumParams; ++p) {
1479     ParmVarDecl *Param = FD->getParamDecl(p);
1480     if (Param->hasDefaultArg())
1481       break;
1482   }
1483 
1484   // C++11 [dcl.fct.default]p4:
1485   //   In a given function declaration, each parameter subsequent to a parameter
1486   //   with a default argument shall have a default argument supplied in this or
1487   //   a previous declaration or shall be a function parameter pack. A default
1488   //   argument shall not be redefined by a later declaration (not even to the
1489   //   same value).
1490   unsigned LastMissingDefaultArg = 0;
1491   for (; p < NumParams; ++p) {
1492     ParmVarDecl *Param = FD->getParamDecl(p);
1493     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1494       if (Param->isInvalidDecl())
1495         /* We already complained about this parameter. */;
1496       else if (Param->getIdentifier())
1497         Diag(Param->getLocation(),
1498              diag::err_param_default_argument_missing_name)
1499           << Param->getIdentifier();
1500       else
1501         Diag(Param->getLocation(),
1502              diag::err_param_default_argument_missing);
1503 
1504       LastMissingDefaultArg = p;
1505     }
1506   }
1507 
1508   if (LastMissingDefaultArg > 0) {
1509     // Some default arguments were missing. Clear out all of the
1510     // default arguments up to (and including) the last missing
1511     // default argument, so that we leave the function parameters
1512     // in a semantically valid state.
1513     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1514       ParmVarDecl *Param = FD->getParamDecl(p);
1515       if (Param->hasDefaultArg()) {
1516         Param->setDefaultArg(nullptr);
1517       }
1518     }
1519   }
1520 }
1521 
1522 // CheckConstexprParameterTypes - Check whether a function's parameter types
1523 // are all literal types. If so, return true. If not, produce a suitable
1524 // diagnostic and return false.
1525 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1526                                          const FunctionDecl *FD) {
1527   unsigned ArgIndex = 0;
1528   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1529   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1530                                               e = FT->param_type_end();
1531        i != e; ++i, ++ArgIndex) {
1532     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1533     SourceLocation ParamLoc = PD->getLocation();
1534     if (!(*i)->isDependentType() &&
1535         SemaRef.RequireLiteralType(ParamLoc, *i,
1536                                    diag::err_constexpr_non_literal_param,
1537                                    ArgIndex+1, PD->getSourceRange(),
1538                                    isa<CXXConstructorDecl>(FD)))
1539       return false;
1540   }
1541   return true;
1542 }
1543 
1544 /// \brief Get diagnostic %select index for tag kind for
1545 /// record diagnostic message.
1546 /// WARNING: Indexes apply to particular diagnostics only!
1547 ///
1548 /// \returns diagnostic %select index.
1549 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1550   switch (Tag) {
1551   case TTK_Struct: return 0;
1552   case TTK_Interface: return 1;
1553   case TTK_Class:  return 2;
1554   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1555   }
1556 }
1557 
1558 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1559 // the requirements of a constexpr function definition or a constexpr
1560 // constructor definition. If so, return true. If not, produce appropriate
1561 // diagnostics and return false.
1562 //
1563 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1564 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1565   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1566   if (MD && MD->isInstance()) {
1567     // C++11 [dcl.constexpr]p4:
1568     //  The definition of a constexpr constructor shall satisfy the following
1569     //  constraints:
1570     //  - the class shall not have any virtual base classes;
1571     const CXXRecordDecl *RD = MD->getParent();
1572     if (RD->getNumVBases()) {
1573       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1574         << isa<CXXConstructorDecl>(NewFD)
1575         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1576       for (const auto &I : RD->vbases())
1577         Diag(I.getLocStart(),
1578              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1579       return false;
1580     }
1581   }
1582 
1583   if (!isa<CXXConstructorDecl>(NewFD)) {
1584     // C++11 [dcl.constexpr]p3:
1585     //  The definition of a constexpr function shall satisfy the following
1586     //  constraints:
1587     // - it shall not be virtual;
1588     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1589     if (Method && Method->isVirtual()) {
1590       Method = Method->getCanonicalDecl();
1591       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1592 
1593       // If it's not obvious why this function is virtual, find an overridden
1594       // function which uses the 'virtual' keyword.
1595       const CXXMethodDecl *WrittenVirtual = Method;
1596       while (!WrittenVirtual->isVirtualAsWritten())
1597         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1598       if (WrittenVirtual != Method)
1599         Diag(WrittenVirtual->getLocation(),
1600              diag::note_overridden_virtual_function);
1601       return false;
1602     }
1603 
1604     // - its return type shall be a literal type;
1605     QualType RT = NewFD->getReturnType();
1606     if (!RT->isDependentType() &&
1607         RequireLiteralType(NewFD->getLocation(), RT,
1608                            diag::err_constexpr_non_literal_return))
1609       return false;
1610   }
1611 
1612   // - each of its parameter types shall be a literal type;
1613   if (!CheckConstexprParameterTypes(*this, NewFD))
1614     return false;
1615 
1616   return true;
1617 }
1618 
1619 /// Check the given declaration statement is legal within a constexpr function
1620 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1621 ///
1622 /// \return true if the body is OK (maybe only as an extension), false if we
1623 ///         have diagnosed a problem.
1624 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1625                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1626   // C++11 [dcl.constexpr]p3 and p4:
1627   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1628   //  contain only
1629   for (const auto *DclIt : DS->decls()) {
1630     switch (DclIt->getKind()) {
1631     case Decl::StaticAssert:
1632     case Decl::Using:
1633     case Decl::UsingShadow:
1634     case Decl::UsingDirective:
1635     case Decl::UnresolvedUsingTypename:
1636     case Decl::UnresolvedUsingValue:
1637       //   - static_assert-declarations
1638       //   - using-declarations,
1639       //   - using-directives,
1640       continue;
1641 
1642     case Decl::Typedef:
1643     case Decl::TypeAlias: {
1644       //   - typedef declarations and alias-declarations that do not define
1645       //     classes or enumerations,
1646       const auto *TN = cast<TypedefNameDecl>(DclIt);
1647       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1648         // Don't allow variably-modified types in constexpr functions.
1649         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1650         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1651           << TL.getSourceRange() << TL.getType()
1652           << isa<CXXConstructorDecl>(Dcl);
1653         return false;
1654       }
1655       continue;
1656     }
1657 
1658     case Decl::Enum:
1659     case Decl::CXXRecord:
1660       // C++1y allows types to be defined, not just declared.
1661       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1662         SemaRef.Diag(DS->getLocStart(),
1663                      SemaRef.getLangOpts().CPlusPlus14
1664                        ? diag::warn_cxx11_compat_constexpr_type_definition
1665                        : diag::ext_constexpr_type_definition)
1666           << isa<CXXConstructorDecl>(Dcl);
1667       continue;
1668 
1669     case Decl::EnumConstant:
1670     case Decl::IndirectField:
1671     case Decl::ParmVar:
1672       // These can only appear with other declarations which are banned in
1673       // C++11 and permitted in C++1y, so ignore them.
1674       continue;
1675 
1676     case Decl::Var:
1677     case Decl::Decomposition: {
1678       // C++1y [dcl.constexpr]p3 allows anything except:
1679       //   a definition of a variable of non-literal type or of static or
1680       //   thread storage duration or for which no initialization is performed.
1681       const auto *VD = cast<VarDecl>(DclIt);
1682       if (VD->isThisDeclarationADefinition()) {
1683         if (VD->isStaticLocal()) {
1684           SemaRef.Diag(VD->getLocation(),
1685                        diag::err_constexpr_local_var_static)
1686             << isa<CXXConstructorDecl>(Dcl)
1687             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1688           return false;
1689         }
1690         if (!VD->getType()->isDependentType() &&
1691             SemaRef.RequireLiteralType(
1692               VD->getLocation(), VD->getType(),
1693               diag::err_constexpr_local_var_non_literal_type,
1694               isa<CXXConstructorDecl>(Dcl)))
1695           return false;
1696         if (!VD->getType()->isDependentType() &&
1697             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1698           SemaRef.Diag(VD->getLocation(),
1699                        diag::err_constexpr_local_var_no_init)
1700             << isa<CXXConstructorDecl>(Dcl);
1701           return false;
1702         }
1703       }
1704       SemaRef.Diag(VD->getLocation(),
1705                    SemaRef.getLangOpts().CPlusPlus14
1706                     ? diag::warn_cxx11_compat_constexpr_local_var
1707                     : diag::ext_constexpr_local_var)
1708         << isa<CXXConstructorDecl>(Dcl);
1709       continue;
1710     }
1711 
1712     case Decl::NamespaceAlias:
1713     case Decl::Function:
1714       // These are disallowed in C++11 and permitted in C++1y. Allow them
1715       // everywhere as an extension.
1716       if (!Cxx1yLoc.isValid())
1717         Cxx1yLoc = DS->getLocStart();
1718       continue;
1719 
1720     default:
1721       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1722         << isa<CXXConstructorDecl>(Dcl);
1723       return false;
1724     }
1725   }
1726 
1727   return true;
1728 }
1729 
1730 /// Check that the given field is initialized within a constexpr constructor.
1731 ///
1732 /// \param Dcl The constexpr constructor being checked.
1733 /// \param Field The field being checked. This may be a member of an anonymous
1734 ///        struct or union nested within the class being checked.
1735 /// \param Inits All declarations, including anonymous struct/union members and
1736 ///        indirect members, for which any initialization was provided.
1737 /// \param Diagnosed Set to true if an error is produced.
1738 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1739                                           const FunctionDecl *Dcl,
1740                                           FieldDecl *Field,
1741                                           llvm::SmallSet<Decl*, 16> &Inits,
1742                                           bool &Diagnosed) {
1743   if (Field->isInvalidDecl())
1744     return;
1745 
1746   if (Field->isUnnamedBitfield())
1747     return;
1748 
1749   // Anonymous unions with no variant members and empty anonymous structs do not
1750   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1751   // indirect fields don't need initializing.
1752   if (Field->isAnonymousStructOrUnion() &&
1753       (Field->getType()->isUnionType()
1754            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1755            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1756     return;
1757 
1758   if (!Inits.count(Field)) {
1759     if (!Diagnosed) {
1760       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1761       Diagnosed = true;
1762     }
1763     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1764   } else if (Field->isAnonymousStructOrUnion()) {
1765     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1766     for (auto *I : RD->fields())
1767       // If an anonymous union contains an anonymous struct of which any member
1768       // is initialized, all members must be initialized.
1769       if (!RD->isUnion() || Inits.count(I))
1770         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1771   }
1772 }
1773 
1774 /// Check the provided statement is allowed in a constexpr function
1775 /// definition.
1776 static bool
1777 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1778                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1779                            SourceLocation &Cxx1yLoc) {
1780   // - its function-body shall be [...] a compound-statement that contains only
1781   switch (S->getStmtClass()) {
1782   case Stmt::NullStmtClass:
1783     //   - null statements,
1784     return true;
1785 
1786   case Stmt::DeclStmtClass:
1787     //   - static_assert-declarations
1788     //   - using-declarations,
1789     //   - using-directives,
1790     //   - typedef declarations and alias-declarations that do not define
1791     //     classes or enumerations,
1792     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1793       return false;
1794     return true;
1795 
1796   case Stmt::ReturnStmtClass:
1797     //   - and exactly one return statement;
1798     if (isa<CXXConstructorDecl>(Dcl)) {
1799       // C++1y allows return statements in constexpr constructors.
1800       if (!Cxx1yLoc.isValid())
1801         Cxx1yLoc = S->getLocStart();
1802       return true;
1803     }
1804 
1805     ReturnStmts.push_back(S->getLocStart());
1806     return true;
1807 
1808   case Stmt::CompoundStmtClass: {
1809     // C++1y allows compound-statements.
1810     if (!Cxx1yLoc.isValid())
1811       Cxx1yLoc = S->getLocStart();
1812 
1813     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1814     for (auto *BodyIt : CompStmt->body()) {
1815       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1816                                       Cxx1yLoc))
1817         return false;
1818     }
1819     return true;
1820   }
1821 
1822   case Stmt::AttributedStmtClass:
1823     if (!Cxx1yLoc.isValid())
1824       Cxx1yLoc = S->getLocStart();
1825     return true;
1826 
1827   case Stmt::IfStmtClass: {
1828     // C++1y allows if-statements.
1829     if (!Cxx1yLoc.isValid())
1830       Cxx1yLoc = S->getLocStart();
1831 
1832     IfStmt *If = cast<IfStmt>(S);
1833     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1834                                     Cxx1yLoc))
1835       return false;
1836     if (If->getElse() &&
1837         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1838                                     Cxx1yLoc))
1839       return false;
1840     return true;
1841   }
1842 
1843   case Stmt::WhileStmtClass:
1844   case Stmt::DoStmtClass:
1845   case Stmt::ForStmtClass:
1846   case Stmt::CXXForRangeStmtClass:
1847   case Stmt::ContinueStmtClass:
1848     // C++1y allows all of these. We don't allow them as extensions in C++11,
1849     // because they don't make sense without variable mutation.
1850     if (!SemaRef.getLangOpts().CPlusPlus14)
1851       break;
1852     if (!Cxx1yLoc.isValid())
1853       Cxx1yLoc = S->getLocStart();
1854     for (Stmt *SubStmt : S->children())
1855       if (SubStmt &&
1856           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1857                                       Cxx1yLoc))
1858         return false;
1859     return true;
1860 
1861   case Stmt::SwitchStmtClass:
1862   case Stmt::CaseStmtClass:
1863   case Stmt::DefaultStmtClass:
1864   case Stmt::BreakStmtClass:
1865     // C++1y allows switch-statements, and since they don't need variable
1866     // mutation, we can reasonably allow them in C++11 as an extension.
1867     if (!Cxx1yLoc.isValid())
1868       Cxx1yLoc = S->getLocStart();
1869     for (Stmt *SubStmt : S->children())
1870       if (SubStmt &&
1871           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1872                                       Cxx1yLoc))
1873         return false;
1874     return true;
1875 
1876   default:
1877     if (!isa<Expr>(S))
1878       break;
1879 
1880     // C++1y allows expression-statements.
1881     if (!Cxx1yLoc.isValid())
1882       Cxx1yLoc = S->getLocStart();
1883     return true;
1884   }
1885 
1886   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1887     << isa<CXXConstructorDecl>(Dcl);
1888   return false;
1889 }
1890 
1891 /// Check the body for the given constexpr function declaration only contains
1892 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1893 ///
1894 /// \return true if the body is OK, false if we have diagnosed a problem.
1895 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1896   if (isa<CXXTryStmt>(Body)) {
1897     // C++11 [dcl.constexpr]p3:
1898     //  The definition of a constexpr function shall satisfy the following
1899     //  constraints: [...]
1900     // - its function-body shall be = delete, = default, or a
1901     //   compound-statement
1902     //
1903     // C++11 [dcl.constexpr]p4:
1904     //  In the definition of a constexpr constructor, [...]
1905     // - its function-body shall not be a function-try-block;
1906     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1907       << isa<CXXConstructorDecl>(Dcl);
1908     return false;
1909   }
1910 
1911   SmallVector<SourceLocation, 4> ReturnStmts;
1912 
1913   // - its function-body shall be [...] a compound-statement that contains only
1914   //   [... list of cases ...]
1915   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1916   SourceLocation Cxx1yLoc;
1917   for (auto *BodyIt : CompBody->body()) {
1918     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1919       return false;
1920   }
1921 
1922   if (Cxx1yLoc.isValid())
1923     Diag(Cxx1yLoc,
1924          getLangOpts().CPlusPlus14
1925            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1926            : diag::ext_constexpr_body_invalid_stmt)
1927       << isa<CXXConstructorDecl>(Dcl);
1928 
1929   if (const CXXConstructorDecl *Constructor
1930         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1931     const CXXRecordDecl *RD = Constructor->getParent();
1932     // DR1359:
1933     // - every non-variant non-static data member and base class sub-object
1934     //   shall be initialized;
1935     // DR1460:
1936     // - if the class is a union having variant members, exactly one of them
1937     //   shall be initialized;
1938     if (RD->isUnion()) {
1939       if (Constructor->getNumCtorInitializers() == 0 &&
1940           RD->hasVariantMembers()) {
1941         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1942         return false;
1943       }
1944     } else if (!Constructor->isDependentContext() &&
1945                !Constructor->isDelegatingConstructor()) {
1946       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1947 
1948       // Skip detailed checking if we have enough initializers, and we would
1949       // allow at most one initializer per member.
1950       bool AnyAnonStructUnionMembers = false;
1951       unsigned Fields = 0;
1952       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1953            E = RD->field_end(); I != E; ++I, ++Fields) {
1954         if (I->isAnonymousStructOrUnion()) {
1955           AnyAnonStructUnionMembers = true;
1956           break;
1957         }
1958       }
1959       // DR1460:
1960       // - if the class is a union-like class, but is not a union, for each of
1961       //   its anonymous union members having variant members, exactly one of
1962       //   them shall be initialized;
1963       if (AnyAnonStructUnionMembers ||
1964           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1965         // Check initialization of non-static data members. Base classes are
1966         // always initialized so do not need to be checked. Dependent bases
1967         // might not have initializers in the member initializer list.
1968         llvm::SmallSet<Decl*, 16> Inits;
1969         for (const auto *I: Constructor->inits()) {
1970           if (FieldDecl *FD = I->getMember())
1971             Inits.insert(FD);
1972           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1973             Inits.insert(ID->chain_begin(), ID->chain_end());
1974         }
1975 
1976         bool Diagnosed = false;
1977         for (auto *I : RD->fields())
1978           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1979         if (Diagnosed)
1980           return false;
1981       }
1982     }
1983   } else {
1984     if (ReturnStmts.empty()) {
1985       // C++1y doesn't require constexpr functions to contain a 'return'
1986       // statement. We still do, unless the return type might be void, because
1987       // otherwise if there's no return statement, the function cannot
1988       // be used in a core constant expression.
1989       bool OK = getLangOpts().CPlusPlus14 &&
1990                 (Dcl->getReturnType()->isVoidType() ||
1991                  Dcl->getReturnType()->isDependentType());
1992       Diag(Dcl->getLocation(),
1993            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1994               : diag::err_constexpr_body_no_return);
1995       if (!OK)
1996         return false;
1997     } else if (ReturnStmts.size() > 1) {
1998       Diag(ReturnStmts.back(),
1999            getLangOpts().CPlusPlus14
2000              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2001              : diag::ext_constexpr_body_multiple_return);
2002       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2003         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2004     }
2005   }
2006 
2007   // C++11 [dcl.constexpr]p5:
2008   //   if no function argument values exist such that the function invocation
2009   //   substitution would produce a constant expression, the program is
2010   //   ill-formed; no diagnostic required.
2011   // C++11 [dcl.constexpr]p3:
2012   //   - every constructor call and implicit conversion used in initializing the
2013   //     return value shall be one of those allowed in a constant expression.
2014   // C++11 [dcl.constexpr]p4:
2015   //   - every constructor involved in initializing non-static data members and
2016   //     base class sub-objects shall be a constexpr constructor.
2017   SmallVector<PartialDiagnosticAt, 8> Diags;
2018   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2019     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2020       << isa<CXXConstructorDecl>(Dcl);
2021     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2022       Diag(Diags[I].first, Diags[I].second);
2023     // Don't return false here: we allow this for compatibility in
2024     // system headers.
2025   }
2026 
2027   return true;
2028 }
2029 
2030 /// isCurrentClassName - Determine whether the identifier II is the
2031 /// name of the class type currently being defined. In the case of
2032 /// nested classes, this will only return true if II is the name of
2033 /// the innermost class.
2034 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2035                               const CXXScopeSpec *SS) {
2036   assert(getLangOpts().CPlusPlus && "No class names in C!");
2037 
2038   CXXRecordDecl *CurDecl;
2039   if (SS && SS->isSet() && !SS->isInvalid()) {
2040     DeclContext *DC = computeDeclContext(*SS, true);
2041     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2042   } else
2043     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2044 
2045   if (CurDecl && CurDecl->getIdentifier())
2046     return &II == CurDecl->getIdentifier();
2047   return false;
2048 }
2049 
2050 /// \brief Determine whether the identifier II is a typo for the name of
2051 /// the class type currently being defined. If so, update it to the identifier
2052 /// that should have been used.
2053 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2054   assert(getLangOpts().CPlusPlus && "No class names in C!");
2055 
2056   if (!getLangOpts().SpellChecking)
2057     return false;
2058 
2059   CXXRecordDecl *CurDecl;
2060   if (SS && SS->isSet() && !SS->isInvalid()) {
2061     DeclContext *DC = computeDeclContext(*SS, true);
2062     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2063   } else
2064     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2065 
2066   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2067       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2068           < II->getLength()) {
2069     II = CurDecl->getIdentifier();
2070     return true;
2071   }
2072 
2073   return false;
2074 }
2075 
2076 /// \brief Determine whether the given class is a base class of the given
2077 /// class, including looking at dependent bases.
2078 static bool findCircularInheritance(const CXXRecordDecl *Class,
2079                                     const CXXRecordDecl *Current) {
2080   SmallVector<const CXXRecordDecl*, 8> Queue;
2081 
2082   Class = Class->getCanonicalDecl();
2083   while (true) {
2084     for (const auto &I : Current->bases()) {
2085       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2086       if (!Base)
2087         continue;
2088 
2089       Base = Base->getDefinition();
2090       if (!Base)
2091         continue;
2092 
2093       if (Base->getCanonicalDecl() == Class)
2094         return true;
2095 
2096       Queue.push_back(Base);
2097     }
2098 
2099     if (Queue.empty())
2100       return false;
2101 
2102     Current = Queue.pop_back_val();
2103   }
2104 
2105   return false;
2106 }
2107 
2108 /// \brief Check the validity of a C++ base class specifier.
2109 ///
2110 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2111 /// and returns NULL otherwise.
2112 CXXBaseSpecifier *
2113 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2114                          SourceRange SpecifierRange,
2115                          bool Virtual, AccessSpecifier Access,
2116                          TypeSourceInfo *TInfo,
2117                          SourceLocation EllipsisLoc) {
2118   QualType BaseType = TInfo->getType();
2119 
2120   // C++ [class.union]p1:
2121   //   A union shall not have base classes.
2122   if (Class->isUnion()) {
2123     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2124       << SpecifierRange;
2125     return nullptr;
2126   }
2127 
2128   if (EllipsisLoc.isValid() &&
2129       !TInfo->getType()->containsUnexpandedParameterPack()) {
2130     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2131       << TInfo->getTypeLoc().getSourceRange();
2132     EllipsisLoc = SourceLocation();
2133   }
2134 
2135   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2136 
2137   if (BaseType->isDependentType()) {
2138     // Make sure that we don't have circular inheritance among our dependent
2139     // bases. For non-dependent bases, the check for completeness below handles
2140     // this.
2141     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2142       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2143           ((BaseDecl = BaseDecl->getDefinition()) &&
2144            findCircularInheritance(Class, BaseDecl))) {
2145         Diag(BaseLoc, diag::err_circular_inheritance)
2146           << BaseType << Context.getTypeDeclType(Class);
2147 
2148         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2149           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2150             << BaseType;
2151 
2152         return nullptr;
2153       }
2154     }
2155 
2156     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2157                                           Class->getTagKind() == TTK_Class,
2158                                           Access, TInfo, EllipsisLoc);
2159   }
2160 
2161   // Base specifiers must be record types.
2162   if (!BaseType->isRecordType()) {
2163     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2164     return nullptr;
2165   }
2166 
2167   // C++ [class.union]p1:
2168   //   A union shall not be used as a base class.
2169   if (BaseType->isUnionType()) {
2170     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2171     return nullptr;
2172   }
2173 
2174   // For the MS ABI, propagate DLL attributes to base class templates.
2175   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2176     if (Attr *ClassAttr = getDLLAttr(Class)) {
2177       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2178               BaseType->getAsCXXRecordDecl())) {
2179         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2180                                             BaseLoc);
2181       }
2182     }
2183   }
2184 
2185   // C++ [class.derived]p2:
2186   //   The class-name in a base-specifier shall not be an incompletely
2187   //   defined class.
2188   if (RequireCompleteType(BaseLoc, BaseType,
2189                           diag::err_incomplete_base_class, SpecifierRange)) {
2190     Class->setInvalidDecl();
2191     return nullptr;
2192   }
2193 
2194   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2195   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2196   assert(BaseDecl && "Record type has no declaration");
2197   BaseDecl = BaseDecl->getDefinition();
2198   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2199   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2200   assert(CXXBaseDecl && "Base type is not a C++ type");
2201 
2202   // A class which contains a flexible array member is not suitable for use as a
2203   // base class:
2204   //   - If the layout determines that a base comes before another base,
2205   //     the flexible array member would index into the subsequent base.
2206   //   - If the layout determines that base comes before the derived class,
2207   //     the flexible array member would index into the derived class.
2208   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2209     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2210       << CXXBaseDecl->getDeclName();
2211     return nullptr;
2212   }
2213 
2214   // C++ [class]p3:
2215   //   If a class is marked final and it appears as a base-type-specifier in
2216   //   base-clause, the program is ill-formed.
2217   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2218     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2219       << CXXBaseDecl->getDeclName()
2220       << FA->isSpelledAsSealed();
2221     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2222         << CXXBaseDecl->getDeclName() << FA->getRange();
2223     return nullptr;
2224   }
2225 
2226   if (BaseDecl->isInvalidDecl())
2227     Class->setInvalidDecl();
2228 
2229   // Create the base specifier.
2230   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2231                                         Class->getTagKind() == TTK_Class,
2232                                         Access, TInfo, EllipsisLoc);
2233 }
2234 
2235 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2236 /// one entry in the base class list of a class specifier, for
2237 /// example:
2238 ///    class foo : public bar, virtual private baz {
2239 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2240 BaseResult
2241 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2242                          ParsedAttributes &Attributes,
2243                          bool Virtual, AccessSpecifier Access,
2244                          ParsedType basetype, SourceLocation BaseLoc,
2245                          SourceLocation EllipsisLoc) {
2246   if (!classdecl)
2247     return true;
2248 
2249   AdjustDeclIfTemplate(classdecl);
2250   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2251   if (!Class)
2252     return true;
2253 
2254   // We haven't yet attached the base specifiers.
2255   Class->setIsParsingBaseSpecifiers();
2256 
2257   // We do not support any C++11 attributes on base-specifiers yet.
2258   // Diagnose any attributes we see.
2259   if (!Attributes.empty()) {
2260     for (AttributeList *Attr = Attributes.getList(); Attr;
2261          Attr = Attr->getNext()) {
2262       if (Attr->isInvalid() ||
2263           Attr->getKind() == AttributeList::IgnoredAttribute)
2264         continue;
2265       Diag(Attr->getLoc(),
2266            Attr->getKind() == AttributeList::UnknownAttribute
2267              ? diag::warn_unknown_attribute_ignored
2268              : diag::err_base_specifier_attribute)
2269         << Attr->getName();
2270     }
2271   }
2272 
2273   TypeSourceInfo *TInfo = nullptr;
2274   GetTypeFromParser(basetype, &TInfo);
2275 
2276   if (EllipsisLoc.isInvalid() &&
2277       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2278                                       UPPC_BaseType))
2279     return true;
2280 
2281   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2282                                                       Virtual, Access, TInfo,
2283                                                       EllipsisLoc))
2284     return BaseSpec;
2285   else
2286     Class->setInvalidDecl();
2287 
2288   return true;
2289 }
2290 
2291 /// Use small set to collect indirect bases.  As this is only used
2292 /// locally, there's no need to abstract the small size parameter.
2293 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2294 
2295 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2296 static void
2297 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2298                   const QualType &Type)
2299 {
2300   // Even though the incoming type is a base, it might not be
2301   // a class -- it could be a template parm, for instance.
2302   if (auto Rec = Type->getAs<RecordType>()) {
2303     auto Decl = Rec->getAsCXXRecordDecl();
2304 
2305     // Iterate over its bases.
2306     for (const auto &BaseSpec : Decl->bases()) {
2307       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2308         .getUnqualifiedType();
2309       if (Set.insert(Base).second)
2310         // If we've not already seen it, recurse.
2311         NoteIndirectBases(Context, Set, Base);
2312     }
2313   }
2314 }
2315 
2316 /// \brief Performs the actual work of attaching the given base class
2317 /// specifiers to a C++ class.
2318 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2319                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2320  if (Bases.empty())
2321     return false;
2322 
2323   // Used to keep track of which base types we have already seen, so
2324   // that we can properly diagnose redundant direct base types. Note
2325   // that the key is always the unqualified canonical type of the base
2326   // class.
2327   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2328 
2329   // Used to track indirect bases so we can see if a direct base is
2330   // ambiguous.
2331   IndirectBaseSet IndirectBaseTypes;
2332 
2333   // Copy non-redundant base specifiers into permanent storage.
2334   unsigned NumGoodBases = 0;
2335   bool Invalid = false;
2336   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2337     QualType NewBaseType
2338       = Context.getCanonicalType(Bases[idx]->getType());
2339     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2340 
2341     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2342     if (KnownBase) {
2343       // C++ [class.mi]p3:
2344       //   A class shall not be specified as a direct base class of a
2345       //   derived class more than once.
2346       Diag(Bases[idx]->getLocStart(),
2347            diag::err_duplicate_base_class)
2348         << KnownBase->getType()
2349         << Bases[idx]->getSourceRange();
2350 
2351       // Delete the duplicate base class specifier; we're going to
2352       // overwrite its pointer later.
2353       Context.Deallocate(Bases[idx]);
2354 
2355       Invalid = true;
2356     } else {
2357       // Okay, add this new base class.
2358       KnownBase = Bases[idx];
2359       Bases[NumGoodBases++] = Bases[idx];
2360 
2361       // Note this base's direct & indirect bases, if there could be ambiguity.
2362       if (Bases.size() > 1)
2363         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2364 
2365       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2366         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2367         if (Class->isInterface() &&
2368               (!RD->isInterface() ||
2369                KnownBase->getAccessSpecifier() != AS_public)) {
2370           // The Microsoft extension __interface does not permit bases that
2371           // are not themselves public interfaces.
2372           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2373             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2374             << RD->getSourceRange();
2375           Invalid = true;
2376         }
2377         if (RD->hasAttr<WeakAttr>())
2378           Class->addAttr(WeakAttr::CreateImplicit(Context));
2379       }
2380     }
2381   }
2382 
2383   // Attach the remaining base class specifiers to the derived class.
2384   Class->setBases(Bases.data(), NumGoodBases);
2385 
2386   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2387     // Check whether this direct base is inaccessible due to ambiguity.
2388     QualType BaseType = Bases[idx]->getType();
2389     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2390       .getUnqualifiedType();
2391 
2392     if (IndirectBaseTypes.count(CanonicalBase)) {
2393       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2394                          /*DetectVirtual=*/true);
2395       bool found
2396         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2397       assert(found);
2398       (void)found;
2399 
2400       if (Paths.isAmbiguous(CanonicalBase))
2401         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2402           << BaseType << getAmbiguousPathsDisplayString(Paths)
2403           << Bases[idx]->getSourceRange();
2404       else
2405         assert(Bases[idx]->isVirtual());
2406     }
2407 
2408     // Delete the base class specifier, since its data has been copied
2409     // into the CXXRecordDecl.
2410     Context.Deallocate(Bases[idx]);
2411   }
2412 
2413   return Invalid;
2414 }
2415 
2416 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2417 /// class, after checking whether there are any duplicate base
2418 /// classes.
2419 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2420                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2421   if (!ClassDecl || Bases.empty())
2422     return;
2423 
2424   AdjustDeclIfTemplate(ClassDecl);
2425   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2426 }
2427 
2428 /// \brief Determine whether the type \p Derived is a C++ class that is
2429 /// derived from the type \p Base.
2430 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2431   if (!getLangOpts().CPlusPlus)
2432     return false;
2433 
2434   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2435   if (!DerivedRD)
2436     return false;
2437 
2438   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2439   if (!BaseRD)
2440     return false;
2441 
2442   // If either the base or the derived type is invalid, don't try to
2443   // check whether one is derived from the other.
2444   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2445     return false;
2446 
2447   // FIXME: In a modules build, do we need the entire path to be visible for us
2448   // to be able to use the inheritance relationship?
2449   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2450     return false;
2451 
2452   return DerivedRD->isDerivedFrom(BaseRD);
2453 }
2454 
2455 /// \brief Determine whether the type \p Derived is a C++ class that is
2456 /// derived from the type \p Base.
2457 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2458                          CXXBasePaths &Paths) {
2459   if (!getLangOpts().CPlusPlus)
2460     return false;
2461 
2462   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2463   if (!DerivedRD)
2464     return false;
2465 
2466   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2467   if (!BaseRD)
2468     return false;
2469 
2470   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2471     return false;
2472 
2473   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2474 }
2475 
2476 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2477                               CXXCastPath &BasePathArray) {
2478   assert(BasePathArray.empty() && "Base path array must be empty!");
2479   assert(Paths.isRecordingPaths() && "Must record paths!");
2480 
2481   const CXXBasePath &Path = Paths.front();
2482 
2483   // We first go backward and check if we have a virtual base.
2484   // FIXME: It would be better if CXXBasePath had the base specifier for
2485   // the nearest virtual base.
2486   unsigned Start = 0;
2487   for (unsigned I = Path.size(); I != 0; --I) {
2488     if (Path[I - 1].Base->isVirtual()) {
2489       Start = I - 1;
2490       break;
2491     }
2492   }
2493 
2494   // Now add all bases.
2495   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2496     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2497 }
2498 
2499 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2500 /// conversion (where Derived and Base are class types) is
2501 /// well-formed, meaning that the conversion is unambiguous (and
2502 /// that all of the base classes are accessible). Returns true
2503 /// and emits a diagnostic if the code is ill-formed, returns false
2504 /// otherwise. Loc is the location where this routine should point to
2505 /// if there is an error, and Range is the source range to highlight
2506 /// if there is an error.
2507 ///
2508 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2509 /// diagnostic for the respective type of error will be suppressed, but the
2510 /// check for ill-formed code will still be performed.
2511 bool
2512 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2513                                    unsigned InaccessibleBaseID,
2514                                    unsigned AmbigiousBaseConvID,
2515                                    SourceLocation Loc, SourceRange Range,
2516                                    DeclarationName Name,
2517                                    CXXCastPath *BasePath,
2518                                    bool IgnoreAccess) {
2519   // First, determine whether the path from Derived to Base is
2520   // ambiguous. This is slightly more expensive than checking whether
2521   // the Derived to Base conversion exists, because here we need to
2522   // explore multiple paths to determine if there is an ambiguity.
2523   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2524                      /*DetectVirtual=*/false);
2525   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2526   assert(DerivationOkay &&
2527          "Can only be used with a derived-to-base conversion");
2528   (void)DerivationOkay;
2529 
2530   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2531     if (!IgnoreAccess) {
2532       // Check that the base class can be accessed.
2533       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2534                                    InaccessibleBaseID)) {
2535         case AR_inaccessible:
2536           return true;
2537         case AR_accessible:
2538         case AR_dependent:
2539         case AR_delayed:
2540           break;
2541       }
2542     }
2543 
2544     // Build a base path if necessary.
2545     if (BasePath)
2546       BuildBasePathArray(Paths, *BasePath);
2547     return false;
2548   }
2549 
2550   if (AmbigiousBaseConvID) {
2551     // We know that the derived-to-base conversion is ambiguous, and
2552     // we're going to produce a diagnostic. Perform the derived-to-base
2553     // search just one more time to compute all of the possible paths so
2554     // that we can print them out. This is more expensive than any of
2555     // the previous derived-to-base checks we've done, but at this point
2556     // performance isn't as much of an issue.
2557     Paths.clear();
2558     Paths.setRecordingPaths(true);
2559     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2560     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2561     (void)StillOkay;
2562 
2563     // Build up a textual representation of the ambiguous paths, e.g.,
2564     // D -> B -> A, that will be used to illustrate the ambiguous
2565     // conversions in the diagnostic. We only print one of the paths
2566     // to each base class subobject.
2567     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2568 
2569     Diag(Loc, AmbigiousBaseConvID)
2570     << Derived << Base << PathDisplayStr << Range << Name;
2571   }
2572   return true;
2573 }
2574 
2575 bool
2576 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2577                                    SourceLocation Loc, SourceRange Range,
2578                                    CXXCastPath *BasePath,
2579                                    bool IgnoreAccess) {
2580   return CheckDerivedToBaseConversion(
2581       Derived, Base, diag::err_upcast_to_inaccessible_base,
2582       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2583       BasePath, IgnoreAccess);
2584 }
2585 
2586 
2587 /// @brief Builds a string representing ambiguous paths from a
2588 /// specific derived class to different subobjects of the same base
2589 /// class.
2590 ///
2591 /// This function builds a string that can be used in error messages
2592 /// to show the different paths that one can take through the
2593 /// inheritance hierarchy to go from the derived class to different
2594 /// subobjects of a base class. The result looks something like this:
2595 /// @code
2596 /// struct D -> struct B -> struct A
2597 /// struct D -> struct C -> struct A
2598 /// @endcode
2599 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2600   std::string PathDisplayStr;
2601   std::set<unsigned> DisplayedPaths;
2602   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2603        Path != Paths.end(); ++Path) {
2604     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2605       // We haven't displayed a path to this particular base
2606       // class subobject yet.
2607       PathDisplayStr += "\n    ";
2608       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2609       for (CXXBasePath::const_iterator Element = Path->begin();
2610            Element != Path->end(); ++Element)
2611         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2612     }
2613   }
2614 
2615   return PathDisplayStr;
2616 }
2617 
2618 //===----------------------------------------------------------------------===//
2619 // C++ class member Handling
2620 //===----------------------------------------------------------------------===//
2621 
2622 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2623 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2624                                 SourceLocation ASLoc,
2625                                 SourceLocation ColonLoc,
2626                                 AttributeList *Attrs) {
2627   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2628   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2629                                                   ASLoc, ColonLoc);
2630   CurContext->addHiddenDecl(ASDecl);
2631   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2632 }
2633 
2634 /// CheckOverrideControl - Check C++11 override control semantics.
2635 void Sema::CheckOverrideControl(NamedDecl *D) {
2636   if (D->isInvalidDecl())
2637     return;
2638 
2639   // We only care about "override" and "final" declarations.
2640   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2641     return;
2642 
2643   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2644 
2645   // We can't check dependent instance methods.
2646   if (MD && MD->isInstance() &&
2647       (MD->getParent()->hasAnyDependentBases() ||
2648        MD->getType()->isDependentType()))
2649     return;
2650 
2651   if (MD && !MD->isVirtual()) {
2652     // If we have a non-virtual method, check if if hides a virtual method.
2653     // (In that case, it's most likely the method has the wrong type.)
2654     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2655     FindHiddenVirtualMethods(MD, OverloadedMethods);
2656 
2657     if (!OverloadedMethods.empty()) {
2658       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2659         Diag(OA->getLocation(),
2660              diag::override_keyword_hides_virtual_member_function)
2661           << "override" << (OverloadedMethods.size() > 1);
2662       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2663         Diag(FA->getLocation(),
2664              diag::override_keyword_hides_virtual_member_function)
2665           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2666           << (OverloadedMethods.size() > 1);
2667       }
2668       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2669       MD->setInvalidDecl();
2670       return;
2671     }
2672     // Fall through into the general case diagnostic.
2673     // FIXME: We might want to attempt typo correction here.
2674   }
2675 
2676   if (!MD || !MD->isVirtual()) {
2677     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2678       Diag(OA->getLocation(),
2679            diag::override_keyword_only_allowed_on_virtual_member_functions)
2680         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2681       D->dropAttr<OverrideAttr>();
2682     }
2683     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2684       Diag(FA->getLocation(),
2685            diag::override_keyword_only_allowed_on_virtual_member_functions)
2686         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2687         << FixItHint::CreateRemoval(FA->getLocation());
2688       D->dropAttr<FinalAttr>();
2689     }
2690     return;
2691   }
2692 
2693   // C++11 [class.virtual]p5:
2694   //   If a function is marked with the virt-specifier override and
2695   //   does not override a member function of a base class, the program is
2696   //   ill-formed.
2697   bool HasOverriddenMethods =
2698     MD->begin_overridden_methods() != MD->end_overridden_methods();
2699   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2700     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2701       << MD->getDeclName();
2702 }
2703 
2704 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2705   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2706     return;
2707   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2708   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2709       isa<CXXDestructorDecl>(MD))
2710     return;
2711 
2712   SourceLocation Loc = MD->getLocation();
2713   SourceLocation SpellingLoc = Loc;
2714   if (getSourceManager().isMacroArgExpansion(Loc))
2715     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2716   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2717   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2718       return;
2719 
2720   if (MD->size_overridden_methods() > 0) {
2721     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2722       << MD->getDeclName();
2723     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2724     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2725   }
2726 }
2727 
2728 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2729 /// function overrides a virtual member function marked 'final', according to
2730 /// C++11 [class.virtual]p4.
2731 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2732                                                   const CXXMethodDecl *Old) {
2733   FinalAttr *FA = Old->getAttr<FinalAttr>();
2734   if (!FA)
2735     return false;
2736 
2737   Diag(New->getLocation(), diag::err_final_function_overridden)
2738     << New->getDeclName()
2739     << FA->isSpelledAsSealed();
2740   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2741   return true;
2742 }
2743 
2744 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2745   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2746   // FIXME: Destruction of ObjC lifetime types has side-effects.
2747   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2748     return !RD->isCompleteDefinition() ||
2749            !RD->hasTrivialDefaultConstructor() ||
2750            !RD->hasTrivialDestructor();
2751   return false;
2752 }
2753 
2754 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2755   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2756     if (it->isDeclspecPropertyAttribute())
2757       return it;
2758   return nullptr;
2759 }
2760 
2761 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2762 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2763 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2764 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2765 /// present (but parsing it has been deferred).
2766 NamedDecl *
2767 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2768                                MultiTemplateParamsArg TemplateParameterLists,
2769                                Expr *BW, const VirtSpecifiers &VS,
2770                                InClassInitStyle InitStyle) {
2771   const DeclSpec &DS = D.getDeclSpec();
2772   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2773   DeclarationName Name = NameInfo.getName();
2774   SourceLocation Loc = NameInfo.getLoc();
2775 
2776   // For anonymous bitfields, the location should point to the type.
2777   if (Loc.isInvalid())
2778     Loc = D.getLocStart();
2779 
2780   Expr *BitWidth = static_cast<Expr*>(BW);
2781 
2782   assert(isa<CXXRecordDecl>(CurContext));
2783   assert(!DS.isFriendSpecified());
2784 
2785   bool isFunc = D.isDeclarationOfFunction();
2786 
2787   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2788     // The Microsoft extension __interface only permits public member functions
2789     // and prohibits constructors, destructors, operators, non-public member
2790     // functions, static methods and data members.
2791     unsigned InvalidDecl;
2792     bool ShowDeclName = true;
2793     if (!isFunc)
2794       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2795     else if (AS != AS_public)
2796       InvalidDecl = 2;
2797     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2798       InvalidDecl = 3;
2799     else switch (Name.getNameKind()) {
2800       case DeclarationName::CXXConstructorName:
2801         InvalidDecl = 4;
2802         ShowDeclName = false;
2803         break;
2804 
2805       case DeclarationName::CXXDestructorName:
2806         InvalidDecl = 5;
2807         ShowDeclName = false;
2808         break;
2809 
2810       case DeclarationName::CXXOperatorName:
2811       case DeclarationName::CXXConversionFunctionName:
2812         InvalidDecl = 6;
2813         break;
2814 
2815       default:
2816         InvalidDecl = 0;
2817         break;
2818     }
2819 
2820     if (InvalidDecl) {
2821       if (ShowDeclName)
2822         Diag(Loc, diag::err_invalid_member_in_interface)
2823           << (InvalidDecl-1) << Name;
2824       else
2825         Diag(Loc, diag::err_invalid_member_in_interface)
2826           << (InvalidDecl-1) << "";
2827       return nullptr;
2828     }
2829   }
2830 
2831   // C++ 9.2p6: A member shall not be declared to have automatic storage
2832   // duration (auto, register) or with the extern storage-class-specifier.
2833   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2834   // data members and cannot be applied to names declared const or static,
2835   // and cannot be applied to reference members.
2836   switch (DS.getStorageClassSpec()) {
2837   case DeclSpec::SCS_unspecified:
2838   case DeclSpec::SCS_typedef:
2839   case DeclSpec::SCS_static:
2840     break;
2841   case DeclSpec::SCS_mutable:
2842     if (isFunc) {
2843       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2844 
2845       // FIXME: It would be nicer if the keyword was ignored only for this
2846       // declarator. Otherwise we could get follow-up errors.
2847       D.getMutableDeclSpec().ClearStorageClassSpecs();
2848     }
2849     break;
2850   default:
2851     Diag(DS.getStorageClassSpecLoc(),
2852          diag::err_storageclass_invalid_for_member);
2853     D.getMutableDeclSpec().ClearStorageClassSpecs();
2854     break;
2855   }
2856 
2857   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2858                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2859                       !isFunc);
2860 
2861   if (DS.isConstexprSpecified() && isInstField) {
2862     SemaDiagnosticBuilder B =
2863         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2864     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2865     if (InitStyle == ICIS_NoInit) {
2866       B << 0 << 0;
2867       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2868         B << FixItHint::CreateRemoval(ConstexprLoc);
2869       else {
2870         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2871         D.getMutableDeclSpec().ClearConstexprSpec();
2872         const char *PrevSpec;
2873         unsigned DiagID;
2874         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2875             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2876         (void)Failed;
2877         assert(!Failed && "Making a constexpr member const shouldn't fail");
2878       }
2879     } else {
2880       B << 1;
2881       const char *PrevSpec;
2882       unsigned DiagID;
2883       if (D.getMutableDeclSpec().SetStorageClassSpec(
2884           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2885           Context.getPrintingPolicy())) {
2886         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2887                "This is the only DeclSpec that should fail to be applied");
2888         B << 1;
2889       } else {
2890         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2891         isInstField = false;
2892       }
2893     }
2894   }
2895 
2896   NamedDecl *Member;
2897   if (isInstField) {
2898     CXXScopeSpec &SS = D.getCXXScopeSpec();
2899 
2900     // Data members must have identifiers for names.
2901     if (!Name.isIdentifier()) {
2902       Diag(Loc, diag::err_bad_variable_name)
2903         << Name;
2904       return nullptr;
2905     }
2906 
2907     IdentifierInfo *II = Name.getAsIdentifierInfo();
2908 
2909     // Member field could not be with "template" keyword.
2910     // So TemplateParameterLists should be empty in this case.
2911     if (TemplateParameterLists.size()) {
2912       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2913       if (TemplateParams->size()) {
2914         // There is no such thing as a member field template.
2915         Diag(D.getIdentifierLoc(), diag::err_template_member)
2916             << II
2917             << SourceRange(TemplateParams->getTemplateLoc(),
2918                 TemplateParams->getRAngleLoc());
2919       } else {
2920         // There is an extraneous 'template<>' for this member.
2921         Diag(TemplateParams->getTemplateLoc(),
2922             diag::err_template_member_noparams)
2923             << II
2924             << SourceRange(TemplateParams->getTemplateLoc(),
2925                 TemplateParams->getRAngleLoc());
2926       }
2927       return nullptr;
2928     }
2929 
2930     if (SS.isSet() && !SS.isInvalid()) {
2931       // The user provided a superfluous scope specifier inside a class
2932       // definition:
2933       //
2934       // class X {
2935       //   int X::member;
2936       // };
2937       if (DeclContext *DC = computeDeclContext(SS, false))
2938         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2939       else
2940         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2941           << Name << SS.getRange();
2942 
2943       SS.clear();
2944     }
2945 
2946     AttributeList *MSPropertyAttr =
2947       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2948     if (MSPropertyAttr) {
2949       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2950                                 BitWidth, InitStyle, AS, MSPropertyAttr);
2951       if (!Member)
2952         return nullptr;
2953       isInstField = false;
2954     } else {
2955       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2956                                 BitWidth, InitStyle, AS);
2957       if (!Member)
2958         return nullptr;
2959     }
2960   } else {
2961     Member = HandleDeclarator(S, D, TemplateParameterLists);
2962     if (!Member)
2963       return nullptr;
2964 
2965     // Non-instance-fields can't have a bitfield.
2966     if (BitWidth) {
2967       if (Member->isInvalidDecl()) {
2968         // don't emit another diagnostic.
2969       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
2970         // C++ 9.6p3: A bit-field shall not be a static member.
2971         // "static member 'A' cannot be a bit-field"
2972         Diag(Loc, diag::err_static_not_bitfield)
2973           << Name << BitWidth->getSourceRange();
2974       } else if (isa<TypedefDecl>(Member)) {
2975         // "typedef member 'x' cannot be a bit-field"
2976         Diag(Loc, diag::err_typedef_not_bitfield)
2977           << Name << BitWidth->getSourceRange();
2978       } else {
2979         // A function typedef ("typedef int f(); f a;").
2980         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2981         Diag(Loc, diag::err_not_integral_type_bitfield)
2982           << Name << cast<ValueDecl>(Member)->getType()
2983           << BitWidth->getSourceRange();
2984       }
2985 
2986       BitWidth = nullptr;
2987       Member->setInvalidDecl();
2988     }
2989 
2990     Member->setAccess(AS);
2991 
2992     // If we have declared a member function template or static data member
2993     // template, set the access of the templated declaration as well.
2994     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2995       FunTmpl->getTemplatedDecl()->setAccess(AS);
2996     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2997       VarTmpl->getTemplatedDecl()->setAccess(AS);
2998   }
2999 
3000   if (VS.isOverrideSpecified())
3001     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3002   if (VS.isFinalSpecified())
3003     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3004                                             VS.isFinalSpelledSealed()));
3005 
3006   if (VS.getLastLocation().isValid()) {
3007     // Update the end location of a method that has a virt-specifiers.
3008     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3009       MD->setRangeEnd(VS.getLastLocation());
3010   }
3011 
3012   CheckOverrideControl(Member);
3013 
3014   assert((Name || isInstField) && "No identifier for non-field ?");
3015 
3016   if (isInstField) {
3017     FieldDecl *FD = cast<FieldDecl>(Member);
3018     FieldCollector->Add(FD);
3019 
3020     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3021       // Remember all explicit private FieldDecls that have a name, no side
3022       // effects and are not part of a dependent type declaration.
3023       if (!FD->isImplicit() && FD->getDeclName() &&
3024           FD->getAccess() == AS_private &&
3025           !FD->hasAttr<UnusedAttr>() &&
3026           !FD->getParent()->isDependentContext() &&
3027           !InitializationHasSideEffects(*FD))
3028         UnusedPrivateFields.insert(FD);
3029     }
3030   }
3031 
3032   return Member;
3033 }
3034 
3035 namespace {
3036   class UninitializedFieldVisitor
3037       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3038     Sema &S;
3039     // List of Decls to generate a warning on.  Also remove Decls that become
3040     // initialized.
3041     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3042     // List of base classes of the record.  Classes are removed after their
3043     // initializers.
3044     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3045     // Vector of decls to be removed from the Decl set prior to visiting the
3046     // nodes.  These Decls may have been initialized in the prior initializer.
3047     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3048     // If non-null, add a note to the warning pointing back to the constructor.
3049     const CXXConstructorDecl *Constructor;
3050     // Variables to hold state when processing an initializer list.  When
3051     // InitList is true, special case initialization of FieldDecls matching
3052     // InitListFieldDecl.
3053     bool InitList;
3054     FieldDecl *InitListFieldDecl;
3055     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3056 
3057   public:
3058     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3059     UninitializedFieldVisitor(Sema &S,
3060                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3061                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3062       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3063         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3064 
3065     // Returns true if the use of ME is not an uninitialized use.
3066     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3067                                          bool CheckReferenceOnly) {
3068       llvm::SmallVector<FieldDecl*, 4> Fields;
3069       bool ReferenceField = false;
3070       while (ME) {
3071         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3072         if (!FD)
3073           return false;
3074         Fields.push_back(FD);
3075         if (FD->getType()->isReferenceType())
3076           ReferenceField = true;
3077         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3078       }
3079 
3080       // Binding a reference to an unintialized field is not an
3081       // uninitialized use.
3082       if (CheckReferenceOnly && !ReferenceField)
3083         return true;
3084 
3085       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3086       // Discard the first field since it is the field decl that is being
3087       // initialized.
3088       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3089         UsedFieldIndex.push_back((*I)->getFieldIndex());
3090       }
3091 
3092       for (auto UsedIter = UsedFieldIndex.begin(),
3093                 UsedEnd = UsedFieldIndex.end(),
3094                 OrigIter = InitFieldIndex.begin(),
3095                 OrigEnd = InitFieldIndex.end();
3096            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3097         if (*UsedIter < *OrigIter)
3098           return true;
3099         if (*UsedIter > *OrigIter)
3100           break;
3101       }
3102 
3103       return false;
3104     }
3105 
3106     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3107                           bool AddressOf) {
3108       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3109         return;
3110 
3111       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3112       // or union.
3113       MemberExpr *FieldME = ME;
3114 
3115       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3116 
3117       Expr *Base = ME;
3118       while (MemberExpr *SubME =
3119                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3120 
3121         if (isa<VarDecl>(SubME->getMemberDecl()))
3122           return;
3123 
3124         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3125           if (!FD->isAnonymousStructOrUnion())
3126             FieldME = SubME;
3127 
3128         if (!FieldME->getType().isPODType(S.Context))
3129           AllPODFields = false;
3130 
3131         Base = SubME->getBase();
3132       }
3133 
3134       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3135         return;
3136 
3137       if (AddressOf && AllPODFields)
3138         return;
3139 
3140       ValueDecl* FoundVD = FieldME->getMemberDecl();
3141 
3142       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3143         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3144           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3145         }
3146 
3147         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3148           QualType T = BaseCast->getType();
3149           if (T->isPointerType() &&
3150               BaseClasses.count(T->getPointeeType())) {
3151             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3152                 << T->getPointeeType() << FoundVD;
3153           }
3154         }
3155       }
3156 
3157       if (!Decls.count(FoundVD))
3158         return;
3159 
3160       const bool IsReference = FoundVD->getType()->isReferenceType();
3161 
3162       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3163         // Special checking for initializer lists.
3164         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3165           return;
3166         }
3167       } else {
3168         // Prevent double warnings on use of unbounded references.
3169         if (CheckReferenceOnly && !IsReference)
3170           return;
3171       }
3172 
3173       unsigned diag = IsReference
3174           ? diag::warn_reference_field_is_uninit
3175           : diag::warn_field_is_uninit;
3176       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3177       if (Constructor)
3178         S.Diag(Constructor->getLocation(),
3179                diag::note_uninit_in_this_constructor)
3180           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3181 
3182     }
3183 
3184     void HandleValue(Expr *E, bool AddressOf) {
3185       E = E->IgnoreParens();
3186 
3187       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3188         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3189                          AddressOf /*AddressOf*/);
3190         return;
3191       }
3192 
3193       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3194         Visit(CO->getCond());
3195         HandleValue(CO->getTrueExpr(), AddressOf);
3196         HandleValue(CO->getFalseExpr(), AddressOf);
3197         return;
3198       }
3199 
3200       if (BinaryConditionalOperator *BCO =
3201               dyn_cast<BinaryConditionalOperator>(E)) {
3202         Visit(BCO->getCond());
3203         HandleValue(BCO->getFalseExpr(), AddressOf);
3204         return;
3205       }
3206 
3207       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3208         HandleValue(OVE->getSourceExpr(), AddressOf);
3209         return;
3210       }
3211 
3212       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3213         switch (BO->getOpcode()) {
3214         default:
3215           break;
3216         case(BO_PtrMemD):
3217         case(BO_PtrMemI):
3218           HandleValue(BO->getLHS(), AddressOf);
3219           Visit(BO->getRHS());
3220           return;
3221         case(BO_Comma):
3222           Visit(BO->getLHS());
3223           HandleValue(BO->getRHS(), AddressOf);
3224           return;
3225         }
3226       }
3227 
3228       Visit(E);
3229     }
3230 
3231     void CheckInitListExpr(InitListExpr *ILE) {
3232       InitFieldIndex.push_back(0);
3233       for (auto Child : ILE->children()) {
3234         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3235           CheckInitListExpr(SubList);
3236         } else {
3237           Visit(Child);
3238         }
3239         ++InitFieldIndex.back();
3240       }
3241       InitFieldIndex.pop_back();
3242     }
3243 
3244     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3245                           FieldDecl *Field, const Type *BaseClass) {
3246       // Remove Decls that may have been initialized in the previous
3247       // initializer.
3248       for (ValueDecl* VD : DeclsToRemove)
3249         Decls.erase(VD);
3250       DeclsToRemove.clear();
3251 
3252       Constructor = FieldConstructor;
3253       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3254 
3255       if (ILE && Field) {
3256         InitList = true;
3257         InitListFieldDecl = Field;
3258         InitFieldIndex.clear();
3259         CheckInitListExpr(ILE);
3260       } else {
3261         InitList = false;
3262         Visit(E);
3263       }
3264 
3265       if (Field)
3266         Decls.erase(Field);
3267       if (BaseClass)
3268         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3269     }
3270 
3271     void VisitMemberExpr(MemberExpr *ME) {
3272       // All uses of unbounded reference fields will warn.
3273       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3274     }
3275 
3276     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3277       if (E->getCastKind() == CK_LValueToRValue) {
3278         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3279         return;
3280       }
3281 
3282       Inherited::VisitImplicitCastExpr(E);
3283     }
3284 
3285     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3286       if (E->getConstructor()->isCopyConstructor()) {
3287         Expr *ArgExpr = E->getArg(0);
3288         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3289           if (ILE->getNumInits() == 1)
3290             ArgExpr = ILE->getInit(0);
3291         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3292           if (ICE->getCastKind() == CK_NoOp)
3293             ArgExpr = ICE->getSubExpr();
3294         HandleValue(ArgExpr, false /*AddressOf*/);
3295         return;
3296       }
3297       Inherited::VisitCXXConstructExpr(E);
3298     }
3299 
3300     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3301       Expr *Callee = E->getCallee();
3302       if (isa<MemberExpr>(Callee)) {
3303         HandleValue(Callee, false /*AddressOf*/);
3304         for (auto Arg : E->arguments())
3305           Visit(Arg);
3306         return;
3307       }
3308 
3309       Inherited::VisitCXXMemberCallExpr(E);
3310     }
3311 
3312     void VisitCallExpr(CallExpr *E) {
3313       // Treat std::move as a use.
3314       if (E->getNumArgs() == 1) {
3315         if (FunctionDecl *FD = E->getDirectCallee()) {
3316           if (FD->isInStdNamespace() && FD->getIdentifier() &&
3317               FD->getIdentifier()->isStr("move")) {
3318             HandleValue(E->getArg(0), false /*AddressOf*/);
3319             return;
3320           }
3321         }
3322       }
3323 
3324       Inherited::VisitCallExpr(E);
3325     }
3326 
3327     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3328       Expr *Callee = E->getCallee();
3329 
3330       if (isa<UnresolvedLookupExpr>(Callee))
3331         return Inherited::VisitCXXOperatorCallExpr(E);
3332 
3333       Visit(Callee);
3334       for (auto Arg : E->arguments())
3335         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3336     }
3337 
3338     void VisitBinaryOperator(BinaryOperator *E) {
3339       // If a field assignment is detected, remove the field from the
3340       // uninitiailized field set.
3341       if (E->getOpcode() == BO_Assign)
3342         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3343           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3344             if (!FD->getType()->isReferenceType())
3345               DeclsToRemove.push_back(FD);
3346 
3347       if (E->isCompoundAssignmentOp()) {
3348         HandleValue(E->getLHS(), false /*AddressOf*/);
3349         Visit(E->getRHS());
3350         return;
3351       }
3352 
3353       Inherited::VisitBinaryOperator(E);
3354     }
3355 
3356     void VisitUnaryOperator(UnaryOperator *E) {
3357       if (E->isIncrementDecrementOp()) {
3358         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3359         return;
3360       }
3361       if (E->getOpcode() == UO_AddrOf) {
3362         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3363           HandleValue(ME->getBase(), true /*AddressOf*/);
3364           return;
3365         }
3366       }
3367 
3368       Inherited::VisitUnaryOperator(E);
3369     }
3370   };
3371 
3372   // Diagnose value-uses of fields to initialize themselves, e.g.
3373   //   foo(foo)
3374   // where foo is not also a parameter to the constructor.
3375   // Also diagnose across field uninitialized use such as
3376   //   x(y), y(x)
3377   // TODO: implement -Wuninitialized and fold this into that framework.
3378   static void DiagnoseUninitializedFields(
3379       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3380 
3381     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3382                                            Constructor->getLocation())) {
3383       return;
3384     }
3385 
3386     if (Constructor->isInvalidDecl())
3387       return;
3388 
3389     const CXXRecordDecl *RD = Constructor->getParent();
3390 
3391     if (RD->getDescribedClassTemplate())
3392       return;
3393 
3394     // Holds fields that are uninitialized.
3395     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3396 
3397     // At the beginning, all fields are uninitialized.
3398     for (auto *I : RD->decls()) {
3399       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3400         UninitializedFields.insert(FD);
3401       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3402         UninitializedFields.insert(IFD->getAnonField());
3403       }
3404     }
3405 
3406     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3407     for (auto I : RD->bases())
3408       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3409 
3410     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3411       return;
3412 
3413     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3414                                                    UninitializedFields,
3415                                                    UninitializedBaseClasses);
3416 
3417     for (const auto *FieldInit : Constructor->inits()) {
3418       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3419         break;
3420 
3421       Expr *InitExpr = FieldInit->getInit();
3422       if (!InitExpr)
3423         continue;
3424 
3425       if (CXXDefaultInitExpr *Default =
3426               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3427         InitExpr = Default->getExpr();
3428         if (!InitExpr)
3429           continue;
3430         // In class initializers will point to the constructor.
3431         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3432                                               FieldInit->getAnyMember(),
3433                                               FieldInit->getBaseClass());
3434       } else {
3435         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3436                                               FieldInit->getAnyMember(),
3437                                               FieldInit->getBaseClass());
3438       }
3439     }
3440   }
3441 } // namespace
3442 
3443 /// \brief Enter a new C++ default initializer scope. After calling this, the
3444 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3445 /// parsing or instantiating the initializer failed.
3446 void Sema::ActOnStartCXXInClassMemberInitializer() {
3447   // Create a synthetic function scope to represent the call to the constructor
3448   // that notionally surrounds a use of this initializer.
3449   PushFunctionScope();
3450 }
3451 
3452 /// \brief This is invoked after parsing an in-class initializer for a
3453 /// non-static C++ class member, and after instantiating an in-class initializer
3454 /// in a class template. Such actions are deferred until the class is complete.
3455 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3456                                                   SourceLocation InitLoc,
3457                                                   Expr *InitExpr) {
3458   // Pop the notional constructor scope we created earlier.
3459   PopFunctionScopeInfo(nullptr, D);
3460 
3461   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3462   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3463          "must set init style when field is created");
3464 
3465   if (!InitExpr) {
3466     D->setInvalidDecl();
3467     if (FD)
3468       FD->removeInClassInitializer();
3469     return;
3470   }
3471 
3472   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3473     FD->setInvalidDecl();
3474     FD->removeInClassInitializer();
3475     return;
3476   }
3477 
3478   ExprResult Init = InitExpr;
3479   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3480     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3481     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3482         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3483         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3484     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3485     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3486     if (Init.isInvalid()) {
3487       FD->setInvalidDecl();
3488       return;
3489     }
3490   }
3491 
3492   // C++11 [class.base.init]p7:
3493   //   The initialization of each base and member constitutes a
3494   //   full-expression.
3495   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3496   if (Init.isInvalid()) {
3497     FD->setInvalidDecl();
3498     return;
3499   }
3500 
3501   InitExpr = Init.get();
3502 
3503   FD->setInClassInitializer(InitExpr);
3504 }
3505 
3506 /// \brief Find the direct and/or virtual base specifiers that
3507 /// correspond to the given base type, for use in base initialization
3508 /// within a constructor.
3509 static bool FindBaseInitializer(Sema &SemaRef,
3510                                 CXXRecordDecl *ClassDecl,
3511                                 QualType BaseType,
3512                                 const CXXBaseSpecifier *&DirectBaseSpec,
3513                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3514   // First, check for a direct base class.
3515   DirectBaseSpec = nullptr;
3516   for (const auto &Base : ClassDecl->bases()) {
3517     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3518       // We found a direct base of this type. That's what we're
3519       // initializing.
3520       DirectBaseSpec = &Base;
3521       break;
3522     }
3523   }
3524 
3525   // Check for a virtual base class.
3526   // FIXME: We might be able to short-circuit this if we know in advance that
3527   // there are no virtual bases.
3528   VirtualBaseSpec = nullptr;
3529   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3530     // We haven't found a base yet; search the class hierarchy for a
3531     // virtual base class.
3532     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3533                        /*DetectVirtual=*/false);
3534     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3535                               SemaRef.Context.getTypeDeclType(ClassDecl),
3536                               BaseType, Paths)) {
3537       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3538            Path != Paths.end(); ++Path) {
3539         if (Path->back().Base->isVirtual()) {
3540           VirtualBaseSpec = Path->back().Base;
3541           break;
3542         }
3543       }
3544     }
3545   }
3546 
3547   return DirectBaseSpec || VirtualBaseSpec;
3548 }
3549 
3550 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3551 MemInitResult
3552 Sema::ActOnMemInitializer(Decl *ConstructorD,
3553                           Scope *S,
3554                           CXXScopeSpec &SS,
3555                           IdentifierInfo *MemberOrBase,
3556                           ParsedType TemplateTypeTy,
3557                           const DeclSpec &DS,
3558                           SourceLocation IdLoc,
3559                           Expr *InitList,
3560                           SourceLocation EllipsisLoc) {
3561   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3562                              DS, IdLoc, InitList,
3563                              EllipsisLoc);
3564 }
3565 
3566 /// \brief Handle a C++ member initializer using parentheses syntax.
3567 MemInitResult
3568 Sema::ActOnMemInitializer(Decl *ConstructorD,
3569                           Scope *S,
3570                           CXXScopeSpec &SS,
3571                           IdentifierInfo *MemberOrBase,
3572                           ParsedType TemplateTypeTy,
3573                           const DeclSpec &DS,
3574                           SourceLocation IdLoc,
3575                           SourceLocation LParenLoc,
3576                           ArrayRef<Expr *> Args,
3577                           SourceLocation RParenLoc,
3578                           SourceLocation EllipsisLoc) {
3579   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3580                                            Args, RParenLoc);
3581   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3582                              DS, IdLoc, List, EllipsisLoc);
3583 }
3584 
3585 namespace {
3586 
3587 // Callback to only accept typo corrections that can be a valid C++ member
3588 // intializer: either a non-static field member or a base class.
3589 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3590 public:
3591   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3592       : ClassDecl(ClassDecl) {}
3593 
3594   bool ValidateCandidate(const TypoCorrection &candidate) override {
3595     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3596       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3597         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3598       return isa<TypeDecl>(ND);
3599     }
3600     return false;
3601   }
3602 
3603 private:
3604   CXXRecordDecl *ClassDecl;
3605 };
3606 
3607 }
3608 
3609 /// \brief Handle a C++ member initializer.
3610 MemInitResult
3611 Sema::BuildMemInitializer(Decl *ConstructorD,
3612                           Scope *S,
3613                           CXXScopeSpec &SS,
3614                           IdentifierInfo *MemberOrBase,
3615                           ParsedType TemplateTypeTy,
3616                           const DeclSpec &DS,
3617                           SourceLocation IdLoc,
3618                           Expr *Init,
3619                           SourceLocation EllipsisLoc) {
3620   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3621   if (!Res.isUsable())
3622     return true;
3623   Init = Res.get();
3624 
3625   if (!ConstructorD)
3626     return true;
3627 
3628   AdjustDeclIfTemplate(ConstructorD);
3629 
3630   CXXConstructorDecl *Constructor
3631     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3632   if (!Constructor) {
3633     // The user wrote a constructor initializer on a function that is
3634     // not a C++ constructor. Ignore the error for now, because we may
3635     // have more member initializers coming; we'll diagnose it just
3636     // once in ActOnMemInitializers.
3637     return true;
3638   }
3639 
3640   CXXRecordDecl *ClassDecl = Constructor->getParent();
3641 
3642   // C++ [class.base.init]p2:
3643   //   Names in a mem-initializer-id are looked up in the scope of the
3644   //   constructor's class and, if not found in that scope, are looked
3645   //   up in the scope containing the constructor's definition.
3646   //   [Note: if the constructor's class contains a member with the
3647   //   same name as a direct or virtual base class of the class, a
3648   //   mem-initializer-id naming the member or base class and composed
3649   //   of a single identifier refers to the class member. A
3650   //   mem-initializer-id for the hidden base class may be specified
3651   //   using a qualified name. ]
3652   if (!SS.getScopeRep() && !TemplateTypeTy) {
3653     // Look for a member, first.
3654     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3655     if (!Result.empty()) {
3656       ValueDecl *Member;
3657       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3658           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3659         if (EllipsisLoc.isValid())
3660           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3661             << MemberOrBase
3662             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3663 
3664         return BuildMemberInitializer(Member, Init, IdLoc);
3665       }
3666     }
3667   }
3668   // It didn't name a member, so see if it names a class.
3669   QualType BaseType;
3670   TypeSourceInfo *TInfo = nullptr;
3671 
3672   if (TemplateTypeTy) {
3673     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3674   } else if (DS.getTypeSpecType() == TST_decltype) {
3675     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3676   } else {
3677     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3678     LookupParsedName(R, S, &SS);
3679 
3680     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3681     if (!TyD) {
3682       if (R.isAmbiguous()) return true;
3683 
3684       // We don't want access-control diagnostics here.
3685       R.suppressDiagnostics();
3686 
3687       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3688         bool NotUnknownSpecialization = false;
3689         DeclContext *DC = computeDeclContext(SS, false);
3690         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3691           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3692 
3693         if (!NotUnknownSpecialization) {
3694           // When the scope specifier can refer to a member of an unknown
3695           // specialization, we take it as a type name.
3696           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3697                                        SS.getWithLocInContext(Context),
3698                                        *MemberOrBase, IdLoc);
3699           if (BaseType.isNull())
3700             return true;
3701 
3702           R.clear();
3703           R.setLookupName(MemberOrBase);
3704         }
3705       }
3706 
3707       // If no results were found, try to correct typos.
3708       TypoCorrection Corr;
3709       if (R.empty() && BaseType.isNull() &&
3710           (Corr = CorrectTypo(
3711                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3712                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3713                CTK_ErrorRecovery, ClassDecl))) {
3714         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3715           // We have found a non-static data member with a similar
3716           // name to what was typed; complain and initialize that
3717           // member.
3718           diagnoseTypo(Corr,
3719                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3720                          << MemberOrBase << true);
3721           return BuildMemberInitializer(Member, Init, IdLoc);
3722         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3723           const CXXBaseSpecifier *DirectBaseSpec;
3724           const CXXBaseSpecifier *VirtualBaseSpec;
3725           if (FindBaseInitializer(*this, ClassDecl,
3726                                   Context.getTypeDeclType(Type),
3727                                   DirectBaseSpec, VirtualBaseSpec)) {
3728             // We have found a direct or virtual base class with a
3729             // similar name to what was typed; complain and initialize
3730             // that base class.
3731             diagnoseTypo(Corr,
3732                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3733                            << MemberOrBase << false,
3734                          PDiag() /*Suppress note, we provide our own.*/);
3735 
3736             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3737                                                               : VirtualBaseSpec;
3738             Diag(BaseSpec->getLocStart(),
3739                  diag::note_base_class_specified_here)
3740               << BaseSpec->getType()
3741               << BaseSpec->getSourceRange();
3742 
3743             TyD = Type;
3744           }
3745         }
3746       }
3747 
3748       if (!TyD && BaseType.isNull()) {
3749         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3750           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3751         return true;
3752       }
3753     }
3754 
3755     if (BaseType.isNull()) {
3756       BaseType = Context.getTypeDeclType(TyD);
3757       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3758       if (SS.isSet()) {
3759         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3760                                              BaseType);
3761         TInfo = Context.CreateTypeSourceInfo(BaseType);
3762         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3763         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3764         TL.setElaboratedKeywordLoc(SourceLocation());
3765         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3766       }
3767     }
3768   }
3769 
3770   if (!TInfo)
3771     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3772 
3773   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3774 }
3775 
3776 /// Checks a member initializer expression for cases where reference (or
3777 /// pointer) members are bound to by-value parameters (or their addresses).
3778 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3779                                                Expr *Init,
3780                                                SourceLocation IdLoc) {
3781   QualType MemberTy = Member->getType();
3782 
3783   // We only handle pointers and references currently.
3784   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3785   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3786     return;
3787 
3788   const bool IsPointer = MemberTy->isPointerType();
3789   if (IsPointer) {
3790     if (const UnaryOperator *Op
3791           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3792       // The only case we're worried about with pointers requires taking the
3793       // address.
3794       if (Op->getOpcode() != UO_AddrOf)
3795         return;
3796 
3797       Init = Op->getSubExpr();
3798     } else {
3799       // We only handle address-of expression initializers for pointers.
3800       return;
3801     }
3802   }
3803 
3804   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3805     // We only warn when referring to a non-reference parameter declaration.
3806     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3807     if (!Parameter || Parameter->getType()->isReferenceType())
3808       return;
3809 
3810     S.Diag(Init->getExprLoc(),
3811            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3812                      : diag::warn_bind_ref_member_to_parameter)
3813       << Member << Parameter << Init->getSourceRange();
3814   } else {
3815     // Other initializers are fine.
3816     return;
3817   }
3818 
3819   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3820     << (unsigned)IsPointer;
3821 }
3822 
3823 MemInitResult
3824 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3825                              SourceLocation IdLoc) {
3826   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3827   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3828   assert((DirectMember || IndirectMember) &&
3829          "Member must be a FieldDecl or IndirectFieldDecl");
3830 
3831   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3832     return true;
3833 
3834   if (Member->isInvalidDecl())
3835     return true;
3836 
3837   MultiExprArg Args;
3838   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3839     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3840   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3841     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3842   } else {
3843     // Template instantiation doesn't reconstruct ParenListExprs for us.
3844     Args = Init;
3845   }
3846 
3847   SourceRange InitRange = Init->getSourceRange();
3848 
3849   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3850     // Can't check initialization for a member of dependent type or when
3851     // any of the arguments are type-dependent expressions.
3852     DiscardCleanupsInEvaluationContext();
3853   } else {
3854     bool InitList = false;
3855     if (isa<InitListExpr>(Init)) {
3856       InitList = true;
3857       Args = Init;
3858     }
3859 
3860     // Initialize the member.
3861     InitializedEntity MemberEntity =
3862       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3863                    : InitializedEntity::InitializeMember(IndirectMember,
3864                                                          nullptr);
3865     InitializationKind Kind =
3866       InitList ? InitializationKind::CreateDirectList(IdLoc)
3867                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3868                                                   InitRange.getEnd());
3869 
3870     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3871     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3872                                             nullptr);
3873     if (MemberInit.isInvalid())
3874       return true;
3875 
3876     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3877 
3878     // C++11 [class.base.init]p7:
3879     //   The initialization of each base and member constitutes a
3880     //   full-expression.
3881     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3882     if (MemberInit.isInvalid())
3883       return true;
3884 
3885     Init = MemberInit.get();
3886   }
3887 
3888   if (DirectMember) {
3889     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3890                                             InitRange.getBegin(), Init,
3891                                             InitRange.getEnd());
3892   } else {
3893     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3894                                             InitRange.getBegin(), Init,
3895                                             InitRange.getEnd());
3896   }
3897 }
3898 
3899 MemInitResult
3900 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3901                                  CXXRecordDecl *ClassDecl) {
3902   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3903   if (!LangOpts.CPlusPlus11)
3904     return Diag(NameLoc, diag::err_delegating_ctor)
3905       << TInfo->getTypeLoc().getLocalSourceRange();
3906   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3907 
3908   bool InitList = true;
3909   MultiExprArg Args = Init;
3910   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3911     InitList = false;
3912     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3913   }
3914 
3915   SourceRange InitRange = Init->getSourceRange();
3916   // Initialize the object.
3917   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3918                                      QualType(ClassDecl->getTypeForDecl(), 0));
3919   InitializationKind Kind =
3920     InitList ? InitializationKind::CreateDirectList(NameLoc)
3921              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3922                                                 InitRange.getEnd());
3923   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3924   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3925                                               Args, nullptr);
3926   if (DelegationInit.isInvalid())
3927     return true;
3928 
3929   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3930          "Delegating constructor with no target?");
3931 
3932   // C++11 [class.base.init]p7:
3933   //   The initialization of each base and member constitutes a
3934   //   full-expression.
3935   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3936                                        InitRange.getBegin());
3937   if (DelegationInit.isInvalid())
3938     return true;
3939 
3940   // If we are in a dependent context, template instantiation will
3941   // perform this type-checking again. Just save the arguments that we
3942   // received in a ParenListExpr.
3943   // FIXME: This isn't quite ideal, since our ASTs don't capture all
3944   // of the information that we have about the base
3945   // initializer. However, deconstructing the ASTs is a dicey process,
3946   // and this approach is far more likely to get the corner cases right.
3947   if (CurContext->isDependentContext())
3948     DelegationInit = Init;
3949 
3950   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
3951                                           DelegationInit.getAs<Expr>(),
3952                                           InitRange.getEnd());
3953 }
3954 
3955 MemInitResult
3956 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
3957                            Expr *Init, CXXRecordDecl *ClassDecl,
3958                            SourceLocation EllipsisLoc) {
3959   SourceLocation BaseLoc
3960     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
3961 
3962   if (!BaseType->isDependentType() && !BaseType->isRecordType())
3963     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3964              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3965 
3966   // C++ [class.base.init]p2:
3967   //   [...] Unless the mem-initializer-id names a nonstatic data
3968   //   member of the constructor's class or a direct or virtual base
3969   //   of that class, the mem-initializer is ill-formed. A
3970   //   mem-initializer-list can initialize a base class using any
3971   //   name that denotes that base class type.
3972   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
3973 
3974   SourceRange InitRange = Init->getSourceRange();
3975   if (EllipsisLoc.isValid()) {
3976     // This is a pack expansion.
3977     if (!BaseType->containsUnexpandedParameterPack())  {
3978       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
3979         << SourceRange(BaseLoc, InitRange.getEnd());
3980 
3981       EllipsisLoc = SourceLocation();
3982     }
3983   } else {
3984     // Check for any unexpanded parameter packs.
3985     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3986       return true;
3987 
3988     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3989       return true;
3990   }
3991 
3992   // Check for direct and virtual base classes.
3993   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3994   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
3995   if (!Dependent) {
3996     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3997                                        BaseType))
3998       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
3999 
4000     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4001                         VirtualBaseSpec);
4002 
4003     // C++ [base.class.init]p2:
4004     // Unless the mem-initializer-id names a nonstatic data member of the
4005     // constructor's class or a direct or virtual base of that class, the
4006     // mem-initializer is ill-formed.
4007     if (!DirectBaseSpec && !VirtualBaseSpec) {
4008       // If the class has any dependent bases, then it's possible that
4009       // one of those types will resolve to the same type as
4010       // BaseType. Therefore, just treat this as a dependent base
4011       // class initialization.  FIXME: Should we try to check the
4012       // initialization anyway? It seems odd.
4013       if (ClassDecl->hasAnyDependentBases())
4014         Dependent = true;
4015       else
4016         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4017           << BaseType << Context.getTypeDeclType(ClassDecl)
4018           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4019     }
4020   }
4021 
4022   if (Dependent) {
4023     DiscardCleanupsInEvaluationContext();
4024 
4025     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4026                                             /*IsVirtual=*/false,
4027                                             InitRange.getBegin(), Init,
4028                                             InitRange.getEnd(), EllipsisLoc);
4029   }
4030 
4031   // C++ [base.class.init]p2:
4032   //   If a mem-initializer-id is ambiguous because it designates both
4033   //   a direct non-virtual base class and an inherited virtual base
4034   //   class, the mem-initializer is ill-formed.
4035   if (DirectBaseSpec && VirtualBaseSpec)
4036     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4037       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4038 
4039   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4040   if (!BaseSpec)
4041     BaseSpec = VirtualBaseSpec;
4042 
4043   // Initialize the base.
4044   bool InitList = true;
4045   MultiExprArg Args = Init;
4046   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4047     InitList = false;
4048     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4049   }
4050 
4051   InitializedEntity BaseEntity =
4052     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4053   InitializationKind Kind =
4054     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4055              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4056                                                 InitRange.getEnd());
4057   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4058   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4059   if (BaseInit.isInvalid())
4060     return true;
4061 
4062   // C++11 [class.base.init]p7:
4063   //   The initialization of each base and member constitutes a
4064   //   full-expression.
4065   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4066   if (BaseInit.isInvalid())
4067     return true;
4068 
4069   // If we are in a dependent context, template instantiation will
4070   // perform this type-checking again. Just save the arguments that we
4071   // received in a ParenListExpr.
4072   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4073   // of the information that we have about the base
4074   // initializer. However, deconstructing the ASTs is a dicey process,
4075   // and this approach is far more likely to get the corner cases right.
4076   if (CurContext->isDependentContext())
4077     BaseInit = Init;
4078 
4079   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4080                                           BaseSpec->isVirtual(),
4081                                           InitRange.getBegin(),
4082                                           BaseInit.getAs<Expr>(),
4083                                           InitRange.getEnd(), EllipsisLoc);
4084 }
4085 
4086 // Create a static_cast\<T&&>(expr).
4087 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4088   if (T.isNull()) T = E->getType();
4089   QualType TargetType = SemaRef.BuildReferenceType(
4090       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4091   SourceLocation ExprLoc = E->getLocStart();
4092   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4093       TargetType, ExprLoc);
4094 
4095   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4096                                    SourceRange(ExprLoc, ExprLoc),
4097                                    E->getSourceRange()).get();
4098 }
4099 
4100 /// ImplicitInitializerKind - How an implicit base or member initializer should
4101 /// initialize its base or member.
4102 enum ImplicitInitializerKind {
4103   IIK_Default,
4104   IIK_Copy,
4105   IIK_Move,
4106   IIK_Inherit
4107 };
4108 
4109 static bool
4110 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4111                              ImplicitInitializerKind ImplicitInitKind,
4112                              CXXBaseSpecifier *BaseSpec,
4113                              bool IsInheritedVirtualBase,
4114                              CXXCtorInitializer *&CXXBaseInit) {
4115   InitializedEntity InitEntity
4116     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4117                                         IsInheritedVirtualBase);
4118 
4119   ExprResult BaseInit;
4120 
4121   switch (ImplicitInitKind) {
4122   case IIK_Inherit:
4123   case IIK_Default: {
4124     InitializationKind InitKind
4125       = InitializationKind::CreateDefault(Constructor->getLocation());
4126     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4127     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4128     break;
4129   }
4130 
4131   case IIK_Move:
4132   case IIK_Copy: {
4133     bool Moving = ImplicitInitKind == IIK_Move;
4134     ParmVarDecl *Param = Constructor->getParamDecl(0);
4135     QualType ParamType = Param->getType().getNonReferenceType();
4136 
4137     Expr *CopyCtorArg =
4138       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4139                           SourceLocation(), Param, false,
4140                           Constructor->getLocation(), ParamType,
4141                           VK_LValue, nullptr);
4142 
4143     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4144 
4145     // Cast to the base class to avoid ambiguities.
4146     QualType ArgTy =
4147       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4148                                        ParamType.getQualifiers());
4149 
4150     if (Moving) {
4151       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4152     }
4153 
4154     CXXCastPath BasePath;
4155     BasePath.push_back(BaseSpec);
4156     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4157                                             CK_UncheckedDerivedToBase,
4158                                             Moving ? VK_XValue : VK_LValue,
4159                                             &BasePath).get();
4160 
4161     InitializationKind InitKind
4162       = InitializationKind::CreateDirect(Constructor->getLocation(),
4163                                          SourceLocation(), SourceLocation());
4164     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4165     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4166     break;
4167   }
4168   }
4169 
4170   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4171   if (BaseInit.isInvalid())
4172     return true;
4173 
4174   CXXBaseInit =
4175     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4176                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4177                                                         SourceLocation()),
4178                                              BaseSpec->isVirtual(),
4179                                              SourceLocation(),
4180                                              BaseInit.getAs<Expr>(),
4181                                              SourceLocation(),
4182                                              SourceLocation());
4183 
4184   return false;
4185 }
4186 
4187 static bool RefersToRValueRef(Expr *MemRef) {
4188   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4189   return Referenced->getType()->isRValueReferenceType();
4190 }
4191 
4192 static bool
4193 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4194                                ImplicitInitializerKind ImplicitInitKind,
4195                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4196                                CXXCtorInitializer *&CXXMemberInit) {
4197   if (Field->isInvalidDecl())
4198     return true;
4199 
4200   SourceLocation Loc = Constructor->getLocation();
4201 
4202   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4203     bool Moving = ImplicitInitKind == IIK_Move;
4204     ParmVarDecl *Param = Constructor->getParamDecl(0);
4205     QualType ParamType = Param->getType().getNonReferenceType();
4206 
4207     // Suppress copying zero-width bitfields.
4208     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4209       return false;
4210 
4211     Expr *MemberExprBase =
4212       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4213                           SourceLocation(), Param, false,
4214                           Loc, ParamType, VK_LValue, nullptr);
4215 
4216     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4217 
4218     if (Moving) {
4219       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4220     }
4221 
4222     // Build a reference to this field within the parameter.
4223     CXXScopeSpec SS;
4224     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4225                               Sema::LookupMemberName);
4226     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4227                                   : cast<ValueDecl>(Field), AS_public);
4228     MemberLookup.resolveKind();
4229     ExprResult CtorArg
4230       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4231                                          ParamType, Loc,
4232                                          /*IsArrow=*/false,
4233                                          SS,
4234                                          /*TemplateKWLoc=*/SourceLocation(),
4235                                          /*FirstQualifierInScope=*/nullptr,
4236                                          MemberLookup,
4237                                          /*TemplateArgs=*/nullptr,
4238                                          /*S*/nullptr);
4239     if (CtorArg.isInvalid())
4240       return true;
4241 
4242     // C++11 [class.copy]p15:
4243     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4244     //     with static_cast<T&&>(x.m);
4245     if (RefersToRValueRef(CtorArg.get())) {
4246       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4247     }
4248 
4249     InitializedEntity Entity =
4250         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4251                                                        /*Implicit*/ true)
4252                  : InitializedEntity::InitializeMember(Field, nullptr,
4253                                                        /*Implicit*/ true);
4254 
4255     // Direct-initialize to use the copy constructor.
4256     InitializationKind InitKind =
4257       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4258 
4259     Expr *CtorArgE = CtorArg.getAs<Expr>();
4260     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4261     ExprResult MemberInit =
4262         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4263     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4264     if (MemberInit.isInvalid())
4265       return true;
4266 
4267     if (Indirect)
4268       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4269           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4270     else
4271       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4272           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4273     return false;
4274   }
4275 
4276   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4277          "Unhandled implicit init kind!");
4278 
4279   QualType FieldBaseElementType =
4280     SemaRef.Context.getBaseElementType(Field->getType());
4281 
4282   if (FieldBaseElementType->isRecordType()) {
4283     InitializedEntity InitEntity =
4284         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4285                                                        /*Implicit*/ true)
4286                  : InitializedEntity::InitializeMember(Field, nullptr,
4287                                                        /*Implicit*/ true);
4288     InitializationKind InitKind =
4289       InitializationKind::CreateDefault(Loc);
4290 
4291     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4292     ExprResult MemberInit =
4293       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4294 
4295     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4296     if (MemberInit.isInvalid())
4297       return true;
4298 
4299     if (Indirect)
4300       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4301                                                                Indirect, Loc,
4302                                                                Loc,
4303                                                                MemberInit.get(),
4304                                                                Loc);
4305     else
4306       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4307                                                                Field, Loc, Loc,
4308                                                                MemberInit.get(),
4309                                                                Loc);
4310     return false;
4311   }
4312 
4313   if (!Field->getParent()->isUnion()) {
4314     if (FieldBaseElementType->isReferenceType()) {
4315       SemaRef.Diag(Constructor->getLocation(),
4316                    diag::err_uninitialized_member_in_ctor)
4317       << (int)Constructor->isImplicit()
4318       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4319       << 0 << Field->getDeclName();
4320       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4321       return true;
4322     }
4323 
4324     if (FieldBaseElementType.isConstQualified()) {
4325       SemaRef.Diag(Constructor->getLocation(),
4326                    diag::err_uninitialized_member_in_ctor)
4327       << (int)Constructor->isImplicit()
4328       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4329       << 1 << Field->getDeclName();
4330       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4331       return true;
4332     }
4333   }
4334 
4335   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
4336       FieldBaseElementType->isObjCRetainableType() &&
4337       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4338       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
4339     // ARC:
4340     //   Default-initialize Objective-C pointers to NULL.
4341     CXXMemberInit
4342       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4343                                                  Loc, Loc,
4344                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4345                                                  Loc);
4346     return false;
4347   }
4348 
4349   // Nothing to initialize.
4350   CXXMemberInit = nullptr;
4351   return false;
4352 }
4353 
4354 namespace {
4355 struct BaseAndFieldInfo {
4356   Sema &S;
4357   CXXConstructorDecl *Ctor;
4358   bool AnyErrorsInInits;
4359   ImplicitInitializerKind IIK;
4360   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4361   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4362   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4363 
4364   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4365     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4366     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4367     if (Ctor->getInheritedConstructor())
4368       IIK = IIK_Inherit;
4369     else if (Generated && Ctor->isCopyConstructor())
4370       IIK = IIK_Copy;
4371     else if (Generated && Ctor->isMoveConstructor())
4372       IIK = IIK_Move;
4373     else
4374       IIK = IIK_Default;
4375   }
4376 
4377   bool isImplicitCopyOrMove() const {
4378     switch (IIK) {
4379     case IIK_Copy:
4380     case IIK_Move:
4381       return true;
4382 
4383     case IIK_Default:
4384     case IIK_Inherit:
4385       return false;
4386     }
4387 
4388     llvm_unreachable("Invalid ImplicitInitializerKind!");
4389   }
4390 
4391   bool addFieldInitializer(CXXCtorInitializer *Init) {
4392     AllToInit.push_back(Init);
4393 
4394     // Check whether this initializer makes the field "used".
4395     if (Init->getInit()->HasSideEffects(S.Context))
4396       S.UnusedPrivateFields.remove(Init->getAnyMember());
4397 
4398     return false;
4399   }
4400 
4401   bool isInactiveUnionMember(FieldDecl *Field) {
4402     RecordDecl *Record = Field->getParent();
4403     if (!Record->isUnion())
4404       return false;
4405 
4406     if (FieldDecl *Active =
4407             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4408       return Active != Field->getCanonicalDecl();
4409 
4410     // In an implicit copy or move constructor, ignore any in-class initializer.
4411     if (isImplicitCopyOrMove())
4412       return true;
4413 
4414     // If there's no explicit initialization, the field is active only if it
4415     // has an in-class initializer...
4416     if (Field->hasInClassInitializer())
4417       return false;
4418     // ... or it's an anonymous struct or union whose class has an in-class
4419     // initializer.
4420     if (!Field->isAnonymousStructOrUnion())
4421       return true;
4422     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4423     return !FieldRD->hasInClassInitializer();
4424   }
4425 
4426   /// \brief Determine whether the given field is, or is within, a union member
4427   /// that is inactive (because there was an initializer given for a different
4428   /// member of the union, or because the union was not initialized at all).
4429   bool isWithinInactiveUnionMember(FieldDecl *Field,
4430                                    IndirectFieldDecl *Indirect) {
4431     if (!Indirect)
4432       return isInactiveUnionMember(Field);
4433 
4434     for (auto *C : Indirect->chain()) {
4435       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4436       if (Field && isInactiveUnionMember(Field))
4437         return true;
4438     }
4439     return false;
4440   }
4441 };
4442 }
4443 
4444 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4445 /// array type.
4446 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4447   if (T->isIncompleteArrayType())
4448     return true;
4449 
4450   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4451     if (!ArrayT->getSize())
4452       return true;
4453 
4454     T = ArrayT->getElementType();
4455   }
4456 
4457   return false;
4458 }
4459 
4460 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4461                                     FieldDecl *Field,
4462                                     IndirectFieldDecl *Indirect = nullptr) {
4463   if (Field->isInvalidDecl())
4464     return false;
4465 
4466   // Overwhelmingly common case: we have a direct initializer for this field.
4467   if (CXXCtorInitializer *Init =
4468           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4469     return Info.addFieldInitializer(Init);
4470 
4471   // C++11 [class.base.init]p8:
4472   //   if the entity is a non-static data member that has a
4473   //   brace-or-equal-initializer and either
4474   //   -- the constructor's class is a union and no other variant member of that
4475   //      union is designated by a mem-initializer-id or
4476   //   -- the constructor's class is not a union, and, if the entity is a member
4477   //      of an anonymous union, no other member of that union is designated by
4478   //      a mem-initializer-id,
4479   //   the entity is initialized as specified in [dcl.init].
4480   //
4481   // We also apply the same rules to handle anonymous structs within anonymous
4482   // unions.
4483   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4484     return false;
4485 
4486   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4487     ExprResult DIE =
4488         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4489     if (DIE.isInvalid())
4490       return true;
4491     CXXCtorInitializer *Init;
4492     if (Indirect)
4493       Init = new (SemaRef.Context)
4494           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4495                              SourceLocation(), DIE.get(), SourceLocation());
4496     else
4497       Init = new (SemaRef.Context)
4498           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4499                              SourceLocation(), DIE.get(), SourceLocation());
4500     return Info.addFieldInitializer(Init);
4501   }
4502 
4503   // Don't initialize incomplete or zero-length arrays.
4504   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4505     return false;
4506 
4507   // Don't try to build an implicit initializer if there were semantic
4508   // errors in any of the initializers (and therefore we might be
4509   // missing some that the user actually wrote).
4510   if (Info.AnyErrorsInInits)
4511     return false;
4512 
4513   CXXCtorInitializer *Init = nullptr;
4514   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4515                                      Indirect, Init))
4516     return true;
4517 
4518   if (!Init)
4519     return false;
4520 
4521   return Info.addFieldInitializer(Init);
4522 }
4523 
4524 bool
4525 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4526                                CXXCtorInitializer *Initializer) {
4527   assert(Initializer->isDelegatingInitializer());
4528   Constructor->setNumCtorInitializers(1);
4529   CXXCtorInitializer **initializer =
4530     new (Context) CXXCtorInitializer*[1];
4531   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4532   Constructor->setCtorInitializers(initializer);
4533 
4534   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4535     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4536     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4537   }
4538 
4539   DelegatingCtorDecls.push_back(Constructor);
4540 
4541   DiagnoseUninitializedFields(*this, Constructor);
4542 
4543   return false;
4544 }
4545 
4546 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4547                                ArrayRef<CXXCtorInitializer *> Initializers) {
4548   if (Constructor->isDependentContext()) {
4549     // Just store the initializers as written, they will be checked during
4550     // instantiation.
4551     if (!Initializers.empty()) {
4552       Constructor->setNumCtorInitializers(Initializers.size());
4553       CXXCtorInitializer **baseOrMemberInitializers =
4554         new (Context) CXXCtorInitializer*[Initializers.size()];
4555       memcpy(baseOrMemberInitializers, Initializers.data(),
4556              Initializers.size() * sizeof(CXXCtorInitializer*));
4557       Constructor->setCtorInitializers(baseOrMemberInitializers);
4558     }
4559 
4560     // Let template instantiation know whether we had errors.
4561     if (AnyErrors)
4562       Constructor->setInvalidDecl();
4563 
4564     return false;
4565   }
4566 
4567   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4568 
4569   // We need to build the initializer AST according to order of construction
4570   // and not what user specified in the Initializers list.
4571   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4572   if (!ClassDecl)
4573     return true;
4574 
4575   bool HadError = false;
4576 
4577   for (unsigned i = 0; i < Initializers.size(); i++) {
4578     CXXCtorInitializer *Member = Initializers[i];
4579 
4580     if (Member->isBaseInitializer())
4581       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4582     else {
4583       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4584 
4585       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4586         for (auto *C : F->chain()) {
4587           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4588           if (FD && FD->getParent()->isUnion())
4589             Info.ActiveUnionMember.insert(std::make_pair(
4590                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4591         }
4592       } else if (FieldDecl *FD = Member->getMember()) {
4593         if (FD->getParent()->isUnion())
4594           Info.ActiveUnionMember.insert(std::make_pair(
4595               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4596       }
4597     }
4598   }
4599 
4600   // Keep track of the direct virtual bases.
4601   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4602   for (auto &I : ClassDecl->bases()) {
4603     if (I.isVirtual())
4604       DirectVBases.insert(&I);
4605   }
4606 
4607   // Push virtual bases before others.
4608   for (auto &VBase : ClassDecl->vbases()) {
4609     if (CXXCtorInitializer *Value
4610         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4611       // [class.base.init]p7, per DR257:
4612       //   A mem-initializer where the mem-initializer-id names a virtual base
4613       //   class is ignored during execution of a constructor of any class that
4614       //   is not the most derived class.
4615       if (ClassDecl->isAbstract()) {
4616         // FIXME: Provide a fixit to remove the base specifier. This requires
4617         // tracking the location of the associated comma for a base specifier.
4618         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4619           << VBase.getType() << ClassDecl;
4620         DiagnoseAbstractType(ClassDecl);
4621       }
4622 
4623       Info.AllToInit.push_back(Value);
4624     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4625       // [class.base.init]p8, per DR257:
4626       //   If a given [...] base class is not named by a mem-initializer-id
4627       //   [...] and the entity is not a virtual base class of an abstract
4628       //   class, then [...] the entity is default-initialized.
4629       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4630       CXXCtorInitializer *CXXBaseInit;
4631       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4632                                        &VBase, IsInheritedVirtualBase,
4633                                        CXXBaseInit)) {
4634         HadError = true;
4635         continue;
4636       }
4637 
4638       Info.AllToInit.push_back(CXXBaseInit);
4639     }
4640   }
4641 
4642   // Non-virtual bases.
4643   for (auto &Base : ClassDecl->bases()) {
4644     // Virtuals are in the virtual base list and already constructed.
4645     if (Base.isVirtual())
4646       continue;
4647 
4648     if (CXXCtorInitializer *Value
4649           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4650       Info.AllToInit.push_back(Value);
4651     } else if (!AnyErrors) {
4652       CXXCtorInitializer *CXXBaseInit;
4653       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4654                                        &Base, /*IsInheritedVirtualBase=*/false,
4655                                        CXXBaseInit)) {
4656         HadError = true;
4657         continue;
4658       }
4659 
4660       Info.AllToInit.push_back(CXXBaseInit);
4661     }
4662   }
4663 
4664   // Fields.
4665   for (auto *Mem : ClassDecl->decls()) {
4666     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4667       // C++ [class.bit]p2:
4668       //   A declaration for a bit-field that omits the identifier declares an
4669       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4670       //   initialized.
4671       if (F->isUnnamedBitfield())
4672         continue;
4673 
4674       // If we're not generating the implicit copy/move constructor, then we'll
4675       // handle anonymous struct/union fields based on their individual
4676       // indirect fields.
4677       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4678         continue;
4679 
4680       if (CollectFieldInitializer(*this, Info, F))
4681         HadError = true;
4682       continue;
4683     }
4684 
4685     // Beyond this point, we only consider default initialization.
4686     if (Info.isImplicitCopyOrMove())
4687       continue;
4688 
4689     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4690       if (F->getType()->isIncompleteArrayType()) {
4691         assert(ClassDecl->hasFlexibleArrayMember() &&
4692                "Incomplete array type is not valid");
4693         continue;
4694       }
4695 
4696       // Initialize each field of an anonymous struct individually.
4697       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4698         HadError = true;
4699 
4700       continue;
4701     }
4702   }
4703 
4704   unsigned NumInitializers = Info.AllToInit.size();
4705   if (NumInitializers > 0) {
4706     Constructor->setNumCtorInitializers(NumInitializers);
4707     CXXCtorInitializer **baseOrMemberInitializers =
4708       new (Context) CXXCtorInitializer*[NumInitializers];
4709     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4710            NumInitializers * sizeof(CXXCtorInitializer*));
4711     Constructor->setCtorInitializers(baseOrMemberInitializers);
4712 
4713     // Constructors implicitly reference the base and member
4714     // destructors.
4715     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4716                                            Constructor->getParent());
4717   }
4718 
4719   return HadError;
4720 }
4721 
4722 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4723   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4724     const RecordDecl *RD = RT->getDecl();
4725     if (RD->isAnonymousStructOrUnion()) {
4726       for (auto *Field : RD->fields())
4727         PopulateKeysForFields(Field, IdealInits);
4728       return;
4729     }
4730   }
4731   IdealInits.push_back(Field->getCanonicalDecl());
4732 }
4733 
4734 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4735   return Context.getCanonicalType(BaseType).getTypePtr();
4736 }
4737 
4738 static const void *GetKeyForMember(ASTContext &Context,
4739                                    CXXCtorInitializer *Member) {
4740   if (!Member->isAnyMemberInitializer())
4741     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4742 
4743   return Member->getAnyMember()->getCanonicalDecl();
4744 }
4745 
4746 static void DiagnoseBaseOrMemInitializerOrder(
4747     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4748     ArrayRef<CXXCtorInitializer *> Inits) {
4749   if (Constructor->getDeclContext()->isDependentContext())
4750     return;
4751 
4752   // Don't check initializers order unless the warning is enabled at the
4753   // location of at least one initializer.
4754   bool ShouldCheckOrder = false;
4755   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4756     CXXCtorInitializer *Init = Inits[InitIndex];
4757     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4758                                  Init->getSourceLocation())) {
4759       ShouldCheckOrder = true;
4760       break;
4761     }
4762   }
4763   if (!ShouldCheckOrder)
4764     return;
4765 
4766   // Build the list of bases and members in the order that they'll
4767   // actually be initialized.  The explicit initializers should be in
4768   // this same order but may be missing things.
4769   SmallVector<const void*, 32> IdealInitKeys;
4770 
4771   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4772 
4773   // 1. Virtual bases.
4774   for (const auto &VBase : ClassDecl->vbases())
4775     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4776 
4777   // 2. Non-virtual bases.
4778   for (const auto &Base : ClassDecl->bases()) {
4779     if (Base.isVirtual())
4780       continue;
4781     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4782   }
4783 
4784   // 3. Direct fields.
4785   for (auto *Field : ClassDecl->fields()) {
4786     if (Field->isUnnamedBitfield())
4787       continue;
4788 
4789     PopulateKeysForFields(Field, IdealInitKeys);
4790   }
4791 
4792   unsigned NumIdealInits = IdealInitKeys.size();
4793   unsigned IdealIndex = 0;
4794 
4795   CXXCtorInitializer *PrevInit = nullptr;
4796   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4797     CXXCtorInitializer *Init = Inits[InitIndex];
4798     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4799 
4800     // Scan forward to try to find this initializer in the idealized
4801     // initializers list.
4802     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4803       if (InitKey == IdealInitKeys[IdealIndex])
4804         break;
4805 
4806     // If we didn't find this initializer, it must be because we
4807     // scanned past it on a previous iteration.  That can only
4808     // happen if we're out of order;  emit a warning.
4809     if (IdealIndex == NumIdealInits && PrevInit) {
4810       Sema::SemaDiagnosticBuilder D =
4811         SemaRef.Diag(PrevInit->getSourceLocation(),
4812                      diag::warn_initializer_out_of_order);
4813 
4814       if (PrevInit->isAnyMemberInitializer())
4815         D << 0 << PrevInit->getAnyMember()->getDeclName();
4816       else
4817         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4818 
4819       if (Init->isAnyMemberInitializer())
4820         D << 0 << Init->getAnyMember()->getDeclName();
4821       else
4822         D << 1 << Init->getTypeSourceInfo()->getType();
4823 
4824       // Move back to the initializer's location in the ideal list.
4825       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4826         if (InitKey == IdealInitKeys[IdealIndex])
4827           break;
4828 
4829       assert(IdealIndex < NumIdealInits &&
4830              "initializer not found in initializer list");
4831     }
4832 
4833     PrevInit = Init;
4834   }
4835 }
4836 
4837 namespace {
4838 bool CheckRedundantInit(Sema &S,
4839                         CXXCtorInitializer *Init,
4840                         CXXCtorInitializer *&PrevInit) {
4841   if (!PrevInit) {
4842     PrevInit = Init;
4843     return false;
4844   }
4845 
4846   if (FieldDecl *Field = Init->getAnyMember())
4847     S.Diag(Init->getSourceLocation(),
4848            diag::err_multiple_mem_initialization)
4849       << Field->getDeclName()
4850       << Init->getSourceRange();
4851   else {
4852     const Type *BaseClass = Init->getBaseClass();
4853     assert(BaseClass && "neither field nor base");
4854     S.Diag(Init->getSourceLocation(),
4855            diag::err_multiple_base_initialization)
4856       << QualType(BaseClass, 0)
4857       << Init->getSourceRange();
4858   }
4859   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4860     << 0 << PrevInit->getSourceRange();
4861 
4862   return true;
4863 }
4864 
4865 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4866 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4867 
4868 bool CheckRedundantUnionInit(Sema &S,
4869                              CXXCtorInitializer *Init,
4870                              RedundantUnionMap &Unions) {
4871   FieldDecl *Field = Init->getAnyMember();
4872   RecordDecl *Parent = Field->getParent();
4873   NamedDecl *Child = Field;
4874 
4875   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4876     if (Parent->isUnion()) {
4877       UnionEntry &En = Unions[Parent];
4878       if (En.first && En.first != Child) {
4879         S.Diag(Init->getSourceLocation(),
4880                diag::err_multiple_mem_union_initialization)
4881           << Field->getDeclName()
4882           << Init->getSourceRange();
4883         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4884           << 0 << En.second->getSourceRange();
4885         return true;
4886       }
4887       if (!En.first) {
4888         En.first = Child;
4889         En.second = Init;
4890       }
4891       if (!Parent->isAnonymousStructOrUnion())
4892         return false;
4893     }
4894 
4895     Child = Parent;
4896     Parent = cast<RecordDecl>(Parent->getDeclContext());
4897   }
4898 
4899   return false;
4900 }
4901 }
4902 
4903 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4904 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4905                                 SourceLocation ColonLoc,
4906                                 ArrayRef<CXXCtorInitializer*> MemInits,
4907                                 bool AnyErrors) {
4908   if (!ConstructorDecl)
4909     return;
4910 
4911   AdjustDeclIfTemplate(ConstructorDecl);
4912 
4913   CXXConstructorDecl *Constructor
4914     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4915 
4916   if (!Constructor) {
4917     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4918     return;
4919   }
4920 
4921   // Mapping for the duplicate initializers check.
4922   // For member initializers, this is keyed with a FieldDecl*.
4923   // For base initializers, this is keyed with a Type*.
4924   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4925 
4926   // Mapping for the inconsistent anonymous-union initializers check.
4927   RedundantUnionMap MemberUnions;
4928 
4929   bool HadError = false;
4930   for (unsigned i = 0; i < MemInits.size(); i++) {
4931     CXXCtorInitializer *Init = MemInits[i];
4932 
4933     // Set the source order index.
4934     Init->setSourceOrder(i);
4935 
4936     if (Init->isAnyMemberInitializer()) {
4937       const void *Key = GetKeyForMember(Context, Init);
4938       if (CheckRedundantInit(*this, Init, Members[Key]) ||
4939           CheckRedundantUnionInit(*this, Init, MemberUnions))
4940         HadError = true;
4941     } else if (Init->isBaseInitializer()) {
4942       const void *Key = GetKeyForMember(Context, Init);
4943       if (CheckRedundantInit(*this, Init, Members[Key]))
4944         HadError = true;
4945     } else {
4946       assert(Init->isDelegatingInitializer());
4947       // This must be the only initializer
4948       if (MemInits.size() != 1) {
4949         Diag(Init->getSourceLocation(),
4950              diag::err_delegating_initializer_alone)
4951           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
4952         // We will treat this as being the only initializer.
4953       }
4954       SetDelegatingInitializer(Constructor, MemInits[i]);
4955       // Return immediately as the initializer is set.
4956       return;
4957     }
4958   }
4959 
4960   if (HadError)
4961     return;
4962 
4963   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
4964 
4965   SetCtorInitializers(Constructor, AnyErrors, MemInits);
4966 
4967   DiagnoseUninitializedFields(*this, Constructor);
4968 }
4969 
4970 void
4971 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4972                                              CXXRecordDecl *ClassDecl) {
4973   // Ignore dependent contexts. Also ignore unions, since their members never
4974   // have destructors implicitly called.
4975   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
4976     return;
4977 
4978   // FIXME: all the access-control diagnostics are positioned on the
4979   // field/base declaration.  That's probably good; that said, the
4980   // user might reasonably want to know why the destructor is being
4981   // emitted, and we currently don't say.
4982 
4983   // Non-static data members.
4984   for (auto *Field : ClassDecl->fields()) {
4985     if (Field->isInvalidDecl())
4986       continue;
4987 
4988     // Don't destroy incomplete or zero-length arrays.
4989     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4990       continue;
4991 
4992     QualType FieldType = Context.getBaseElementType(Field->getType());
4993 
4994     const RecordType* RT = FieldType->getAs<RecordType>();
4995     if (!RT)
4996       continue;
4997 
4998     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
4999     if (FieldClassDecl->isInvalidDecl())
5000       continue;
5001     if (FieldClassDecl->hasIrrelevantDestructor())
5002       continue;
5003     // The destructor for an implicit anonymous union member is never invoked.
5004     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5005       continue;
5006 
5007     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5008     assert(Dtor && "No dtor found for FieldClassDecl!");
5009     CheckDestructorAccess(Field->getLocation(), Dtor,
5010                           PDiag(diag::err_access_dtor_field)
5011                             << Field->getDeclName()
5012                             << FieldType);
5013 
5014     MarkFunctionReferenced(Location, Dtor);
5015     DiagnoseUseOfDecl(Dtor, Location);
5016   }
5017 
5018   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5019 
5020   // Bases.
5021   for (const auto &Base : ClassDecl->bases()) {
5022     // Bases are always records in a well-formed non-dependent class.
5023     const RecordType *RT = Base.getType()->getAs<RecordType>();
5024 
5025     // Remember direct virtual bases.
5026     if (Base.isVirtual())
5027       DirectVirtualBases.insert(RT);
5028 
5029     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5030     // If our base class is invalid, we probably can't get its dtor anyway.
5031     if (BaseClassDecl->isInvalidDecl())
5032       continue;
5033     if (BaseClassDecl->hasIrrelevantDestructor())
5034       continue;
5035 
5036     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5037     assert(Dtor && "No dtor found for BaseClassDecl!");
5038 
5039     // FIXME: caret should be on the start of the class name
5040     CheckDestructorAccess(Base.getLocStart(), Dtor,
5041                           PDiag(diag::err_access_dtor_base)
5042                             << Base.getType()
5043                             << Base.getSourceRange(),
5044                           Context.getTypeDeclType(ClassDecl));
5045 
5046     MarkFunctionReferenced(Location, Dtor);
5047     DiagnoseUseOfDecl(Dtor, Location);
5048   }
5049 
5050   // Virtual bases.
5051   for (const auto &VBase : ClassDecl->vbases()) {
5052     // Bases are always records in a well-formed non-dependent class.
5053     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5054 
5055     // Ignore direct virtual bases.
5056     if (DirectVirtualBases.count(RT))
5057       continue;
5058 
5059     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5060     // If our base class is invalid, we probably can't get its dtor anyway.
5061     if (BaseClassDecl->isInvalidDecl())
5062       continue;
5063     if (BaseClassDecl->hasIrrelevantDestructor())
5064       continue;
5065 
5066     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5067     assert(Dtor && "No dtor found for BaseClassDecl!");
5068     if (CheckDestructorAccess(
5069             ClassDecl->getLocation(), Dtor,
5070             PDiag(diag::err_access_dtor_vbase)
5071                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5072             Context.getTypeDeclType(ClassDecl)) ==
5073         AR_accessible) {
5074       CheckDerivedToBaseConversion(
5075           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5076           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5077           SourceRange(), DeclarationName(), nullptr);
5078     }
5079 
5080     MarkFunctionReferenced(Location, Dtor);
5081     DiagnoseUseOfDecl(Dtor, Location);
5082   }
5083 }
5084 
5085 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5086   if (!CDtorDecl)
5087     return;
5088 
5089   if (CXXConstructorDecl *Constructor
5090       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5091     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5092     DiagnoseUninitializedFields(*this, Constructor);
5093   }
5094 }
5095 
5096 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5097   if (!getLangOpts().CPlusPlus)
5098     return false;
5099 
5100   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5101   if (!RD)
5102     return false;
5103 
5104   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5105   // class template specialization here, but doing so breaks a lot of code.
5106 
5107   // We can't answer whether something is abstract until it has a
5108   // definition. If it's currently being defined, we'll walk back
5109   // over all the declarations when we have a full definition.
5110   const CXXRecordDecl *Def = RD->getDefinition();
5111   if (!Def || Def->isBeingDefined())
5112     return false;
5113 
5114   return RD->isAbstract();
5115 }
5116 
5117 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5118                                   TypeDiagnoser &Diagnoser) {
5119   if (!isAbstractType(Loc, T))
5120     return false;
5121 
5122   T = Context.getBaseElementType(T);
5123   Diagnoser.diagnose(*this, Loc, T);
5124   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5125   return true;
5126 }
5127 
5128 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5129   // Check if we've already emitted the list of pure virtual functions
5130   // for this class.
5131   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5132     return;
5133 
5134   // If the diagnostic is suppressed, don't emit the notes. We're only
5135   // going to emit them once, so try to attach them to a diagnostic we're
5136   // actually going to show.
5137   if (Diags.isLastDiagnosticIgnored())
5138     return;
5139 
5140   CXXFinalOverriderMap FinalOverriders;
5141   RD->getFinalOverriders(FinalOverriders);
5142 
5143   // Keep a set of seen pure methods so we won't diagnose the same method
5144   // more than once.
5145   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5146 
5147   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5148                                    MEnd = FinalOverriders.end();
5149        M != MEnd;
5150        ++M) {
5151     for (OverridingMethods::iterator SO = M->second.begin(),
5152                                   SOEnd = M->second.end();
5153          SO != SOEnd; ++SO) {
5154       // C++ [class.abstract]p4:
5155       //   A class is abstract if it contains or inherits at least one
5156       //   pure virtual function for which the final overrider is pure
5157       //   virtual.
5158 
5159       //
5160       if (SO->second.size() != 1)
5161         continue;
5162 
5163       if (!SO->second.front().Method->isPure())
5164         continue;
5165 
5166       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5167         continue;
5168 
5169       Diag(SO->second.front().Method->getLocation(),
5170            diag::note_pure_virtual_function)
5171         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5172     }
5173   }
5174 
5175   if (!PureVirtualClassDiagSet)
5176     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5177   PureVirtualClassDiagSet->insert(RD);
5178 }
5179 
5180 namespace {
5181 struct AbstractUsageInfo {
5182   Sema &S;
5183   CXXRecordDecl *Record;
5184   CanQualType AbstractType;
5185   bool Invalid;
5186 
5187   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5188     : S(S), Record(Record),
5189       AbstractType(S.Context.getCanonicalType(
5190                    S.Context.getTypeDeclType(Record))),
5191       Invalid(false) {}
5192 
5193   void DiagnoseAbstractType() {
5194     if (Invalid) return;
5195     S.DiagnoseAbstractType(Record);
5196     Invalid = true;
5197   }
5198 
5199   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5200 };
5201 
5202 struct CheckAbstractUsage {
5203   AbstractUsageInfo &Info;
5204   const NamedDecl *Ctx;
5205 
5206   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5207     : Info(Info), Ctx(Ctx) {}
5208 
5209   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5210     switch (TL.getTypeLocClass()) {
5211 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5212 #define TYPELOC(CLASS, PARENT) \
5213     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5214 #include "clang/AST/TypeLocNodes.def"
5215     }
5216   }
5217 
5218   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5219     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5220     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5221       if (!TL.getParam(I))
5222         continue;
5223 
5224       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5225       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5226     }
5227   }
5228 
5229   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5230     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5231   }
5232 
5233   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5234     // Visit the type parameters from a permissive context.
5235     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5236       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5237       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5238         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5239           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5240       // TODO: other template argument types?
5241     }
5242   }
5243 
5244   // Visit pointee types from a permissive context.
5245 #define CheckPolymorphic(Type) \
5246   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5247     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5248   }
5249   CheckPolymorphic(PointerTypeLoc)
5250   CheckPolymorphic(ReferenceTypeLoc)
5251   CheckPolymorphic(MemberPointerTypeLoc)
5252   CheckPolymorphic(BlockPointerTypeLoc)
5253   CheckPolymorphic(AtomicTypeLoc)
5254 
5255   /// Handle all the types we haven't given a more specific
5256   /// implementation for above.
5257   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5258     // Every other kind of type that we haven't called out already
5259     // that has an inner type is either (1) sugar or (2) contains that
5260     // inner type in some way as a subobject.
5261     if (TypeLoc Next = TL.getNextTypeLoc())
5262       return Visit(Next, Sel);
5263 
5264     // If there's no inner type and we're in a permissive context,
5265     // don't diagnose.
5266     if (Sel == Sema::AbstractNone) return;
5267 
5268     // Check whether the type matches the abstract type.
5269     QualType T = TL.getType();
5270     if (T->isArrayType()) {
5271       Sel = Sema::AbstractArrayType;
5272       T = Info.S.Context.getBaseElementType(T);
5273     }
5274     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5275     if (CT != Info.AbstractType) return;
5276 
5277     // It matched; do some magic.
5278     if (Sel == Sema::AbstractArrayType) {
5279       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5280         << T << TL.getSourceRange();
5281     } else {
5282       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5283         << Sel << T << TL.getSourceRange();
5284     }
5285     Info.DiagnoseAbstractType();
5286   }
5287 };
5288 
5289 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5290                                   Sema::AbstractDiagSelID Sel) {
5291   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5292 }
5293 
5294 }
5295 
5296 /// Check for invalid uses of an abstract type in a method declaration.
5297 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5298                                     CXXMethodDecl *MD) {
5299   // No need to do the check on definitions, which require that
5300   // the return/param types be complete.
5301   if (MD->doesThisDeclarationHaveABody())
5302     return;
5303 
5304   // For safety's sake, just ignore it if we don't have type source
5305   // information.  This should never happen for non-implicit methods,
5306   // but...
5307   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5308     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5309 }
5310 
5311 /// Check for invalid uses of an abstract type within a class definition.
5312 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5313                                     CXXRecordDecl *RD) {
5314   for (auto *D : RD->decls()) {
5315     if (D->isImplicit()) continue;
5316 
5317     // Methods and method templates.
5318     if (isa<CXXMethodDecl>(D)) {
5319       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5320     } else if (isa<FunctionTemplateDecl>(D)) {
5321       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5322       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5323 
5324     // Fields and static variables.
5325     } else if (isa<FieldDecl>(D)) {
5326       FieldDecl *FD = cast<FieldDecl>(D);
5327       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5328         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5329     } else if (isa<VarDecl>(D)) {
5330       VarDecl *VD = cast<VarDecl>(D);
5331       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5332         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5333 
5334     // Nested classes and class templates.
5335     } else if (isa<CXXRecordDecl>(D)) {
5336       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5337     } else if (isa<ClassTemplateDecl>(D)) {
5338       CheckAbstractClassUsage(Info,
5339                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5340     }
5341   }
5342 }
5343 
5344 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5345   Attr *ClassAttr = getDLLAttr(Class);
5346   if (!ClassAttr)
5347     return;
5348 
5349   assert(ClassAttr->getKind() == attr::DLLExport);
5350 
5351   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5352 
5353   if (TSK == TSK_ExplicitInstantiationDeclaration)
5354     // Don't go any further if this is just an explicit instantiation
5355     // declaration.
5356     return;
5357 
5358   for (Decl *Member : Class->decls()) {
5359     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5360     if (!MD)
5361       continue;
5362 
5363     if (Member->getAttr<DLLExportAttr>()) {
5364       if (MD->isUserProvided()) {
5365         // Instantiate non-default class member functions ...
5366 
5367         // .. except for certain kinds of template specializations.
5368         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5369           continue;
5370 
5371         S.MarkFunctionReferenced(Class->getLocation(), MD);
5372 
5373         // The function will be passed to the consumer when its definition is
5374         // encountered.
5375       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5376                  MD->isCopyAssignmentOperator() ||
5377                  MD->isMoveAssignmentOperator()) {
5378         // Synthesize and instantiate non-trivial implicit methods, explicitly
5379         // defaulted methods, and the copy and move assignment operators. The
5380         // latter are exported even if they are trivial, because the address of
5381         // an operator can be taken and should compare equal accross libraries.
5382         DiagnosticErrorTrap Trap(S.Diags);
5383         S.MarkFunctionReferenced(Class->getLocation(), MD);
5384         if (Trap.hasErrorOccurred()) {
5385           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5386               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5387           break;
5388         }
5389 
5390         // There is no later point when we will see the definition of this
5391         // function, so pass it to the consumer now.
5392         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5393       }
5394     }
5395   }
5396 }
5397 
5398 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5399                                                         CXXRecordDecl *Class) {
5400   // Only the MS ABI has default constructor closures, so we don't need to do
5401   // this semantic checking anywhere else.
5402   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5403     return;
5404 
5405   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5406   for (Decl *Member : Class->decls()) {
5407     // Look for exported default constructors.
5408     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5409     if (!CD || !CD->isDefaultConstructor())
5410       continue;
5411     auto *Attr = CD->getAttr<DLLExportAttr>();
5412     if (!Attr)
5413       continue;
5414 
5415     // If the class is non-dependent, mark the default arguments as ODR-used so
5416     // that we can properly codegen the constructor closure.
5417     if (!Class->isDependentContext()) {
5418       for (ParmVarDecl *PD : CD->parameters()) {
5419         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5420         S.DiscardCleanupsInEvaluationContext();
5421       }
5422     }
5423 
5424     if (LastExportedDefaultCtor) {
5425       S.Diag(LastExportedDefaultCtor->getLocation(),
5426              diag::err_attribute_dll_ambiguous_default_ctor)
5427           << Class;
5428       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5429           << CD->getDeclName();
5430       return;
5431     }
5432     LastExportedDefaultCtor = CD;
5433   }
5434 }
5435 
5436 /// \brief Check class-level dllimport/dllexport attribute.
5437 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5438   Attr *ClassAttr = getDLLAttr(Class);
5439 
5440   // MSVC inherits DLL attributes to partial class template specializations.
5441   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5442     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5443       if (Attr *TemplateAttr =
5444               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5445         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5446         A->setInherited(true);
5447         ClassAttr = A;
5448       }
5449     }
5450   }
5451 
5452   if (!ClassAttr)
5453     return;
5454 
5455   if (!Class->isExternallyVisible()) {
5456     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5457         << Class << ClassAttr;
5458     return;
5459   }
5460 
5461   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5462       !ClassAttr->isInherited()) {
5463     // Diagnose dll attributes on members of class with dll attribute.
5464     for (Decl *Member : Class->decls()) {
5465       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5466         continue;
5467       InheritableAttr *MemberAttr = getDLLAttr(Member);
5468       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5469         continue;
5470 
5471       Diag(MemberAttr->getLocation(),
5472              diag::err_attribute_dll_member_of_dll_class)
5473           << MemberAttr << ClassAttr;
5474       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5475       Member->setInvalidDecl();
5476     }
5477   }
5478 
5479   if (Class->getDescribedClassTemplate())
5480     // Don't inherit dll attribute until the template is instantiated.
5481     return;
5482 
5483   // The class is either imported or exported.
5484   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5485 
5486   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5487 
5488   // Ignore explicit dllexport on explicit class template instantiation declarations.
5489   if (ClassExported && !ClassAttr->isInherited() &&
5490       TSK == TSK_ExplicitInstantiationDeclaration) {
5491     Class->dropAttr<DLLExportAttr>();
5492     return;
5493   }
5494 
5495   // Force declaration of implicit members so they can inherit the attribute.
5496   ForceDeclarationOfImplicitMembers(Class);
5497 
5498   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5499   // seem to be true in practice?
5500 
5501   for (Decl *Member : Class->decls()) {
5502     VarDecl *VD = dyn_cast<VarDecl>(Member);
5503     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5504 
5505     // Only methods and static fields inherit the attributes.
5506     if (!VD && !MD)
5507       continue;
5508 
5509     if (MD) {
5510       // Don't process deleted methods.
5511       if (MD->isDeleted())
5512         continue;
5513 
5514       if (MD->isInlined()) {
5515         // MinGW does not import or export inline methods.
5516         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5517             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5518           continue;
5519 
5520         // MSVC versions before 2015 don't export the move assignment operators
5521         // and move constructor, so don't attempt to import/export them if
5522         // we have a definition.
5523         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5524         if ((MD->isMoveAssignmentOperator() ||
5525              (Ctor && Ctor->isMoveConstructor())) &&
5526             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5527           continue;
5528 
5529         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5530         // operator is exported anyway.
5531         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5532             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5533           continue;
5534       }
5535     }
5536 
5537     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5538       continue;
5539 
5540     if (!getDLLAttr(Member)) {
5541       auto *NewAttr =
5542           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5543       NewAttr->setInherited(true);
5544       Member->addAttr(NewAttr);
5545     }
5546   }
5547 
5548   if (ClassExported)
5549     DelayedDllExportClasses.push_back(Class);
5550 }
5551 
5552 /// \brief Perform propagation of DLL attributes from a derived class to a
5553 /// templated base class for MS compatibility.
5554 void Sema::propagateDLLAttrToBaseClassTemplate(
5555     CXXRecordDecl *Class, Attr *ClassAttr,
5556     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5557   if (getDLLAttr(
5558           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5559     // If the base class template has a DLL attribute, don't try to change it.
5560     return;
5561   }
5562 
5563   auto TSK = BaseTemplateSpec->getSpecializationKind();
5564   if (!getDLLAttr(BaseTemplateSpec) &&
5565       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5566        TSK == TSK_ImplicitInstantiation)) {
5567     // The template hasn't been instantiated yet (or it has, but only as an
5568     // explicit instantiation declaration or implicit instantiation, which means
5569     // we haven't codegenned any members yet), so propagate the attribute.
5570     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5571     NewAttr->setInherited(true);
5572     BaseTemplateSpec->addAttr(NewAttr);
5573 
5574     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5575     // needs to be run again to work see the new attribute. Otherwise this will
5576     // get run whenever the template is instantiated.
5577     if (TSK != TSK_Undeclared)
5578       checkClassLevelDLLAttribute(BaseTemplateSpec);
5579 
5580     return;
5581   }
5582 
5583   if (getDLLAttr(BaseTemplateSpec)) {
5584     // The template has already been specialized or instantiated with an
5585     // attribute, explicitly or through propagation. We should not try to change
5586     // it.
5587     return;
5588   }
5589 
5590   // The template was previously instantiated or explicitly specialized without
5591   // a dll attribute, It's too late for us to add an attribute, so warn that
5592   // this is unsupported.
5593   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5594       << BaseTemplateSpec->isExplicitSpecialization();
5595   Diag(ClassAttr->getLocation(), diag::note_attribute);
5596   if (BaseTemplateSpec->isExplicitSpecialization()) {
5597     Diag(BaseTemplateSpec->getLocation(),
5598            diag::note_template_class_explicit_specialization_was_here)
5599         << BaseTemplateSpec;
5600   } else {
5601     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5602            diag::note_template_class_instantiation_was_here)
5603         << BaseTemplateSpec;
5604   }
5605 }
5606 
5607 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5608                                         SourceLocation DefaultLoc) {
5609   switch (S.getSpecialMember(MD)) {
5610   case Sema::CXXDefaultConstructor:
5611     S.DefineImplicitDefaultConstructor(DefaultLoc,
5612                                        cast<CXXConstructorDecl>(MD));
5613     break;
5614   case Sema::CXXCopyConstructor:
5615     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5616     break;
5617   case Sema::CXXCopyAssignment:
5618     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5619     break;
5620   case Sema::CXXDestructor:
5621     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5622     break;
5623   case Sema::CXXMoveConstructor:
5624     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5625     break;
5626   case Sema::CXXMoveAssignment:
5627     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5628     break;
5629   case Sema::CXXInvalid:
5630     llvm_unreachable("Invalid special member.");
5631   }
5632 }
5633 
5634 /// \brief Perform semantic checks on a class definition that has been
5635 /// completing, introducing implicitly-declared members, checking for
5636 /// abstract types, etc.
5637 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5638   if (!Record)
5639     return;
5640 
5641   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5642     AbstractUsageInfo Info(*this, Record);
5643     CheckAbstractClassUsage(Info, Record);
5644   }
5645 
5646   // If this is not an aggregate type and has no user-declared constructor,
5647   // complain about any non-static data members of reference or const scalar
5648   // type, since they will never get initializers.
5649   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5650       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5651       !Record->isLambda()) {
5652     bool Complained = false;
5653     for (const auto *F : Record->fields()) {
5654       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5655         continue;
5656 
5657       if (F->getType()->isReferenceType() ||
5658           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5659         if (!Complained) {
5660           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5661             << Record->getTagKind() << Record;
5662           Complained = true;
5663         }
5664 
5665         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5666           << F->getType()->isReferenceType()
5667           << F->getDeclName();
5668       }
5669     }
5670   }
5671 
5672   if (Record->getIdentifier()) {
5673     // C++ [class.mem]p13:
5674     //   If T is the name of a class, then each of the following shall have a
5675     //   name different from T:
5676     //     - every member of every anonymous union that is a member of class T.
5677     //
5678     // C++ [class.mem]p14:
5679     //   In addition, if class T has a user-declared constructor (12.1), every
5680     //   non-static data member of class T shall have a name different from T.
5681     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5682     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5683          ++I) {
5684       NamedDecl *D = *I;
5685       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5686           isa<IndirectFieldDecl>(D)) {
5687         Diag(D->getLocation(), diag::err_member_name_of_class)
5688           << D->getDeclName();
5689         break;
5690       }
5691     }
5692   }
5693 
5694   // Warn if the class has virtual methods but non-virtual public destructor.
5695   if (Record->isPolymorphic() && !Record->isDependentType()) {
5696     CXXDestructorDecl *dtor = Record->getDestructor();
5697     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5698         !Record->hasAttr<FinalAttr>())
5699       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5700            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5701   }
5702 
5703   if (Record->isAbstract()) {
5704     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5705       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5706         << FA->isSpelledAsSealed();
5707       DiagnoseAbstractType(Record);
5708     }
5709   }
5710 
5711   bool HasMethodWithOverrideControl = false,
5712        HasOverridingMethodWithoutOverrideControl = false;
5713   if (!Record->isDependentType()) {
5714     for (auto *M : Record->methods()) {
5715       // See if a method overloads virtual methods in a base
5716       // class without overriding any.
5717       if (!M->isStatic())
5718         DiagnoseHiddenVirtualMethods(M);
5719       if (M->hasAttr<OverrideAttr>())
5720         HasMethodWithOverrideControl = true;
5721       else if (M->size_overridden_methods() > 0)
5722         HasOverridingMethodWithoutOverrideControl = true;
5723       // Check whether the explicitly-defaulted special members are valid.
5724       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5725         CheckExplicitlyDefaultedSpecialMember(M);
5726 
5727       // For an explicitly defaulted or deleted special member, we defer
5728       // determining triviality until the class is complete. That time is now!
5729       CXXSpecialMember CSM = getSpecialMember(M);
5730       if (!M->isImplicit() && !M->isUserProvided()) {
5731         if (CSM != CXXInvalid) {
5732           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5733 
5734           // Inform the class that we've finished declaring this member.
5735           Record->finishedDefaultedOrDeletedMember(M);
5736         }
5737       }
5738 
5739       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5740           M->hasAttr<DLLExportAttr>()) {
5741         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5742             M->isTrivial() &&
5743             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5744              CSM == CXXDestructor))
5745           M->dropAttr<DLLExportAttr>();
5746 
5747         if (M->hasAttr<DLLExportAttr>()) {
5748           DefineImplicitSpecialMember(*this, M, M->getLocation());
5749           ActOnFinishInlineFunctionDef(M);
5750         }
5751       }
5752     }
5753   }
5754 
5755   if (HasMethodWithOverrideControl &&
5756       HasOverridingMethodWithoutOverrideControl) {
5757     // At least one method has the 'override' control declared.
5758     // Diagnose all other overridden methods which do not have 'override' specified on them.
5759     for (auto *M : Record->methods())
5760       DiagnoseAbsenceOfOverrideControl(M);
5761   }
5762 
5763   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5764   // whether this class uses any C++ features that are implemented
5765   // completely differently in MSVC, and if so, emit a diagnostic.
5766   // That diagnostic defaults to an error, but we allow projects to
5767   // map it down to a warning (or ignore it).  It's a fairly common
5768   // practice among users of the ms_struct pragma to mass-annotate
5769   // headers, sweeping up a bunch of types that the project doesn't
5770   // really rely on MSVC-compatible layout for.  We must therefore
5771   // support "ms_struct except for C++ stuff" as a secondary ABI.
5772   if (Record->isMsStruct(Context) &&
5773       (Record->isPolymorphic() || Record->getNumBases())) {
5774     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5775   }
5776 
5777   checkClassLevelDLLAttribute(Record);
5778 }
5779 
5780 /// Look up the special member function that would be called by a special
5781 /// member function for a subobject of class type.
5782 ///
5783 /// \param Class The class type of the subobject.
5784 /// \param CSM The kind of special member function.
5785 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5786 /// \param ConstRHS True if this is a copy operation with a const object
5787 ///        on its RHS, that is, if the argument to the outer special member
5788 ///        function is 'const' and this is not a field marked 'mutable'.
5789 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5790     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5791     unsigned FieldQuals, bool ConstRHS) {
5792   unsigned LHSQuals = 0;
5793   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5794     LHSQuals = FieldQuals;
5795 
5796   unsigned RHSQuals = FieldQuals;
5797   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5798     RHSQuals = 0;
5799   else if (ConstRHS)
5800     RHSQuals |= Qualifiers::Const;
5801 
5802   return S.LookupSpecialMember(Class, CSM,
5803                                RHSQuals & Qualifiers::Const,
5804                                RHSQuals & Qualifiers::Volatile,
5805                                false,
5806                                LHSQuals & Qualifiers::Const,
5807                                LHSQuals & Qualifiers::Volatile);
5808 }
5809 
5810 class Sema::InheritedConstructorInfo {
5811   Sema &S;
5812   SourceLocation UseLoc;
5813 
5814   /// A mapping from the base classes through which the constructor was
5815   /// inherited to the using shadow declaration in that base class (or a null
5816   /// pointer if the constructor was declared in that base class).
5817   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5818       InheritedFromBases;
5819 
5820 public:
5821   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5822                            ConstructorUsingShadowDecl *Shadow)
5823       : S(S), UseLoc(UseLoc) {
5824     bool DiagnosedMultipleConstructedBases = false;
5825     CXXRecordDecl *ConstructedBase = nullptr;
5826     UsingDecl *ConstructedBaseUsing = nullptr;
5827 
5828     // Find the set of such base class subobjects and check that there's a
5829     // unique constructed subobject.
5830     for (auto *D : Shadow->redecls()) {
5831       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5832       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5833       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5834 
5835       InheritedFromBases.insert(
5836           std::make_pair(DNominatedBase->getCanonicalDecl(),
5837                          DShadow->getNominatedBaseClassShadowDecl()));
5838       if (DShadow->constructsVirtualBase())
5839         InheritedFromBases.insert(
5840             std::make_pair(DConstructedBase->getCanonicalDecl(),
5841                            DShadow->getConstructedBaseClassShadowDecl()));
5842       else
5843         assert(DNominatedBase == DConstructedBase);
5844 
5845       // [class.inhctor.init]p2:
5846       //   If the constructor was inherited from multiple base class subobjects
5847       //   of type B, the program is ill-formed.
5848       if (!ConstructedBase) {
5849         ConstructedBase = DConstructedBase;
5850         ConstructedBaseUsing = D->getUsingDecl();
5851       } else if (ConstructedBase != DConstructedBase &&
5852                  !Shadow->isInvalidDecl()) {
5853         if (!DiagnosedMultipleConstructedBases) {
5854           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5855               << Shadow->getTargetDecl();
5856           S.Diag(ConstructedBaseUsing->getLocation(),
5857                diag::note_ambiguous_inherited_constructor_using)
5858               << ConstructedBase;
5859           DiagnosedMultipleConstructedBases = true;
5860         }
5861         S.Diag(D->getUsingDecl()->getLocation(),
5862                diag::note_ambiguous_inherited_constructor_using)
5863             << DConstructedBase;
5864       }
5865     }
5866 
5867     if (DiagnosedMultipleConstructedBases)
5868       Shadow->setInvalidDecl();
5869   }
5870 
5871   /// Find the constructor to use for inherited construction of a base class,
5872   /// and whether that base class constructor inherits the constructor from a
5873   /// virtual base class (in which case it won't actually invoke it).
5874   std::pair<CXXConstructorDecl *, bool>
5875   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5876     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5877     if (It == InheritedFromBases.end())
5878       return std::make_pair(nullptr, false);
5879 
5880     // This is an intermediary class.
5881     if (It->second)
5882       return std::make_pair(
5883           S.findInheritingConstructor(UseLoc, Ctor, It->second),
5884           It->second->constructsVirtualBase());
5885 
5886     // This is the base class from which the constructor was inherited.
5887     return std::make_pair(Ctor, false);
5888   }
5889 };
5890 
5891 /// Is the special member function which would be selected to perform the
5892 /// specified operation on the specified class type a constexpr constructor?
5893 static bool
5894 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5895                          Sema::CXXSpecialMember CSM, unsigned Quals,
5896                          bool ConstRHS,
5897                          CXXConstructorDecl *InheritedCtor = nullptr,
5898                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
5899   // If we're inheriting a constructor, see if we need to call it for this base
5900   // class.
5901   if (InheritedCtor) {
5902     assert(CSM == Sema::CXXDefaultConstructor);
5903     auto BaseCtor =
5904         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5905     if (BaseCtor)
5906       return BaseCtor->isConstexpr();
5907   }
5908 
5909   if (CSM == Sema::CXXDefaultConstructor)
5910     return ClassDecl->hasConstexprDefaultConstructor();
5911 
5912   Sema::SpecialMemberOverloadResult *SMOR =
5913       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5914   if (!SMOR || !SMOR->getMethod())
5915     // A constructor we wouldn't select can't be "involved in initializing"
5916     // anything.
5917     return true;
5918   return SMOR->getMethod()->isConstexpr();
5919 }
5920 
5921 /// Determine whether the specified special member function would be constexpr
5922 /// if it were implicitly defined.
5923 static bool defaultedSpecialMemberIsConstexpr(
5924     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5925     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5926     Sema::InheritedConstructorInfo *Inherited = nullptr) {
5927   if (!S.getLangOpts().CPlusPlus11)
5928     return false;
5929 
5930   // C++11 [dcl.constexpr]p4:
5931   // In the definition of a constexpr constructor [...]
5932   bool Ctor = true;
5933   switch (CSM) {
5934   case Sema::CXXDefaultConstructor:
5935     if (Inherited)
5936       break;
5937     // Since default constructor lookup is essentially trivial (and cannot
5938     // involve, for instance, template instantiation), we compute whether a
5939     // defaulted default constructor is constexpr directly within CXXRecordDecl.
5940     //
5941     // This is important for performance; we need to know whether the default
5942     // constructor is constexpr to determine whether the type is a literal type.
5943     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
5944 
5945   case Sema::CXXCopyConstructor:
5946   case Sema::CXXMoveConstructor:
5947     // For copy or move constructors, we need to perform overload resolution.
5948     break;
5949 
5950   case Sema::CXXCopyAssignment:
5951   case Sema::CXXMoveAssignment:
5952     if (!S.getLangOpts().CPlusPlus14)
5953       return false;
5954     // In C++1y, we need to perform overload resolution.
5955     Ctor = false;
5956     break;
5957 
5958   case Sema::CXXDestructor:
5959   case Sema::CXXInvalid:
5960     return false;
5961   }
5962 
5963   //   -- if the class is a non-empty union, or for each non-empty anonymous
5964   //      union member of a non-union class, exactly one non-static data member
5965   //      shall be initialized; [DR1359]
5966   //
5967   // If we squint, this is guaranteed, since exactly one non-static data member
5968   // will be initialized (if the constructor isn't deleted), we just don't know
5969   // which one.
5970   if (Ctor && ClassDecl->isUnion())
5971     return CSM == Sema::CXXDefaultConstructor
5972                ? ClassDecl->hasInClassInitializer() ||
5973                      !ClassDecl->hasVariantMembers()
5974                : true;
5975 
5976   //   -- the class shall not have any virtual base classes;
5977   if (Ctor && ClassDecl->getNumVBases())
5978     return false;
5979 
5980   // C++1y [class.copy]p26:
5981   //   -- [the class] is a literal type, and
5982   if (!Ctor && !ClassDecl->isLiteral())
5983     return false;
5984 
5985   //   -- every constructor involved in initializing [...] base class
5986   //      sub-objects shall be a constexpr constructor;
5987   //   -- the assignment operator selected to copy/move each direct base
5988   //      class is a constexpr function, and
5989   for (const auto &B : ClassDecl->bases()) {
5990     const RecordType *BaseType = B.getType()->getAs<RecordType>();
5991     if (!BaseType) continue;
5992 
5993     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5994     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
5995                                   InheritedCtor, Inherited))
5996       return false;
5997   }
5998 
5999   //   -- every constructor involved in initializing non-static data members
6000   //      [...] shall be a constexpr constructor;
6001   //   -- every non-static data member and base class sub-object shall be
6002   //      initialized
6003   //   -- for each non-static data member of X that is of class type (or array
6004   //      thereof), the assignment operator selected to copy/move that member is
6005   //      a constexpr function
6006   for (const auto *F : ClassDecl->fields()) {
6007     if (F->isInvalidDecl())
6008       continue;
6009     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6010       continue;
6011     QualType BaseType = S.Context.getBaseElementType(F->getType());
6012     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6013       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6014       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6015                                     BaseType.getCVRQualifiers(),
6016                                     ConstArg && !F->isMutable()))
6017         return false;
6018     } else if (CSM == Sema::CXXDefaultConstructor) {
6019       return false;
6020     }
6021   }
6022 
6023   // All OK, it's constexpr!
6024   return true;
6025 }
6026 
6027 static Sema::ImplicitExceptionSpecification
6028 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6029   switch (S.getSpecialMember(MD)) {
6030   case Sema::CXXDefaultConstructor:
6031     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6032   case Sema::CXXCopyConstructor:
6033     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6034   case Sema::CXXCopyAssignment:
6035     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6036   case Sema::CXXMoveConstructor:
6037     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6038   case Sema::CXXMoveAssignment:
6039     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6040   case Sema::CXXDestructor:
6041     return S.ComputeDefaultedDtorExceptionSpec(MD);
6042   case Sema::CXXInvalid:
6043     break;
6044   }
6045   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6046          "only special members have implicit exception specs");
6047   return S.ComputeInheritingCtorExceptionSpec(Loc,
6048                                               cast<CXXConstructorDecl>(MD));
6049 }
6050 
6051 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6052                                                             CXXMethodDecl *MD) {
6053   FunctionProtoType::ExtProtoInfo EPI;
6054 
6055   // Build an exception specification pointing back at this member.
6056   EPI.ExceptionSpec.Type = EST_Unevaluated;
6057   EPI.ExceptionSpec.SourceDecl = MD;
6058 
6059   // Set the calling convention to the default for C++ instance methods.
6060   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6061       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6062                                             /*IsCXXMethod=*/true));
6063   return EPI;
6064 }
6065 
6066 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6067   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6068   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6069     return;
6070 
6071   // Evaluate the exception specification.
6072   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6073   auto ESI = IES.getExceptionSpec();
6074 
6075   // Update the type of the special member to use it.
6076   UpdateExceptionSpec(MD, ESI);
6077 
6078   // A user-provided destructor can be defined outside the class. When that
6079   // happens, be sure to update the exception specification on both
6080   // declarations.
6081   const FunctionProtoType *CanonicalFPT =
6082     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6083   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6084     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6085 }
6086 
6087 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6088   CXXRecordDecl *RD = MD->getParent();
6089   CXXSpecialMember CSM = getSpecialMember(MD);
6090 
6091   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6092          "not an explicitly-defaulted special member");
6093 
6094   // Whether this was the first-declared instance of the constructor.
6095   // This affects whether we implicitly add an exception spec and constexpr.
6096   bool First = MD == MD->getCanonicalDecl();
6097 
6098   bool HadError = false;
6099 
6100   // C++11 [dcl.fct.def.default]p1:
6101   //   A function that is explicitly defaulted shall
6102   //     -- be a special member function (checked elsewhere),
6103   //     -- have the same type (except for ref-qualifiers, and except that a
6104   //        copy operation can take a non-const reference) as an implicit
6105   //        declaration, and
6106   //     -- not have default arguments.
6107   unsigned ExpectedParams = 1;
6108   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6109     ExpectedParams = 0;
6110   if (MD->getNumParams() != ExpectedParams) {
6111     // This also checks for default arguments: a copy or move constructor with a
6112     // default argument is classified as a default constructor, and assignment
6113     // operations and destructors can't have default arguments.
6114     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6115       << CSM << MD->getSourceRange();
6116     HadError = true;
6117   } else if (MD->isVariadic()) {
6118     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6119       << CSM << MD->getSourceRange();
6120     HadError = true;
6121   }
6122 
6123   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6124 
6125   bool CanHaveConstParam = false;
6126   if (CSM == CXXCopyConstructor)
6127     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6128   else if (CSM == CXXCopyAssignment)
6129     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6130 
6131   QualType ReturnType = Context.VoidTy;
6132   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6133     // Check for return type matching.
6134     ReturnType = Type->getReturnType();
6135     QualType ExpectedReturnType =
6136         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6137     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6138       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6139         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6140       HadError = true;
6141     }
6142 
6143     // A defaulted special member cannot have cv-qualifiers.
6144     if (Type->getTypeQuals()) {
6145       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6146         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6147       HadError = true;
6148     }
6149   }
6150 
6151   // Check for parameter type matching.
6152   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6153   bool HasConstParam = false;
6154   if (ExpectedParams && ArgType->isReferenceType()) {
6155     // Argument must be reference to possibly-const T.
6156     QualType ReferentType = ArgType->getPointeeType();
6157     HasConstParam = ReferentType.isConstQualified();
6158 
6159     if (ReferentType.isVolatileQualified()) {
6160       Diag(MD->getLocation(),
6161            diag::err_defaulted_special_member_volatile_param) << CSM;
6162       HadError = true;
6163     }
6164 
6165     if (HasConstParam && !CanHaveConstParam) {
6166       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6167         Diag(MD->getLocation(),
6168              diag::err_defaulted_special_member_copy_const_param)
6169           << (CSM == CXXCopyAssignment);
6170         // FIXME: Explain why this special member can't be const.
6171       } else {
6172         Diag(MD->getLocation(),
6173              diag::err_defaulted_special_member_move_const_param)
6174           << (CSM == CXXMoveAssignment);
6175       }
6176       HadError = true;
6177     }
6178   } else if (ExpectedParams) {
6179     // A copy assignment operator can take its argument by value, but a
6180     // defaulted one cannot.
6181     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6182     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6183     HadError = true;
6184   }
6185 
6186   // C++11 [dcl.fct.def.default]p2:
6187   //   An explicitly-defaulted function may be declared constexpr only if it
6188   //   would have been implicitly declared as constexpr,
6189   // Do not apply this rule to members of class templates, since core issue 1358
6190   // makes such functions always instantiate to constexpr functions. For
6191   // functions which cannot be constexpr (for non-constructors in C++11 and for
6192   // destructors in C++1y), this is checked elsewhere.
6193   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6194                                                      HasConstParam);
6195   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6196                                  : isa<CXXConstructorDecl>(MD)) &&
6197       MD->isConstexpr() && !Constexpr &&
6198       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6199     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6200     // FIXME: Explain why the special member can't be constexpr.
6201     HadError = true;
6202   }
6203 
6204   //   and may have an explicit exception-specification only if it is compatible
6205   //   with the exception-specification on the implicit declaration.
6206   if (Type->hasExceptionSpec()) {
6207     // Delay the check if this is the first declaration of the special member,
6208     // since we may not have parsed some necessary in-class initializers yet.
6209     if (First) {
6210       // If the exception specification needs to be instantiated, do so now,
6211       // before we clobber it with an EST_Unevaluated specification below.
6212       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6213         InstantiateExceptionSpec(MD->getLocStart(), MD);
6214         Type = MD->getType()->getAs<FunctionProtoType>();
6215       }
6216       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6217     } else
6218       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6219   }
6220 
6221   //   If a function is explicitly defaulted on its first declaration,
6222   if (First) {
6223     //  -- it is implicitly considered to be constexpr if the implicit
6224     //     definition would be,
6225     MD->setConstexpr(Constexpr);
6226 
6227     //  -- it is implicitly considered to have the same exception-specification
6228     //     as if it had been implicitly declared,
6229     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6230     EPI.ExceptionSpec.Type = EST_Unevaluated;
6231     EPI.ExceptionSpec.SourceDecl = MD;
6232     MD->setType(Context.getFunctionType(ReturnType,
6233                                         llvm::makeArrayRef(&ArgType,
6234                                                            ExpectedParams),
6235                                         EPI));
6236   }
6237 
6238   if (ShouldDeleteSpecialMember(MD, CSM)) {
6239     if (First) {
6240       SetDeclDeleted(MD, MD->getLocation());
6241     } else {
6242       // C++11 [dcl.fct.def.default]p4:
6243       //   [For a] user-provided explicitly-defaulted function [...] if such a
6244       //   function is implicitly defined as deleted, the program is ill-formed.
6245       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6246       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6247       HadError = true;
6248     }
6249   }
6250 
6251   if (HadError)
6252     MD->setInvalidDecl();
6253 }
6254 
6255 /// Check whether the exception specification provided for an
6256 /// explicitly-defaulted special member matches the exception specification
6257 /// that would have been generated for an implicit special member, per
6258 /// C++11 [dcl.fct.def.default]p2.
6259 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6260     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6261   // If the exception specification was explicitly specified but hadn't been
6262   // parsed when the method was defaulted, grab it now.
6263   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6264     SpecifiedType =
6265         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6266 
6267   // Compute the implicit exception specification.
6268   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6269                                                        /*IsCXXMethod=*/true);
6270   FunctionProtoType::ExtProtoInfo EPI(CC);
6271   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6272   EPI.ExceptionSpec = IES.getExceptionSpec();
6273   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6274     Context.getFunctionType(Context.VoidTy, None, EPI));
6275 
6276   // Ensure that it matches.
6277   CheckEquivalentExceptionSpec(
6278     PDiag(diag::err_incorrect_defaulted_exception_spec)
6279       << getSpecialMember(MD), PDiag(),
6280     ImplicitType, SourceLocation(),
6281     SpecifiedType, MD->getLocation());
6282 }
6283 
6284 void Sema::CheckDelayedMemberExceptionSpecs() {
6285   decltype(DelayedExceptionSpecChecks) Checks;
6286   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6287 
6288   std::swap(Checks, DelayedExceptionSpecChecks);
6289   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6290 
6291   // Perform any deferred checking of exception specifications for virtual
6292   // destructors.
6293   for (auto &Check : Checks)
6294     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6295 
6296   // Check that any explicitly-defaulted methods have exception specifications
6297   // compatible with their implicit exception specifications.
6298   for (auto &Spec : Specs)
6299     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6300 }
6301 
6302 namespace {
6303 struct SpecialMemberDeletionInfo {
6304   Sema &S;
6305   CXXMethodDecl *MD;
6306   Sema::CXXSpecialMember CSM;
6307   Sema::InheritedConstructorInfo *ICI;
6308   bool Diagnose;
6309 
6310   // Properties of the special member, computed for convenience.
6311   bool IsConstructor, IsAssignment, IsMove, ConstArg;
6312   SourceLocation Loc;
6313 
6314   bool AllFieldsAreConst;
6315 
6316   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6317                             Sema::CXXSpecialMember CSM,
6318                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6319       : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6320         IsConstructor(false), IsAssignment(false), IsMove(false),
6321         ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
6322     switch (CSM) {
6323       case Sema::CXXDefaultConstructor:
6324       case Sema::CXXCopyConstructor:
6325         IsConstructor = true;
6326         break;
6327       case Sema::CXXMoveConstructor:
6328         IsConstructor = true;
6329         IsMove = true;
6330         break;
6331       case Sema::CXXCopyAssignment:
6332         IsAssignment = true;
6333         break;
6334       case Sema::CXXMoveAssignment:
6335         IsAssignment = true;
6336         IsMove = true;
6337         break;
6338       case Sema::CXXDestructor:
6339         break;
6340       case Sema::CXXInvalid:
6341         llvm_unreachable("invalid special member kind");
6342     }
6343 
6344     if (MD->getNumParams()) {
6345       if (const ReferenceType *RT =
6346               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6347         ConstArg = RT->getPointeeType().isConstQualified();
6348     }
6349   }
6350 
6351   bool inUnion() const { return MD->getParent()->isUnion(); }
6352 
6353   Sema::CXXSpecialMember getEffectiveCSM() {
6354     return ICI ? Sema::CXXInvalid : CSM;
6355   }
6356 
6357   /// Look up the corresponding special member in the given class.
6358   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
6359                                               unsigned Quals, bool IsMutable) {
6360     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6361                                        ConstArg && !IsMutable);
6362   }
6363 
6364   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6365 
6366   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6367   bool shouldDeleteForField(FieldDecl *FD);
6368   bool shouldDeleteForAllConstMembers();
6369 
6370   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6371                                      unsigned Quals);
6372   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6373                                     Sema::SpecialMemberOverloadResult *SMOR,
6374                                     bool IsDtorCallInCtor);
6375 
6376   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6377 };
6378 }
6379 
6380 /// Is the given special member inaccessible when used on the given
6381 /// sub-object.
6382 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6383                                              CXXMethodDecl *target) {
6384   /// If we're operating on a base class, the object type is the
6385   /// type of this special member.
6386   QualType objectTy;
6387   AccessSpecifier access = target->getAccess();
6388   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6389     objectTy = S.Context.getTypeDeclType(MD->getParent());
6390     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6391 
6392   // If we're operating on a field, the object type is the type of the field.
6393   } else {
6394     objectTy = S.Context.getTypeDeclType(target->getParent());
6395   }
6396 
6397   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6398 }
6399 
6400 /// Check whether we should delete a special member due to the implicit
6401 /// definition containing a call to a special member of a subobject.
6402 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6403     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6404     bool IsDtorCallInCtor) {
6405   CXXMethodDecl *Decl = SMOR->getMethod();
6406   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6407 
6408   int DiagKind = -1;
6409 
6410   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6411     DiagKind = !Decl ? 0 : 1;
6412   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6413     DiagKind = 2;
6414   else if (!isAccessible(Subobj, Decl))
6415     DiagKind = 3;
6416   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6417            !Decl->isTrivial()) {
6418     // A member of a union must have a trivial corresponding special member.
6419     // As a weird special case, a destructor call from a union's constructor
6420     // must be accessible and non-deleted, but need not be trivial. Such a
6421     // destructor is never actually called, but is semantically checked as
6422     // if it were.
6423     DiagKind = 4;
6424   }
6425 
6426   if (DiagKind == -1)
6427     return false;
6428 
6429   if (Diagnose) {
6430     if (Field) {
6431       S.Diag(Field->getLocation(),
6432              diag::note_deleted_special_member_class_subobject)
6433         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6434         << Field << DiagKind << IsDtorCallInCtor;
6435     } else {
6436       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6437       S.Diag(Base->getLocStart(),
6438              diag::note_deleted_special_member_class_subobject)
6439         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6440         << Base->getType() << DiagKind << IsDtorCallInCtor;
6441     }
6442 
6443     if (DiagKind == 1)
6444       S.NoteDeletedFunction(Decl);
6445     // FIXME: Explain inaccessibility if DiagKind == 3.
6446   }
6447 
6448   return true;
6449 }
6450 
6451 /// Check whether we should delete a special member function due to having a
6452 /// direct or virtual base class or non-static data member of class type M.
6453 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6454     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6455   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6456   bool IsMutable = Field && Field->isMutable();
6457 
6458   // C++11 [class.ctor]p5:
6459   // -- any direct or virtual base class, or non-static data member with no
6460   //    brace-or-equal-initializer, has class type M (or array thereof) and
6461   //    either M has no default constructor or overload resolution as applied
6462   //    to M's default constructor results in an ambiguity or in a function
6463   //    that is deleted or inaccessible
6464   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6465   // -- a direct or virtual base class B that cannot be copied/moved because
6466   //    overload resolution, as applied to B's corresponding special member,
6467   //    results in an ambiguity or a function that is deleted or inaccessible
6468   //    from the defaulted special member
6469   // C++11 [class.dtor]p5:
6470   // -- any direct or virtual base class [...] has a type with a destructor
6471   //    that is deleted or inaccessible
6472   if (!(CSM == Sema::CXXDefaultConstructor &&
6473         Field && Field->hasInClassInitializer()) &&
6474       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6475                                    false))
6476     return true;
6477 
6478   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6479   // -- any direct or virtual base class or non-static data member has a
6480   //    type with a destructor that is deleted or inaccessible
6481   if (IsConstructor) {
6482     Sema::SpecialMemberOverloadResult *SMOR =
6483         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6484                               false, false, false, false, false);
6485     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6486       return true;
6487   }
6488 
6489   return false;
6490 }
6491 
6492 /// Check whether we should delete a special member function due to the class
6493 /// having a particular direct or virtual base class.
6494 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6495   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6496   // If program is correct, BaseClass cannot be null, but if it is, the error
6497   // must be reported elsewhere.
6498   if (!BaseClass)
6499     return false;
6500   // If we have an inheriting constructor, check whether we're calling an
6501   // inherited constructor instead of a default constructor.
6502   if (ICI) {
6503     assert(CSM == Sema::CXXDefaultConstructor);
6504     auto *BaseCtor =
6505         ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6506                                                    ->getInheritedConstructor()
6507                                                    .getConstructor())
6508             .first;
6509     if (BaseCtor) {
6510       if (BaseCtor->isDeleted() && Diagnose) {
6511         S.Diag(Base->getLocStart(),
6512                diag::note_deleted_special_member_class_subobject)
6513           << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6514           << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6515         S.NoteDeletedFunction(BaseCtor);
6516       }
6517       return BaseCtor->isDeleted();
6518     }
6519   }
6520   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6521 }
6522 
6523 /// Check whether we should delete a special member function due to the class
6524 /// having a particular non-static data member.
6525 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6526   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6527   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6528 
6529   if (CSM == Sema::CXXDefaultConstructor) {
6530     // For a default constructor, all references must be initialized in-class
6531     // and, if a union, it must have a non-const member.
6532     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6533       if (Diagnose)
6534         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6535           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6536       return true;
6537     }
6538     // C++11 [class.ctor]p5: any non-variant non-static data member of
6539     // const-qualified type (or array thereof) with no
6540     // brace-or-equal-initializer does not have a user-provided default
6541     // constructor.
6542     if (!inUnion() && FieldType.isConstQualified() &&
6543         !FD->hasInClassInitializer() &&
6544         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6545       if (Diagnose)
6546         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6547           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6548       return true;
6549     }
6550 
6551     if (inUnion() && !FieldType.isConstQualified())
6552       AllFieldsAreConst = false;
6553   } else if (CSM == Sema::CXXCopyConstructor) {
6554     // For a copy constructor, data members must not be of rvalue reference
6555     // type.
6556     if (FieldType->isRValueReferenceType()) {
6557       if (Diagnose)
6558         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6559           << MD->getParent() << FD << FieldType;
6560       return true;
6561     }
6562   } else if (IsAssignment) {
6563     // For an assignment operator, data members must not be of reference type.
6564     if (FieldType->isReferenceType()) {
6565       if (Diagnose)
6566         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6567           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
6568       return true;
6569     }
6570     if (!FieldRecord && FieldType.isConstQualified()) {
6571       // C++11 [class.copy]p23:
6572       // -- a non-static data member of const non-class type (or array thereof)
6573       if (Diagnose)
6574         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6575           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
6576       return true;
6577     }
6578   }
6579 
6580   if (FieldRecord) {
6581     // Some additional restrictions exist on the variant members.
6582     if (!inUnion() && FieldRecord->isUnion() &&
6583         FieldRecord->isAnonymousStructOrUnion()) {
6584       bool AllVariantFieldsAreConst = true;
6585 
6586       // FIXME: Handle anonymous unions declared within anonymous unions.
6587       for (auto *UI : FieldRecord->fields()) {
6588         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6589 
6590         if (!UnionFieldType.isConstQualified())
6591           AllVariantFieldsAreConst = false;
6592 
6593         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6594         if (UnionFieldRecord &&
6595             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6596                                           UnionFieldType.getCVRQualifiers()))
6597           return true;
6598       }
6599 
6600       // At least one member in each anonymous union must be non-const
6601       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6602           !FieldRecord->field_empty()) {
6603         if (Diagnose)
6604           S.Diag(FieldRecord->getLocation(),
6605                  diag::note_deleted_default_ctor_all_const)
6606             << !!ICI << MD->getParent() << /*anonymous union*/1;
6607         return true;
6608       }
6609 
6610       // Don't check the implicit member of the anonymous union type.
6611       // This is technically non-conformant, but sanity demands it.
6612       return false;
6613     }
6614 
6615     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6616                                       FieldType.getCVRQualifiers()))
6617       return true;
6618   }
6619 
6620   return false;
6621 }
6622 
6623 /// C++11 [class.ctor] p5:
6624 ///   A defaulted default constructor for a class X is defined as deleted if
6625 /// X is a union and all of its variant members are of const-qualified type.
6626 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6627   // This is a silly definition, because it gives an empty union a deleted
6628   // default constructor. Don't do that.
6629   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6630     bool AnyFields = false;
6631     for (auto *F : MD->getParent()->fields())
6632       if ((AnyFields = !F->isUnnamedBitfield()))
6633         break;
6634     if (!AnyFields)
6635       return false;
6636     if (Diagnose)
6637       S.Diag(MD->getParent()->getLocation(),
6638              diag::note_deleted_default_ctor_all_const)
6639         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6640     return true;
6641   }
6642   return false;
6643 }
6644 
6645 /// Determine whether a defaulted special member function should be defined as
6646 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6647 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6648 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6649                                      InheritedConstructorInfo *ICI,
6650                                      bool Diagnose) {
6651   if (MD->isInvalidDecl())
6652     return false;
6653   CXXRecordDecl *RD = MD->getParent();
6654   assert(!RD->isDependentType() && "do deletion after instantiation");
6655   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6656     return false;
6657 
6658   // C++11 [expr.lambda.prim]p19:
6659   //   The closure type associated with a lambda-expression has a
6660   //   deleted (8.4.3) default constructor and a deleted copy
6661   //   assignment operator.
6662   if (RD->isLambda() &&
6663       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6664     if (Diagnose)
6665       Diag(RD->getLocation(), diag::note_lambda_decl);
6666     return true;
6667   }
6668 
6669   // For an anonymous struct or union, the copy and assignment special members
6670   // will never be used, so skip the check. For an anonymous union declared at
6671   // namespace scope, the constructor and destructor are used.
6672   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6673       RD->isAnonymousStructOrUnion())
6674     return false;
6675 
6676   // C++11 [class.copy]p7, p18:
6677   //   If the class definition declares a move constructor or move assignment
6678   //   operator, an implicitly declared copy constructor or copy assignment
6679   //   operator is defined as deleted.
6680   if (MD->isImplicit() &&
6681       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6682     CXXMethodDecl *UserDeclaredMove = nullptr;
6683 
6684     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6685     // deletion of the corresponding copy operation, not both copy operations.
6686     // MSVC 2015 has adopted the standards conforming behavior.
6687     bool DeletesOnlyMatchingCopy =
6688         getLangOpts().MSVCCompat &&
6689         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6690 
6691     if (RD->hasUserDeclaredMoveConstructor() &&
6692         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6693       if (!Diagnose) return true;
6694 
6695       // Find any user-declared move constructor.
6696       for (auto *I : RD->ctors()) {
6697         if (I->isMoveConstructor()) {
6698           UserDeclaredMove = I;
6699           break;
6700         }
6701       }
6702       assert(UserDeclaredMove);
6703     } else if (RD->hasUserDeclaredMoveAssignment() &&
6704                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6705       if (!Diagnose) return true;
6706 
6707       // Find any user-declared move assignment operator.
6708       for (auto *I : RD->methods()) {
6709         if (I->isMoveAssignmentOperator()) {
6710           UserDeclaredMove = I;
6711           break;
6712         }
6713       }
6714       assert(UserDeclaredMove);
6715     }
6716 
6717     if (UserDeclaredMove) {
6718       Diag(UserDeclaredMove->getLocation(),
6719            diag::note_deleted_copy_user_declared_move)
6720         << (CSM == CXXCopyAssignment) << RD
6721         << UserDeclaredMove->isMoveAssignmentOperator();
6722       return true;
6723     }
6724   }
6725 
6726   // Do access control from the special member function
6727   ContextRAII MethodContext(*this, MD);
6728 
6729   // C++11 [class.dtor]p5:
6730   // -- for a virtual destructor, lookup of the non-array deallocation function
6731   //    results in an ambiguity or in a function that is deleted or inaccessible
6732   if (CSM == CXXDestructor && MD->isVirtual()) {
6733     FunctionDecl *OperatorDelete = nullptr;
6734     DeclarationName Name =
6735       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6736     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6737                                  OperatorDelete, /*Diagnose*/false)) {
6738       if (Diagnose)
6739         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6740       return true;
6741     }
6742   }
6743 
6744   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6745 
6746   for (auto &BI : RD->bases())
6747     if ((SMI.IsAssignment || !BI.isVirtual()) &&
6748         SMI.shouldDeleteForBase(&BI))
6749       return true;
6750 
6751   // Per DR1611, do not consider virtual bases of constructors of abstract
6752   // classes, since we are not going to construct them. For assignment
6753   // operators, we only assign (and thus only consider) direct bases.
6754   if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
6755     for (auto &BI : RD->vbases())
6756       if (SMI.shouldDeleteForBase(&BI))
6757         return true;
6758   }
6759 
6760   for (auto *FI : RD->fields())
6761     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6762         SMI.shouldDeleteForField(FI))
6763       return true;
6764 
6765   if (SMI.shouldDeleteForAllConstMembers())
6766     return true;
6767 
6768   if (getLangOpts().CUDA) {
6769     // We should delete the special member in CUDA mode if target inference
6770     // failed.
6771     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6772                                                    Diagnose);
6773   }
6774 
6775   return false;
6776 }
6777 
6778 /// Perform lookup for a special member of the specified kind, and determine
6779 /// whether it is trivial. If the triviality can be determined without the
6780 /// lookup, skip it. This is intended for use when determining whether a
6781 /// special member of a containing object is trivial, and thus does not ever
6782 /// perform overload resolution for default constructors.
6783 ///
6784 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6785 /// member that was most likely to be intended to be trivial, if any.
6786 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6787                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6788                                      bool ConstRHS, CXXMethodDecl **Selected) {
6789   if (Selected)
6790     *Selected = nullptr;
6791 
6792   switch (CSM) {
6793   case Sema::CXXInvalid:
6794     llvm_unreachable("not a special member");
6795 
6796   case Sema::CXXDefaultConstructor:
6797     // C++11 [class.ctor]p5:
6798     //   A default constructor is trivial if:
6799     //    - all the [direct subobjects] have trivial default constructors
6800     //
6801     // Note, no overload resolution is performed in this case.
6802     if (RD->hasTrivialDefaultConstructor())
6803       return true;
6804 
6805     if (Selected) {
6806       // If there's a default constructor which could have been trivial, dig it
6807       // out. Otherwise, if there's any user-provided default constructor, point
6808       // to that as an example of why there's not a trivial one.
6809       CXXConstructorDecl *DefCtor = nullptr;
6810       if (RD->needsImplicitDefaultConstructor())
6811         S.DeclareImplicitDefaultConstructor(RD);
6812       for (auto *CI : RD->ctors()) {
6813         if (!CI->isDefaultConstructor())
6814           continue;
6815         DefCtor = CI;
6816         if (!DefCtor->isUserProvided())
6817           break;
6818       }
6819 
6820       *Selected = DefCtor;
6821     }
6822 
6823     return false;
6824 
6825   case Sema::CXXDestructor:
6826     // C++11 [class.dtor]p5:
6827     //   A destructor is trivial if:
6828     //    - all the direct [subobjects] have trivial destructors
6829     if (RD->hasTrivialDestructor())
6830       return true;
6831 
6832     if (Selected) {
6833       if (RD->needsImplicitDestructor())
6834         S.DeclareImplicitDestructor(RD);
6835       *Selected = RD->getDestructor();
6836     }
6837 
6838     return false;
6839 
6840   case Sema::CXXCopyConstructor:
6841     // C++11 [class.copy]p12:
6842     //   A copy constructor is trivial if:
6843     //    - the constructor selected to copy each direct [subobject] is trivial
6844     if (RD->hasTrivialCopyConstructor()) {
6845       if (Quals == Qualifiers::Const)
6846         // We must either select the trivial copy constructor or reach an
6847         // ambiguity; no need to actually perform overload resolution.
6848         return true;
6849     } else if (!Selected) {
6850       return false;
6851     }
6852     // In C++98, we are not supposed to perform overload resolution here, but we
6853     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6854     // cases like B as having a non-trivial copy constructor:
6855     //   struct A { template<typename T> A(T&); };
6856     //   struct B { mutable A a; };
6857     goto NeedOverloadResolution;
6858 
6859   case Sema::CXXCopyAssignment:
6860     // C++11 [class.copy]p25:
6861     //   A copy assignment operator is trivial if:
6862     //    - the assignment operator selected to copy each direct [subobject] is
6863     //      trivial
6864     if (RD->hasTrivialCopyAssignment()) {
6865       if (Quals == Qualifiers::Const)
6866         return true;
6867     } else if (!Selected) {
6868       return false;
6869     }
6870     // In C++98, we are not supposed to perform overload resolution here, but we
6871     // treat that as a language defect.
6872     goto NeedOverloadResolution;
6873 
6874   case Sema::CXXMoveConstructor:
6875   case Sema::CXXMoveAssignment:
6876   NeedOverloadResolution:
6877     Sema::SpecialMemberOverloadResult *SMOR =
6878         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6879 
6880     // The standard doesn't describe how to behave if the lookup is ambiguous.
6881     // We treat it as not making the member non-trivial, just like the standard
6882     // mandates for the default constructor. This should rarely matter, because
6883     // the member will also be deleted.
6884     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6885       return true;
6886 
6887     if (!SMOR->getMethod()) {
6888       assert(SMOR->getKind() ==
6889              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6890       return false;
6891     }
6892 
6893     // We deliberately don't check if we found a deleted special member. We're
6894     // not supposed to!
6895     if (Selected)
6896       *Selected = SMOR->getMethod();
6897     return SMOR->getMethod()->isTrivial();
6898   }
6899 
6900   llvm_unreachable("unknown special method kind");
6901 }
6902 
6903 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6904   for (auto *CI : RD->ctors())
6905     if (!CI->isImplicit())
6906       return CI;
6907 
6908   // Look for constructor templates.
6909   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6910   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6911     if (CXXConstructorDecl *CD =
6912           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6913       return CD;
6914   }
6915 
6916   return nullptr;
6917 }
6918 
6919 /// The kind of subobject we are checking for triviality. The values of this
6920 /// enumeration are used in diagnostics.
6921 enum TrivialSubobjectKind {
6922   /// The subobject is a base class.
6923   TSK_BaseClass,
6924   /// The subobject is a non-static data member.
6925   TSK_Field,
6926   /// The object is actually the complete object.
6927   TSK_CompleteObject
6928 };
6929 
6930 /// Check whether the special member selected for a given type would be trivial.
6931 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6932                                       QualType SubType, bool ConstRHS,
6933                                       Sema::CXXSpecialMember CSM,
6934                                       TrivialSubobjectKind Kind,
6935                                       bool Diagnose) {
6936   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
6937   if (!SubRD)
6938     return true;
6939 
6940   CXXMethodDecl *Selected;
6941   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
6942                                ConstRHS, Diagnose ? &Selected : nullptr))
6943     return true;
6944 
6945   if (Diagnose) {
6946     if (ConstRHS)
6947       SubType.addConst();
6948 
6949     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
6950       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
6951         << Kind << SubType.getUnqualifiedType();
6952       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
6953         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
6954     } else if (!Selected)
6955       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
6956         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
6957     else if (Selected->isUserProvided()) {
6958       if (Kind == TSK_CompleteObject)
6959         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
6960           << Kind << SubType.getUnqualifiedType() << CSM;
6961       else {
6962         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
6963           << Kind << SubType.getUnqualifiedType() << CSM;
6964         S.Diag(Selected->getLocation(), diag::note_declared_at);
6965       }
6966     } else {
6967       if (Kind != TSK_CompleteObject)
6968         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
6969           << Kind << SubType.getUnqualifiedType() << CSM;
6970 
6971       // Explain why the defaulted or deleted special member isn't trivial.
6972       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
6973     }
6974   }
6975 
6976   return false;
6977 }
6978 
6979 /// Check whether the members of a class type allow a special member to be
6980 /// trivial.
6981 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
6982                                      Sema::CXXSpecialMember CSM,
6983                                      bool ConstArg, bool Diagnose) {
6984   for (const auto *FI : RD->fields()) {
6985     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
6986       continue;
6987 
6988     QualType FieldType = S.Context.getBaseElementType(FI->getType());
6989 
6990     // Pretend anonymous struct or union members are members of this class.
6991     if (FI->isAnonymousStructOrUnion()) {
6992       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
6993                                     CSM, ConstArg, Diagnose))
6994         return false;
6995       continue;
6996     }
6997 
6998     // C++11 [class.ctor]p5:
6999     //   A default constructor is trivial if [...]
7000     //    -- no non-static data member of its class has a
7001     //       brace-or-equal-initializer
7002     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7003       if (Diagnose)
7004         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7005       return false;
7006     }
7007 
7008     // Objective C ARC 4.3.5:
7009     //   [...] nontrivally ownership-qualified types are [...] not trivially
7010     //   default constructible, copy constructible, move constructible, copy
7011     //   assignable, move assignable, or destructible [...]
7012     if (S.getLangOpts().ObjCAutoRefCount &&
7013         FieldType.hasNonTrivialObjCLifetime()) {
7014       if (Diagnose)
7015         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7016           << RD << FieldType.getObjCLifetime();
7017       return false;
7018     }
7019 
7020     bool ConstRHS = ConstArg && !FI->isMutable();
7021     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7022                                    CSM, TSK_Field, Diagnose))
7023       return false;
7024   }
7025 
7026   return true;
7027 }
7028 
7029 /// Diagnose why the specified class does not have a trivial special member of
7030 /// the given kind.
7031 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7032   QualType Ty = Context.getRecordType(RD);
7033 
7034   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7035   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7036                             TSK_CompleteObject, /*Diagnose*/true);
7037 }
7038 
7039 /// Determine whether a defaulted or deleted special member function is trivial,
7040 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7041 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7042 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7043                                   bool Diagnose) {
7044   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7045 
7046   CXXRecordDecl *RD = MD->getParent();
7047 
7048   bool ConstArg = false;
7049 
7050   // C++11 [class.copy]p12, p25: [DR1593]
7051   //   A [special member] is trivial if [...] its parameter-type-list is
7052   //   equivalent to the parameter-type-list of an implicit declaration [...]
7053   switch (CSM) {
7054   case CXXDefaultConstructor:
7055   case CXXDestructor:
7056     // Trivial default constructors and destructors cannot have parameters.
7057     break;
7058 
7059   case CXXCopyConstructor:
7060   case CXXCopyAssignment: {
7061     // Trivial copy operations always have const, non-volatile parameter types.
7062     ConstArg = true;
7063     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7064     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7065     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7066       if (Diagnose)
7067         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7068           << Param0->getSourceRange() << Param0->getType()
7069           << Context.getLValueReferenceType(
7070                Context.getRecordType(RD).withConst());
7071       return false;
7072     }
7073     break;
7074   }
7075 
7076   case CXXMoveConstructor:
7077   case CXXMoveAssignment: {
7078     // Trivial move operations always have non-cv-qualified parameters.
7079     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7080     const RValueReferenceType *RT =
7081       Param0->getType()->getAs<RValueReferenceType>();
7082     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7083       if (Diagnose)
7084         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7085           << Param0->getSourceRange() << Param0->getType()
7086           << Context.getRValueReferenceType(Context.getRecordType(RD));
7087       return false;
7088     }
7089     break;
7090   }
7091 
7092   case CXXInvalid:
7093     llvm_unreachable("not a special member");
7094   }
7095 
7096   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7097     if (Diagnose)
7098       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7099            diag::note_nontrivial_default_arg)
7100         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7101     return false;
7102   }
7103   if (MD->isVariadic()) {
7104     if (Diagnose)
7105       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7106     return false;
7107   }
7108 
7109   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7110   //   A copy/move [constructor or assignment operator] is trivial if
7111   //    -- the [member] selected to copy/move each direct base class subobject
7112   //       is trivial
7113   //
7114   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7115   //   A [default constructor or destructor] is trivial if
7116   //    -- all the direct base classes have trivial [default constructors or
7117   //       destructors]
7118   for (const auto &BI : RD->bases())
7119     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7120                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7121       return false;
7122 
7123   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7124   //   A copy/move [constructor or assignment operator] for a class X is
7125   //   trivial if
7126   //    -- for each non-static data member of X that is of class type (or array
7127   //       thereof), the constructor selected to copy/move that member is
7128   //       trivial
7129   //
7130   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7131   //   A [default constructor or destructor] is trivial if
7132   //    -- for all of the non-static data members of its class that are of class
7133   //       type (or array thereof), each such class has a trivial [default
7134   //       constructor or destructor]
7135   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7136     return false;
7137 
7138   // C++11 [class.dtor]p5:
7139   //   A destructor is trivial if [...]
7140   //    -- the destructor is not virtual
7141   if (CSM == CXXDestructor && MD->isVirtual()) {
7142     if (Diagnose)
7143       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7144     return false;
7145   }
7146 
7147   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7148   //   A [special member] for class X is trivial if [...]
7149   //    -- class X has no virtual functions and no virtual base classes
7150   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7151     if (!Diagnose)
7152       return false;
7153 
7154     if (RD->getNumVBases()) {
7155       // Check for virtual bases. We already know that the corresponding
7156       // member in all bases is trivial, so vbases must all be direct.
7157       CXXBaseSpecifier &BS = *RD->vbases_begin();
7158       assert(BS.isVirtual());
7159       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7160       return false;
7161     }
7162 
7163     // Must have a virtual method.
7164     for (const auto *MI : RD->methods()) {
7165       if (MI->isVirtual()) {
7166         SourceLocation MLoc = MI->getLocStart();
7167         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7168         return false;
7169       }
7170     }
7171 
7172     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7173   }
7174 
7175   // Looks like it's trivial!
7176   return true;
7177 }
7178 
7179 namespace {
7180 struct FindHiddenVirtualMethod {
7181   Sema *S;
7182   CXXMethodDecl *Method;
7183   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7184   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7185 
7186 private:
7187   /// Check whether any most overriden method from MD in Methods
7188   static bool CheckMostOverridenMethods(
7189       const CXXMethodDecl *MD,
7190       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7191     if (MD->size_overridden_methods() == 0)
7192       return Methods.count(MD->getCanonicalDecl());
7193     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7194                                         E = MD->end_overridden_methods();
7195          I != E; ++I)
7196       if (CheckMostOverridenMethods(*I, Methods))
7197         return true;
7198     return false;
7199   }
7200 
7201 public:
7202   /// Member lookup function that determines whether a given C++
7203   /// method overloads virtual methods in a base class without overriding any,
7204   /// to be used with CXXRecordDecl::lookupInBases().
7205   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7206     RecordDecl *BaseRecord =
7207         Specifier->getType()->getAs<RecordType>()->getDecl();
7208 
7209     DeclarationName Name = Method->getDeclName();
7210     assert(Name.getNameKind() == DeclarationName::Identifier);
7211 
7212     bool foundSameNameMethod = false;
7213     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7214     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7215          Path.Decls = Path.Decls.slice(1)) {
7216       NamedDecl *D = Path.Decls.front();
7217       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7218         MD = MD->getCanonicalDecl();
7219         foundSameNameMethod = true;
7220         // Interested only in hidden virtual methods.
7221         if (!MD->isVirtual())
7222           continue;
7223         // If the method we are checking overrides a method from its base
7224         // don't warn about the other overloaded methods. Clang deviates from
7225         // GCC by only diagnosing overloads of inherited virtual functions that
7226         // do not override any other virtual functions in the base. GCC's
7227         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7228         // function from a base class. These cases may be better served by a
7229         // warning (not specific to virtual functions) on call sites when the
7230         // call would select a different function from the base class, were it
7231         // visible.
7232         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7233         if (!S->IsOverload(Method, MD, false))
7234           return true;
7235         // Collect the overload only if its hidden.
7236         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7237           overloadedMethods.push_back(MD);
7238       }
7239     }
7240 
7241     if (foundSameNameMethod)
7242       OverloadedMethods.append(overloadedMethods.begin(),
7243                                overloadedMethods.end());
7244     return foundSameNameMethod;
7245   }
7246 };
7247 } // end anonymous namespace
7248 
7249 /// \brief Add the most overriden methods from MD to Methods
7250 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7251                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7252   if (MD->size_overridden_methods() == 0)
7253     Methods.insert(MD->getCanonicalDecl());
7254   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7255                                       E = MD->end_overridden_methods();
7256        I != E; ++I)
7257     AddMostOverridenMethods(*I, Methods);
7258 }
7259 
7260 /// \brief Check if a method overloads virtual methods in a base class without
7261 /// overriding any.
7262 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7263                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7264   if (!MD->getDeclName().isIdentifier())
7265     return;
7266 
7267   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7268                      /*bool RecordPaths=*/false,
7269                      /*bool DetectVirtual=*/false);
7270   FindHiddenVirtualMethod FHVM;
7271   FHVM.Method = MD;
7272   FHVM.S = this;
7273 
7274   // Keep the base methods that were overriden or introduced in the subclass
7275   // by 'using' in a set. A base method not in this set is hidden.
7276   CXXRecordDecl *DC = MD->getParent();
7277   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7278   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7279     NamedDecl *ND = *I;
7280     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7281       ND = shad->getTargetDecl();
7282     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7283       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7284   }
7285 
7286   if (DC->lookupInBases(FHVM, Paths))
7287     OverloadedMethods = FHVM.OverloadedMethods;
7288 }
7289 
7290 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7291                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7292   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7293     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7294     PartialDiagnostic PD = PDiag(
7295          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7296     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7297     Diag(overloadedMD->getLocation(), PD);
7298   }
7299 }
7300 
7301 /// \brief Diagnose methods which overload virtual methods in a base class
7302 /// without overriding any.
7303 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7304   if (MD->isInvalidDecl())
7305     return;
7306 
7307   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7308     return;
7309 
7310   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7311   FindHiddenVirtualMethods(MD, OverloadedMethods);
7312   if (!OverloadedMethods.empty()) {
7313     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7314       << MD << (OverloadedMethods.size() > 1);
7315 
7316     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7317   }
7318 }
7319 
7320 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7321                                              Decl *TagDecl,
7322                                              SourceLocation LBrac,
7323                                              SourceLocation RBrac,
7324                                              AttributeList *AttrList) {
7325   if (!TagDecl)
7326     return;
7327 
7328   AdjustDeclIfTemplate(TagDecl);
7329 
7330   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7331     if (l->getKind() != AttributeList::AT_Visibility)
7332       continue;
7333     l->setInvalid();
7334     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7335       l->getName();
7336   }
7337 
7338   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7339               // strict aliasing violation!
7340               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7341               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7342 
7343   CheckCompletedCXXClass(
7344                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7345 }
7346 
7347 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7348 /// special functions, such as the default constructor, copy
7349 /// constructor, or destructor, to the given C++ class (C++
7350 /// [special]p1).  This routine can only be executed just before the
7351 /// definition of the class is complete.
7352 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7353   if (ClassDecl->needsImplicitDefaultConstructor()) {
7354     ++ASTContext::NumImplicitDefaultConstructors;
7355 
7356     if (ClassDecl->hasInheritedConstructor())
7357       DeclareImplicitDefaultConstructor(ClassDecl);
7358   }
7359 
7360   if (ClassDecl->needsImplicitCopyConstructor()) {
7361     ++ASTContext::NumImplicitCopyConstructors;
7362 
7363     // If the properties or semantics of the copy constructor couldn't be
7364     // determined while the class was being declared, force a declaration
7365     // of it now.
7366     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7367         ClassDecl->hasInheritedConstructor())
7368       DeclareImplicitCopyConstructor(ClassDecl);
7369     // For the MS ABI we need to know whether the copy ctor is deleted. A
7370     // prerequisite for deleting the implicit copy ctor is that the class has a
7371     // move ctor or move assignment that is either user-declared or whose
7372     // semantics are inherited from a subobject. FIXME: We should provide a more
7373     // direct way for CodeGen to ask whether the constructor was deleted.
7374     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7375              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7376               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7377               ClassDecl->hasUserDeclaredMoveAssignment() ||
7378               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7379       DeclareImplicitCopyConstructor(ClassDecl);
7380   }
7381 
7382   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7383     ++ASTContext::NumImplicitMoveConstructors;
7384 
7385     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7386         ClassDecl->hasInheritedConstructor())
7387       DeclareImplicitMoveConstructor(ClassDecl);
7388   }
7389 
7390   if (ClassDecl->needsImplicitCopyAssignment()) {
7391     ++ASTContext::NumImplicitCopyAssignmentOperators;
7392 
7393     // If we have a dynamic class, then the copy assignment operator may be
7394     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7395     // it shows up in the right place in the vtable and that we diagnose
7396     // problems with the implicit exception specification.
7397     if (ClassDecl->isDynamicClass() ||
7398         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7399         ClassDecl->hasInheritedAssignment())
7400       DeclareImplicitCopyAssignment(ClassDecl);
7401   }
7402 
7403   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7404     ++ASTContext::NumImplicitMoveAssignmentOperators;
7405 
7406     // Likewise for the move assignment operator.
7407     if (ClassDecl->isDynamicClass() ||
7408         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7409         ClassDecl->hasInheritedAssignment())
7410       DeclareImplicitMoveAssignment(ClassDecl);
7411   }
7412 
7413   if (ClassDecl->needsImplicitDestructor()) {
7414     ++ASTContext::NumImplicitDestructors;
7415 
7416     // If we have a dynamic class, then the destructor may be virtual, so we
7417     // have to declare the destructor immediately. This ensures that, e.g., it
7418     // shows up in the right place in the vtable and that we diagnose problems
7419     // with the implicit exception specification.
7420     if (ClassDecl->isDynamicClass() ||
7421         ClassDecl->needsOverloadResolutionForDestructor())
7422       DeclareImplicitDestructor(ClassDecl);
7423   }
7424 }
7425 
7426 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7427   if (!D)
7428     return 0;
7429 
7430   // The order of template parameters is not important here. All names
7431   // get added to the same scope.
7432   SmallVector<TemplateParameterList *, 4> ParameterLists;
7433 
7434   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7435     D = TD->getTemplatedDecl();
7436 
7437   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7438     ParameterLists.push_back(PSD->getTemplateParameters());
7439 
7440   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7441     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7442       ParameterLists.push_back(DD->getTemplateParameterList(i));
7443 
7444     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7445       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7446         ParameterLists.push_back(FTD->getTemplateParameters());
7447     }
7448   }
7449 
7450   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7451     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7452       ParameterLists.push_back(TD->getTemplateParameterList(i));
7453 
7454     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7455       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7456         ParameterLists.push_back(CTD->getTemplateParameters());
7457     }
7458   }
7459 
7460   unsigned Count = 0;
7461   for (TemplateParameterList *Params : ParameterLists) {
7462     if (Params->size() > 0)
7463       // Ignore explicit specializations; they don't contribute to the template
7464       // depth.
7465       ++Count;
7466     for (NamedDecl *Param : *Params) {
7467       if (Param->getDeclName()) {
7468         S->AddDecl(Param);
7469         IdResolver.AddDecl(Param);
7470       }
7471     }
7472   }
7473 
7474   return Count;
7475 }
7476 
7477 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7478   if (!RecordD) return;
7479   AdjustDeclIfTemplate(RecordD);
7480   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7481   PushDeclContext(S, Record);
7482 }
7483 
7484 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7485   if (!RecordD) return;
7486   PopDeclContext();
7487 }
7488 
7489 /// This is used to implement the constant expression evaluation part of the
7490 /// attribute enable_if extension. There is nothing in standard C++ which would
7491 /// require reentering parameters.
7492 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7493   if (!Param)
7494     return;
7495 
7496   S->AddDecl(Param);
7497   if (Param->getDeclName())
7498     IdResolver.AddDecl(Param);
7499 }
7500 
7501 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7502 /// parsing a top-level (non-nested) C++ class, and we are now
7503 /// parsing those parts of the given Method declaration that could
7504 /// not be parsed earlier (C++ [class.mem]p2), such as default
7505 /// arguments. This action should enter the scope of the given
7506 /// Method declaration as if we had just parsed the qualified method
7507 /// name. However, it should not bring the parameters into scope;
7508 /// that will be performed by ActOnDelayedCXXMethodParameter.
7509 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7510 }
7511 
7512 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7513 /// C++ method declaration. We're (re-)introducing the given
7514 /// function parameter into scope for use in parsing later parts of
7515 /// the method declaration. For example, we could see an
7516 /// ActOnParamDefaultArgument event for this parameter.
7517 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7518   if (!ParamD)
7519     return;
7520 
7521   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7522 
7523   // If this parameter has an unparsed default argument, clear it out
7524   // to make way for the parsed default argument.
7525   if (Param->hasUnparsedDefaultArg())
7526     Param->setDefaultArg(nullptr);
7527 
7528   S->AddDecl(Param);
7529   if (Param->getDeclName())
7530     IdResolver.AddDecl(Param);
7531 }
7532 
7533 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7534 /// processing the delayed method declaration for Method. The method
7535 /// declaration is now considered finished. There may be a separate
7536 /// ActOnStartOfFunctionDef action later (not necessarily
7537 /// immediately!) for this method, if it was also defined inside the
7538 /// class body.
7539 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7540   if (!MethodD)
7541     return;
7542 
7543   AdjustDeclIfTemplate(MethodD);
7544 
7545   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7546 
7547   // Now that we have our default arguments, check the constructor
7548   // again. It could produce additional diagnostics or affect whether
7549   // the class has implicitly-declared destructors, among other
7550   // things.
7551   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7552     CheckConstructor(Constructor);
7553 
7554   // Check the default arguments, which we may have added.
7555   if (!Method->isInvalidDecl())
7556     CheckCXXDefaultArguments(Method);
7557 }
7558 
7559 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7560 /// the well-formedness of the constructor declarator @p D with type @p
7561 /// R. If there are any errors in the declarator, this routine will
7562 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7563 /// will be updated to reflect a well-formed type for the constructor and
7564 /// returned.
7565 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7566                                           StorageClass &SC) {
7567   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7568 
7569   // C++ [class.ctor]p3:
7570   //   A constructor shall not be virtual (10.3) or static (9.4). A
7571   //   constructor can be invoked for a const, volatile or const
7572   //   volatile object. A constructor shall not be declared const,
7573   //   volatile, or const volatile (9.3.2).
7574   if (isVirtual) {
7575     if (!D.isInvalidType())
7576       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7577         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7578         << SourceRange(D.getIdentifierLoc());
7579     D.setInvalidType();
7580   }
7581   if (SC == SC_Static) {
7582     if (!D.isInvalidType())
7583       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7584         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7585         << SourceRange(D.getIdentifierLoc());
7586     D.setInvalidType();
7587     SC = SC_None;
7588   }
7589 
7590   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7591     diagnoseIgnoredQualifiers(
7592         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7593         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7594         D.getDeclSpec().getRestrictSpecLoc(),
7595         D.getDeclSpec().getAtomicSpecLoc());
7596     D.setInvalidType();
7597   }
7598 
7599   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7600   if (FTI.TypeQuals != 0) {
7601     if (FTI.TypeQuals & Qualifiers::Const)
7602       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7603         << "const" << SourceRange(D.getIdentifierLoc());
7604     if (FTI.TypeQuals & Qualifiers::Volatile)
7605       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7606         << "volatile" << SourceRange(D.getIdentifierLoc());
7607     if (FTI.TypeQuals & Qualifiers::Restrict)
7608       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7609         << "restrict" << SourceRange(D.getIdentifierLoc());
7610     D.setInvalidType();
7611   }
7612 
7613   // C++0x [class.ctor]p4:
7614   //   A constructor shall not be declared with a ref-qualifier.
7615   if (FTI.hasRefQualifier()) {
7616     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7617       << FTI.RefQualifierIsLValueRef
7618       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7619     D.setInvalidType();
7620   }
7621 
7622   // Rebuild the function type "R" without any type qualifiers (in
7623   // case any of the errors above fired) and with "void" as the
7624   // return type, since constructors don't have return types.
7625   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7626   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7627     return R;
7628 
7629   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7630   EPI.TypeQuals = 0;
7631   EPI.RefQualifier = RQ_None;
7632 
7633   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7634 }
7635 
7636 /// CheckConstructor - Checks a fully-formed constructor for
7637 /// well-formedness, issuing any diagnostics required. Returns true if
7638 /// the constructor declarator is invalid.
7639 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7640   CXXRecordDecl *ClassDecl
7641     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7642   if (!ClassDecl)
7643     return Constructor->setInvalidDecl();
7644 
7645   // C++ [class.copy]p3:
7646   //   A declaration of a constructor for a class X is ill-formed if
7647   //   its first parameter is of type (optionally cv-qualified) X and
7648   //   either there are no other parameters or else all other
7649   //   parameters have default arguments.
7650   if (!Constructor->isInvalidDecl() &&
7651       ((Constructor->getNumParams() == 1) ||
7652        (Constructor->getNumParams() > 1 &&
7653         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7654       Constructor->getTemplateSpecializationKind()
7655                                               != TSK_ImplicitInstantiation) {
7656     QualType ParamType = Constructor->getParamDecl(0)->getType();
7657     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7658     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7659       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7660       const char *ConstRef
7661         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7662                                                         : " const &";
7663       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7664         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7665 
7666       // FIXME: Rather that making the constructor invalid, we should endeavor
7667       // to fix the type.
7668       Constructor->setInvalidDecl();
7669     }
7670   }
7671 }
7672 
7673 /// CheckDestructor - Checks a fully-formed destructor definition for
7674 /// well-formedness, issuing any diagnostics required.  Returns true
7675 /// on error.
7676 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7677   CXXRecordDecl *RD = Destructor->getParent();
7678 
7679   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7680     SourceLocation Loc;
7681 
7682     if (!Destructor->isImplicit())
7683       Loc = Destructor->getLocation();
7684     else
7685       Loc = RD->getLocation();
7686 
7687     // If we have a virtual destructor, look up the deallocation function
7688     if (FunctionDecl *OperatorDelete =
7689             FindDeallocationFunctionForDestructor(Loc, RD)) {
7690       MarkFunctionReferenced(Loc, OperatorDelete);
7691       Destructor->setOperatorDelete(OperatorDelete);
7692     }
7693   }
7694 
7695   return false;
7696 }
7697 
7698 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7699 /// the well-formednes of the destructor declarator @p D with type @p
7700 /// R. If there are any errors in the declarator, this routine will
7701 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7702 /// will be updated to reflect a well-formed type for the destructor and
7703 /// returned.
7704 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7705                                          StorageClass& SC) {
7706   // C++ [class.dtor]p1:
7707   //   [...] A typedef-name that names a class is a class-name
7708   //   (7.1.3); however, a typedef-name that names a class shall not
7709   //   be used as the identifier in the declarator for a destructor
7710   //   declaration.
7711   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7712   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7713     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7714       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7715   else if (const TemplateSpecializationType *TST =
7716              DeclaratorType->getAs<TemplateSpecializationType>())
7717     if (TST->isTypeAlias())
7718       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7719         << DeclaratorType << 1;
7720 
7721   // C++ [class.dtor]p2:
7722   //   A destructor is used to destroy objects of its class type. A
7723   //   destructor takes no parameters, and no return type can be
7724   //   specified for it (not even void). The address of a destructor
7725   //   shall not be taken. A destructor shall not be static. A
7726   //   destructor can be invoked for a const, volatile or const
7727   //   volatile object. A destructor shall not be declared const,
7728   //   volatile or const volatile (9.3.2).
7729   if (SC == SC_Static) {
7730     if (!D.isInvalidType())
7731       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7732         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7733         << SourceRange(D.getIdentifierLoc())
7734         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7735 
7736     SC = SC_None;
7737   }
7738   if (!D.isInvalidType()) {
7739     // Destructors don't have return types, but the parser will
7740     // happily parse something like:
7741     //
7742     //   class X {
7743     //     float ~X();
7744     //   };
7745     //
7746     // The return type will be eliminated later.
7747     if (D.getDeclSpec().hasTypeSpecifier())
7748       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7749         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7750         << SourceRange(D.getIdentifierLoc());
7751     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7752       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7753                                 SourceLocation(),
7754                                 D.getDeclSpec().getConstSpecLoc(),
7755                                 D.getDeclSpec().getVolatileSpecLoc(),
7756                                 D.getDeclSpec().getRestrictSpecLoc(),
7757                                 D.getDeclSpec().getAtomicSpecLoc());
7758       D.setInvalidType();
7759     }
7760   }
7761 
7762   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7763   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7764     if (FTI.TypeQuals & Qualifiers::Const)
7765       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7766         << "const" << SourceRange(D.getIdentifierLoc());
7767     if (FTI.TypeQuals & Qualifiers::Volatile)
7768       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7769         << "volatile" << SourceRange(D.getIdentifierLoc());
7770     if (FTI.TypeQuals & Qualifiers::Restrict)
7771       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7772         << "restrict" << SourceRange(D.getIdentifierLoc());
7773     D.setInvalidType();
7774   }
7775 
7776   // C++0x [class.dtor]p2:
7777   //   A destructor shall not be declared with a ref-qualifier.
7778   if (FTI.hasRefQualifier()) {
7779     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7780       << FTI.RefQualifierIsLValueRef
7781       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7782     D.setInvalidType();
7783   }
7784 
7785   // Make sure we don't have any parameters.
7786   if (FTIHasNonVoidParameters(FTI)) {
7787     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7788 
7789     // Delete the parameters.
7790     FTI.freeParams();
7791     D.setInvalidType();
7792   }
7793 
7794   // Make sure the destructor isn't variadic.
7795   if (FTI.isVariadic) {
7796     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7797     D.setInvalidType();
7798   }
7799 
7800   // Rebuild the function type "R" without any type qualifiers or
7801   // parameters (in case any of the errors above fired) and with
7802   // "void" as the return type, since destructors don't have return
7803   // types.
7804   if (!D.isInvalidType())
7805     return R;
7806 
7807   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7808   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7809   EPI.Variadic = false;
7810   EPI.TypeQuals = 0;
7811   EPI.RefQualifier = RQ_None;
7812   return Context.getFunctionType(Context.VoidTy, None, EPI);
7813 }
7814 
7815 static void extendLeft(SourceRange &R, SourceRange Before) {
7816   if (Before.isInvalid())
7817     return;
7818   R.setBegin(Before.getBegin());
7819   if (R.getEnd().isInvalid())
7820     R.setEnd(Before.getEnd());
7821 }
7822 
7823 static void extendRight(SourceRange &R, SourceRange After) {
7824   if (After.isInvalid())
7825     return;
7826   if (R.getBegin().isInvalid())
7827     R.setBegin(After.getBegin());
7828   R.setEnd(After.getEnd());
7829 }
7830 
7831 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7832 /// well-formednes of the conversion function declarator @p D with
7833 /// type @p R. If there are any errors in the declarator, this routine
7834 /// will emit diagnostics and return true. Otherwise, it will return
7835 /// false. Either way, the type @p R will be updated to reflect a
7836 /// well-formed type for the conversion operator.
7837 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7838                                      StorageClass& SC) {
7839   // C++ [class.conv.fct]p1:
7840   //   Neither parameter types nor return type can be specified. The
7841   //   type of a conversion function (8.3.5) is "function taking no
7842   //   parameter returning conversion-type-id."
7843   if (SC == SC_Static) {
7844     if (!D.isInvalidType())
7845       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7846         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7847         << D.getName().getSourceRange();
7848     D.setInvalidType();
7849     SC = SC_None;
7850   }
7851 
7852   TypeSourceInfo *ConvTSI = nullptr;
7853   QualType ConvType =
7854       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7855 
7856   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7857     // Conversion functions don't have return types, but the parser will
7858     // happily parse something like:
7859     //
7860     //   class X {
7861     //     float operator bool();
7862     //   };
7863     //
7864     // The return type will be changed later anyway.
7865     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7866       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7867       << SourceRange(D.getIdentifierLoc());
7868     D.setInvalidType();
7869   }
7870 
7871   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7872 
7873   // Make sure we don't have any parameters.
7874   if (Proto->getNumParams() > 0) {
7875     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7876 
7877     // Delete the parameters.
7878     D.getFunctionTypeInfo().freeParams();
7879     D.setInvalidType();
7880   } else if (Proto->isVariadic()) {
7881     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7882     D.setInvalidType();
7883   }
7884 
7885   // Diagnose "&operator bool()" and other such nonsense.  This
7886   // is actually a gcc extension which we don't support.
7887   if (Proto->getReturnType() != ConvType) {
7888     bool NeedsTypedef = false;
7889     SourceRange Before, After;
7890 
7891     // Walk the chunks and extract information on them for our diagnostic.
7892     bool PastFunctionChunk = false;
7893     for (auto &Chunk : D.type_objects()) {
7894       switch (Chunk.Kind) {
7895       case DeclaratorChunk::Function:
7896         if (!PastFunctionChunk) {
7897           if (Chunk.Fun.HasTrailingReturnType) {
7898             TypeSourceInfo *TRT = nullptr;
7899             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7900             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7901           }
7902           PastFunctionChunk = true;
7903           break;
7904         }
7905         // Fall through.
7906       case DeclaratorChunk::Array:
7907         NeedsTypedef = true;
7908         extendRight(After, Chunk.getSourceRange());
7909         break;
7910 
7911       case DeclaratorChunk::Pointer:
7912       case DeclaratorChunk::BlockPointer:
7913       case DeclaratorChunk::Reference:
7914       case DeclaratorChunk::MemberPointer:
7915       case DeclaratorChunk::Pipe:
7916         extendLeft(Before, Chunk.getSourceRange());
7917         break;
7918 
7919       case DeclaratorChunk::Paren:
7920         extendLeft(Before, Chunk.Loc);
7921         extendRight(After, Chunk.EndLoc);
7922         break;
7923       }
7924     }
7925 
7926     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7927                          After.isValid()  ? After.getBegin() :
7928                                             D.getIdentifierLoc();
7929     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7930     DB << Before << After;
7931 
7932     if (!NeedsTypedef) {
7933       DB << /*don't need a typedef*/0;
7934 
7935       // If we can provide a correct fix-it hint, do so.
7936       if (After.isInvalid() && ConvTSI) {
7937         SourceLocation InsertLoc =
7938             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
7939         DB << FixItHint::CreateInsertion(InsertLoc, " ")
7940            << FixItHint::CreateInsertionFromRange(
7941                   InsertLoc, CharSourceRange::getTokenRange(Before))
7942            << FixItHint::CreateRemoval(Before);
7943       }
7944     } else if (!Proto->getReturnType()->isDependentType()) {
7945       DB << /*typedef*/1 << Proto->getReturnType();
7946     } else if (getLangOpts().CPlusPlus11) {
7947       DB << /*alias template*/2 << Proto->getReturnType();
7948     } else {
7949       DB << /*might not be fixable*/3;
7950     }
7951 
7952     // Recover by incorporating the other type chunks into the result type.
7953     // Note, this does *not* change the name of the function. This is compatible
7954     // with the GCC extension:
7955     //   struct S { &operator int(); } s;
7956     //   int &r = s.operator int(); // ok in GCC
7957     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
7958     ConvType = Proto->getReturnType();
7959   }
7960 
7961   // C++ [class.conv.fct]p4:
7962   //   The conversion-type-id shall not represent a function type nor
7963   //   an array type.
7964   if (ConvType->isArrayType()) {
7965     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
7966     ConvType = Context.getPointerType(ConvType);
7967     D.setInvalidType();
7968   } else if (ConvType->isFunctionType()) {
7969     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
7970     ConvType = Context.getPointerType(ConvType);
7971     D.setInvalidType();
7972   }
7973 
7974   // Rebuild the function type "R" without any parameters (in case any
7975   // of the errors above fired) and with the conversion type as the
7976   // return type.
7977   if (D.isInvalidType())
7978     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
7979 
7980   // C++0x explicit conversion operators.
7981   if (D.getDeclSpec().isExplicitSpecified())
7982     Diag(D.getDeclSpec().getExplicitSpecLoc(),
7983          getLangOpts().CPlusPlus11 ?
7984            diag::warn_cxx98_compat_explicit_conversion_functions :
7985            diag::ext_explicit_conversion_functions)
7986       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
7987 }
7988 
7989 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
7990 /// the declaration of the given C++ conversion function. This routine
7991 /// is responsible for recording the conversion function in the C++
7992 /// class, if possible.
7993 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
7994   assert(Conversion && "Expected to receive a conversion function declaration");
7995 
7996   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
7997 
7998   // Make sure we aren't redeclaring the conversion function.
7999   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8000 
8001   // C++ [class.conv.fct]p1:
8002   //   [...] A conversion function is never used to convert a
8003   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8004   //   same object type (or a reference to it), to a (possibly
8005   //   cv-qualified) base class of that type (or a reference to it),
8006   //   or to (possibly cv-qualified) void.
8007   // FIXME: Suppress this warning if the conversion function ends up being a
8008   // virtual function that overrides a virtual function in a base class.
8009   QualType ClassType
8010     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8011   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8012     ConvType = ConvTypeRef->getPointeeType();
8013   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8014       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8015     /* Suppress diagnostics for instantiations. */;
8016   else if (ConvType->isRecordType()) {
8017     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8018     if (ConvType == ClassType)
8019       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8020         << ClassType;
8021     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8022       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8023         <<  ClassType << ConvType;
8024   } else if (ConvType->isVoidType()) {
8025     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8026       << ClassType << ConvType;
8027   }
8028 
8029   if (FunctionTemplateDecl *ConversionTemplate
8030                                 = Conversion->getDescribedFunctionTemplate())
8031     return ConversionTemplate;
8032 
8033   return Conversion;
8034 }
8035 
8036 /// Check the validity of a declarator that we parsed for a deduction-guide.
8037 /// These aren't actually declarators in the grammar, so we need to check that
8038 /// the user didn't specify any pieces that are not part of the deduction-guide
8039 /// grammar.
8040 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8041                                          StorageClass &SC) {
8042   // FIXME: Implement
8043 }
8044 
8045 //===----------------------------------------------------------------------===//
8046 // Namespace Handling
8047 //===----------------------------------------------------------------------===//
8048 
8049 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8050 /// reopened.
8051 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8052                                             SourceLocation Loc,
8053                                             IdentifierInfo *II, bool *IsInline,
8054                                             NamespaceDecl *PrevNS) {
8055   assert(*IsInline != PrevNS->isInline());
8056 
8057   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8058   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8059   // inline namespaces, with the intention of bringing names into namespace std.
8060   //
8061   // We support this just well enough to get that case working; this is not
8062   // sufficient to support reopening namespaces as inline in general.
8063   if (*IsInline && II && II->getName().startswith("__atomic") &&
8064       S.getSourceManager().isInSystemHeader(Loc)) {
8065     // Mark all prior declarations of the namespace as inline.
8066     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8067          NS = NS->getPreviousDecl())
8068       NS->setInline(*IsInline);
8069     // Patch up the lookup table for the containing namespace. This isn't really
8070     // correct, but it's good enough for this particular case.
8071     for (auto *I : PrevNS->decls())
8072       if (auto *ND = dyn_cast<NamedDecl>(I))
8073         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8074     return;
8075   }
8076 
8077   if (PrevNS->isInline())
8078     // The user probably just forgot the 'inline', so suggest that it
8079     // be added back.
8080     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8081       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8082   else
8083     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8084 
8085   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8086   *IsInline = PrevNS->isInline();
8087 }
8088 
8089 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8090 /// definition.
8091 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8092                                    SourceLocation InlineLoc,
8093                                    SourceLocation NamespaceLoc,
8094                                    SourceLocation IdentLoc,
8095                                    IdentifierInfo *II,
8096                                    SourceLocation LBrace,
8097                                    AttributeList *AttrList,
8098                                    UsingDirectiveDecl *&UD) {
8099   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8100   // For anonymous namespace, take the location of the left brace.
8101   SourceLocation Loc = II ? IdentLoc : LBrace;
8102   bool IsInline = InlineLoc.isValid();
8103   bool IsInvalid = false;
8104   bool IsStd = false;
8105   bool AddToKnown = false;
8106   Scope *DeclRegionScope = NamespcScope->getParent();
8107 
8108   NamespaceDecl *PrevNS = nullptr;
8109   if (II) {
8110     // C++ [namespace.def]p2:
8111     //   The identifier in an original-namespace-definition shall not
8112     //   have been previously defined in the declarative region in
8113     //   which the original-namespace-definition appears. The
8114     //   identifier in an original-namespace-definition is the name of
8115     //   the namespace. Subsequently in that declarative region, it is
8116     //   treated as an original-namespace-name.
8117     //
8118     // Since namespace names are unique in their scope, and we don't
8119     // look through using directives, just look for any ordinary names
8120     // as if by qualified name lookup.
8121     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8122     LookupQualifiedName(R, CurContext->getRedeclContext());
8123     NamedDecl *PrevDecl =
8124         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8125     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8126 
8127     if (PrevNS) {
8128       // This is an extended namespace definition.
8129       if (IsInline != PrevNS->isInline())
8130         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8131                                         &IsInline, PrevNS);
8132     } else if (PrevDecl) {
8133       // This is an invalid name redefinition.
8134       Diag(Loc, diag::err_redefinition_different_kind)
8135         << II;
8136       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8137       IsInvalid = true;
8138       // Continue on to push Namespc as current DeclContext and return it.
8139     } else if (II->isStr("std") &&
8140                CurContext->getRedeclContext()->isTranslationUnit()) {
8141       // This is the first "real" definition of the namespace "std", so update
8142       // our cache of the "std" namespace to point at this definition.
8143       PrevNS = getStdNamespace();
8144       IsStd = true;
8145       AddToKnown = !IsInline;
8146     } else {
8147       // We've seen this namespace for the first time.
8148       AddToKnown = !IsInline;
8149     }
8150   } else {
8151     // Anonymous namespaces.
8152 
8153     // Determine whether the parent already has an anonymous namespace.
8154     DeclContext *Parent = CurContext->getRedeclContext();
8155     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8156       PrevNS = TU->getAnonymousNamespace();
8157     } else {
8158       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8159       PrevNS = ND->getAnonymousNamespace();
8160     }
8161 
8162     if (PrevNS && IsInline != PrevNS->isInline())
8163       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8164                                       &IsInline, PrevNS);
8165   }
8166 
8167   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8168                                                  StartLoc, Loc, II, PrevNS);
8169   if (IsInvalid)
8170     Namespc->setInvalidDecl();
8171 
8172   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8173 
8174   // FIXME: Should we be merging attributes?
8175   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8176     PushNamespaceVisibilityAttr(Attr, Loc);
8177 
8178   if (IsStd)
8179     StdNamespace = Namespc;
8180   if (AddToKnown)
8181     KnownNamespaces[Namespc] = false;
8182 
8183   if (II) {
8184     PushOnScopeChains(Namespc, DeclRegionScope);
8185   } else {
8186     // Link the anonymous namespace into its parent.
8187     DeclContext *Parent = CurContext->getRedeclContext();
8188     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8189       TU->setAnonymousNamespace(Namespc);
8190     } else {
8191       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8192     }
8193 
8194     CurContext->addDecl(Namespc);
8195 
8196     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8197     //   behaves as if it were replaced by
8198     //     namespace unique { /* empty body */ }
8199     //     using namespace unique;
8200     //     namespace unique { namespace-body }
8201     //   where all occurrences of 'unique' in a translation unit are
8202     //   replaced by the same identifier and this identifier differs
8203     //   from all other identifiers in the entire program.
8204 
8205     // We just create the namespace with an empty name and then add an
8206     // implicit using declaration, just like the standard suggests.
8207     //
8208     // CodeGen enforces the "universally unique" aspect by giving all
8209     // declarations semantically contained within an anonymous
8210     // namespace internal linkage.
8211 
8212     if (!PrevNS) {
8213       UD = UsingDirectiveDecl::Create(Context, Parent,
8214                                       /* 'using' */ LBrace,
8215                                       /* 'namespace' */ SourceLocation(),
8216                                       /* qualifier */ NestedNameSpecifierLoc(),
8217                                       /* identifier */ SourceLocation(),
8218                                       Namespc,
8219                                       /* Ancestor */ Parent);
8220       UD->setImplicit();
8221       Parent->addDecl(UD);
8222     }
8223   }
8224 
8225   ActOnDocumentableDecl(Namespc);
8226 
8227   // Although we could have an invalid decl (i.e. the namespace name is a
8228   // redefinition), push it as current DeclContext and try to continue parsing.
8229   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8230   // for the namespace has the declarations that showed up in that particular
8231   // namespace definition.
8232   PushDeclContext(NamespcScope, Namespc);
8233   return Namespc;
8234 }
8235 
8236 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8237 /// is a namespace alias, returns the namespace it points to.
8238 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8239   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8240     return AD->getNamespace();
8241   return dyn_cast_or_null<NamespaceDecl>(D);
8242 }
8243 
8244 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8245 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8246 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8247   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8248   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8249   Namespc->setRBraceLoc(RBrace);
8250   PopDeclContext();
8251   if (Namespc->hasAttr<VisibilityAttr>())
8252     PopPragmaVisibility(true, RBrace);
8253 }
8254 
8255 CXXRecordDecl *Sema::getStdBadAlloc() const {
8256   return cast_or_null<CXXRecordDecl>(
8257                                   StdBadAlloc.get(Context.getExternalSource()));
8258 }
8259 
8260 EnumDecl *Sema::getStdAlignValT() const {
8261   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8262 }
8263 
8264 NamespaceDecl *Sema::getStdNamespace() const {
8265   return cast_or_null<NamespaceDecl>(
8266                                  StdNamespace.get(Context.getExternalSource()));
8267 }
8268 
8269 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8270   if (!StdExperimentalNamespaceCache) {
8271     if (auto Std = getStdNamespace()) {
8272       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8273                           SourceLocation(), LookupNamespaceName);
8274       if (!LookupQualifiedName(Result, Std) ||
8275           !(StdExperimentalNamespaceCache =
8276                 Result.getAsSingle<NamespaceDecl>()))
8277         Result.suppressDiagnostics();
8278     }
8279   }
8280   return StdExperimentalNamespaceCache;
8281 }
8282 
8283 /// \brief Retrieve the special "std" namespace, which may require us to
8284 /// implicitly define the namespace.
8285 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8286   if (!StdNamespace) {
8287     // The "std" namespace has not yet been defined, so build one implicitly.
8288     StdNamespace = NamespaceDecl::Create(Context,
8289                                          Context.getTranslationUnitDecl(),
8290                                          /*Inline=*/false,
8291                                          SourceLocation(), SourceLocation(),
8292                                          &PP.getIdentifierTable().get("std"),
8293                                          /*PrevDecl=*/nullptr);
8294     getStdNamespace()->setImplicit(true);
8295   }
8296 
8297   return getStdNamespace();
8298 }
8299 
8300 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8301   assert(getLangOpts().CPlusPlus &&
8302          "Looking for std::initializer_list outside of C++.");
8303 
8304   // We're looking for implicit instantiations of
8305   // template <typename E> class std::initializer_list.
8306 
8307   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8308     return false;
8309 
8310   ClassTemplateDecl *Template = nullptr;
8311   const TemplateArgument *Arguments = nullptr;
8312 
8313   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8314 
8315     ClassTemplateSpecializationDecl *Specialization =
8316         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8317     if (!Specialization)
8318       return false;
8319 
8320     Template = Specialization->getSpecializedTemplate();
8321     Arguments = Specialization->getTemplateArgs().data();
8322   } else if (const TemplateSpecializationType *TST =
8323                  Ty->getAs<TemplateSpecializationType>()) {
8324     Template = dyn_cast_or_null<ClassTemplateDecl>(
8325         TST->getTemplateName().getAsTemplateDecl());
8326     Arguments = TST->getArgs();
8327   }
8328   if (!Template)
8329     return false;
8330 
8331   if (!StdInitializerList) {
8332     // Haven't recognized std::initializer_list yet, maybe this is it.
8333     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8334     if (TemplateClass->getIdentifier() !=
8335             &PP.getIdentifierTable().get("initializer_list") ||
8336         !getStdNamespace()->InEnclosingNamespaceSetOf(
8337             TemplateClass->getDeclContext()))
8338       return false;
8339     // This is a template called std::initializer_list, but is it the right
8340     // template?
8341     TemplateParameterList *Params = Template->getTemplateParameters();
8342     if (Params->getMinRequiredArguments() != 1)
8343       return false;
8344     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8345       return false;
8346 
8347     // It's the right template.
8348     StdInitializerList = Template;
8349   }
8350 
8351   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8352     return false;
8353 
8354   // This is an instance of std::initializer_list. Find the argument type.
8355   if (Element)
8356     *Element = Arguments[0].getAsType();
8357   return true;
8358 }
8359 
8360 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8361   NamespaceDecl *Std = S.getStdNamespace();
8362   if (!Std) {
8363     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8364     return nullptr;
8365   }
8366 
8367   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8368                       Loc, Sema::LookupOrdinaryName);
8369   if (!S.LookupQualifiedName(Result, Std)) {
8370     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8371     return nullptr;
8372   }
8373   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8374   if (!Template) {
8375     Result.suppressDiagnostics();
8376     // We found something weird. Complain about the first thing we found.
8377     NamedDecl *Found = *Result.begin();
8378     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8379     return nullptr;
8380   }
8381 
8382   // We found some template called std::initializer_list. Now verify that it's
8383   // correct.
8384   TemplateParameterList *Params = Template->getTemplateParameters();
8385   if (Params->getMinRequiredArguments() != 1 ||
8386       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8387     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8388     return nullptr;
8389   }
8390 
8391   return Template;
8392 }
8393 
8394 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8395   if (!StdInitializerList) {
8396     StdInitializerList = LookupStdInitializerList(*this, Loc);
8397     if (!StdInitializerList)
8398       return QualType();
8399   }
8400 
8401   TemplateArgumentListInfo Args(Loc, Loc);
8402   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8403                                        Context.getTrivialTypeSourceInfo(Element,
8404                                                                         Loc)));
8405   return Context.getCanonicalType(
8406       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8407 }
8408 
8409 bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
8410   // C++ [dcl.init.list]p2:
8411   //   A constructor is an initializer-list constructor if its first parameter
8412   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8413   //   std::initializer_list<E> for some type E, and either there are no other
8414   //   parameters or else all other parameters have default arguments.
8415   if (Ctor->getNumParams() < 1 ||
8416       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8417     return false;
8418 
8419   QualType ArgType = Ctor->getParamDecl(0)->getType();
8420   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8421     ArgType = RT->getPointeeType().getUnqualifiedType();
8422 
8423   return isStdInitializerList(ArgType, nullptr);
8424 }
8425 
8426 /// \brief Determine whether a using statement is in a context where it will be
8427 /// apply in all contexts.
8428 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8429   switch (CurContext->getDeclKind()) {
8430     case Decl::TranslationUnit:
8431       return true;
8432     case Decl::LinkageSpec:
8433       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8434     default:
8435       return false;
8436   }
8437 }
8438 
8439 namespace {
8440 
8441 // Callback to only accept typo corrections that are namespaces.
8442 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8443 public:
8444   bool ValidateCandidate(const TypoCorrection &candidate) override {
8445     if (NamedDecl *ND = candidate.getCorrectionDecl())
8446       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8447     return false;
8448   }
8449 };
8450 
8451 }
8452 
8453 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8454                                        CXXScopeSpec &SS,
8455                                        SourceLocation IdentLoc,
8456                                        IdentifierInfo *Ident) {
8457   R.clear();
8458   if (TypoCorrection Corrected =
8459           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8460                         llvm::make_unique<NamespaceValidatorCCC>(),
8461                         Sema::CTK_ErrorRecovery)) {
8462     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8463       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8464       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8465                               Ident->getName().equals(CorrectedStr);
8466       S.diagnoseTypo(Corrected,
8467                      S.PDiag(diag::err_using_directive_member_suggest)
8468                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8469                      S.PDiag(diag::note_namespace_defined_here));
8470     } else {
8471       S.diagnoseTypo(Corrected,
8472                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8473                      S.PDiag(diag::note_namespace_defined_here));
8474     }
8475     R.addDecl(Corrected.getFoundDecl());
8476     return true;
8477   }
8478   return false;
8479 }
8480 
8481 Decl *Sema::ActOnUsingDirective(Scope *S,
8482                                           SourceLocation UsingLoc,
8483                                           SourceLocation NamespcLoc,
8484                                           CXXScopeSpec &SS,
8485                                           SourceLocation IdentLoc,
8486                                           IdentifierInfo *NamespcName,
8487                                           AttributeList *AttrList) {
8488   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8489   assert(NamespcName && "Invalid NamespcName.");
8490   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8491 
8492   // This can only happen along a recovery path.
8493   while (S->isTemplateParamScope())
8494     S = S->getParent();
8495   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8496 
8497   UsingDirectiveDecl *UDir = nullptr;
8498   NestedNameSpecifier *Qualifier = nullptr;
8499   if (SS.isSet())
8500     Qualifier = SS.getScopeRep();
8501 
8502   // Lookup namespace name.
8503   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8504   LookupParsedName(R, S, &SS);
8505   if (R.isAmbiguous())
8506     return nullptr;
8507 
8508   if (R.empty()) {
8509     R.clear();
8510     // Allow "using namespace std;" or "using namespace ::std;" even if
8511     // "std" hasn't been defined yet, for GCC compatibility.
8512     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8513         NamespcName->isStr("std")) {
8514       Diag(IdentLoc, diag::ext_using_undefined_std);
8515       R.addDecl(getOrCreateStdNamespace());
8516       R.resolveKind();
8517     }
8518     // Otherwise, attempt typo correction.
8519     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8520   }
8521 
8522   if (!R.empty()) {
8523     NamedDecl *Named = R.getRepresentativeDecl();
8524     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8525     assert(NS && "expected namespace decl");
8526 
8527     // The use of a nested name specifier may trigger deprecation warnings.
8528     DiagnoseUseOfDecl(Named, IdentLoc);
8529 
8530     // C++ [namespace.udir]p1:
8531     //   A using-directive specifies that the names in the nominated
8532     //   namespace can be used in the scope in which the
8533     //   using-directive appears after the using-directive. During
8534     //   unqualified name lookup (3.4.1), the names appear as if they
8535     //   were declared in the nearest enclosing namespace which
8536     //   contains both the using-directive and the nominated
8537     //   namespace. [Note: in this context, "contains" means "contains
8538     //   directly or indirectly". ]
8539 
8540     // Find enclosing context containing both using-directive and
8541     // nominated namespace.
8542     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8543     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8544       CommonAncestor = CommonAncestor->getParent();
8545 
8546     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8547                                       SS.getWithLocInContext(Context),
8548                                       IdentLoc, Named, CommonAncestor);
8549 
8550     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8551         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8552       Diag(IdentLoc, diag::warn_using_directive_in_header);
8553     }
8554 
8555     PushUsingDirective(S, UDir);
8556   } else {
8557     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8558   }
8559 
8560   if (UDir)
8561     ProcessDeclAttributeList(S, UDir, AttrList);
8562 
8563   return UDir;
8564 }
8565 
8566 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8567   // If the scope has an associated entity and the using directive is at
8568   // namespace or translation unit scope, add the UsingDirectiveDecl into
8569   // its lookup structure so qualified name lookup can find it.
8570   DeclContext *Ctx = S->getEntity();
8571   if (Ctx && !Ctx->isFunctionOrMethod())
8572     Ctx->addDecl(UDir);
8573   else
8574     // Otherwise, it is at block scope. The using-directives will affect lookup
8575     // only to the end of the scope.
8576     S->PushUsingDirective(UDir);
8577 }
8578 
8579 
8580 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8581                                   AccessSpecifier AS,
8582                                   SourceLocation UsingLoc,
8583                                   SourceLocation TypenameLoc,
8584                                   CXXScopeSpec &SS,
8585                                   UnqualifiedId &Name,
8586                                   SourceLocation EllipsisLoc,
8587                                   AttributeList *AttrList) {
8588   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8589 
8590   if (SS.isEmpty()) {
8591     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8592     return nullptr;
8593   }
8594 
8595   switch (Name.getKind()) {
8596   case UnqualifiedId::IK_ImplicitSelfParam:
8597   case UnqualifiedId::IK_Identifier:
8598   case UnqualifiedId::IK_OperatorFunctionId:
8599   case UnqualifiedId::IK_LiteralOperatorId:
8600   case UnqualifiedId::IK_ConversionFunctionId:
8601     break;
8602 
8603   case UnqualifiedId::IK_ConstructorName:
8604   case UnqualifiedId::IK_ConstructorTemplateId:
8605     // C++11 inheriting constructors.
8606     Diag(Name.getLocStart(),
8607          getLangOpts().CPlusPlus11 ?
8608            diag::warn_cxx98_compat_using_decl_constructor :
8609            diag::err_using_decl_constructor)
8610       << SS.getRange();
8611 
8612     if (getLangOpts().CPlusPlus11) break;
8613 
8614     return nullptr;
8615 
8616   case UnqualifiedId::IK_DestructorName:
8617     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8618       << SS.getRange();
8619     return nullptr;
8620 
8621   case UnqualifiedId::IK_TemplateId:
8622     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8623       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8624     return nullptr;
8625 
8626   case UnqualifiedId::IK_DeductionGuideName:
8627     llvm_unreachable("cannot parse qualified deduction guide name");
8628   }
8629 
8630   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8631   DeclarationName TargetName = TargetNameInfo.getName();
8632   if (!TargetName)
8633     return nullptr;
8634 
8635   // Warn about access declarations.
8636   if (UsingLoc.isInvalid()) {
8637     Diag(Name.getLocStart(),
8638          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8639                                    : diag::warn_access_decl_deprecated)
8640       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8641   }
8642 
8643   if (EllipsisLoc.isInvalid()) {
8644     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8645         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8646       return nullptr;
8647   } else {
8648     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8649         !TargetNameInfo.containsUnexpandedParameterPack()) {
8650       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8651         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8652       EllipsisLoc = SourceLocation();
8653     }
8654   }
8655 
8656   NamedDecl *UD =
8657       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8658                             SS, TargetNameInfo, EllipsisLoc, AttrList,
8659                             /*IsInstantiation*/false);
8660   if (UD)
8661     PushOnScopeChains(UD, S, /*AddToContext*/ false);
8662 
8663   return UD;
8664 }
8665 
8666 /// \brief Determine whether a using declaration considers the given
8667 /// declarations as "equivalent", e.g., if they are redeclarations of
8668 /// the same entity or are both typedefs of the same type.
8669 static bool
8670 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8671   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8672     return true;
8673 
8674   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8675     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8676       return Context.hasSameType(TD1->getUnderlyingType(),
8677                                  TD2->getUnderlyingType());
8678 
8679   return false;
8680 }
8681 
8682 
8683 /// Determines whether to create a using shadow decl for a particular
8684 /// decl, given the set of decls existing prior to this using lookup.
8685 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8686                                 const LookupResult &Previous,
8687                                 UsingShadowDecl *&PrevShadow) {
8688   // Diagnose finding a decl which is not from a base class of the
8689   // current class.  We do this now because there are cases where this
8690   // function will silently decide not to build a shadow decl, which
8691   // will pre-empt further diagnostics.
8692   //
8693   // We don't need to do this in C++11 because we do the check once on
8694   // the qualifier.
8695   //
8696   // FIXME: diagnose the following if we care enough:
8697   //   struct A { int foo; };
8698   //   struct B : A { using A::foo; };
8699   //   template <class T> struct C : A {};
8700   //   template <class T> struct D : C<T> { using B::foo; } // <---
8701   // This is invalid (during instantiation) in C++03 because B::foo
8702   // resolves to the using decl in B, which is not a base class of D<T>.
8703   // We can't diagnose it immediately because C<T> is an unknown
8704   // specialization.  The UsingShadowDecl in D<T> then points directly
8705   // to A::foo, which will look well-formed when we instantiate.
8706   // The right solution is to not collapse the shadow-decl chain.
8707   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8708     DeclContext *OrigDC = Orig->getDeclContext();
8709 
8710     // Handle enums and anonymous structs.
8711     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8712     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8713     while (OrigRec->isAnonymousStructOrUnion())
8714       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8715 
8716     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8717       if (OrigDC == CurContext) {
8718         Diag(Using->getLocation(),
8719              diag::err_using_decl_nested_name_specifier_is_current_class)
8720           << Using->getQualifierLoc().getSourceRange();
8721         Diag(Orig->getLocation(), diag::note_using_decl_target);
8722         Using->setInvalidDecl();
8723         return true;
8724       }
8725 
8726       Diag(Using->getQualifierLoc().getBeginLoc(),
8727            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8728         << Using->getQualifier()
8729         << cast<CXXRecordDecl>(CurContext)
8730         << Using->getQualifierLoc().getSourceRange();
8731       Diag(Orig->getLocation(), diag::note_using_decl_target);
8732       Using->setInvalidDecl();
8733       return true;
8734     }
8735   }
8736 
8737   if (Previous.empty()) return false;
8738 
8739   NamedDecl *Target = Orig;
8740   if (isa<UsingShadowDecl>(Target))
8741     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8742 
8743   // If the target happens to be one of the previous declarations, we
8744   // don't have a conflict.
8745   //
8746   // FIXME: but we might be increasing its access, in which case we
8747   // should redeclare it.
8748   NamedDecl *NonTag = nullptr, *Tag = nullptr;
8749   bool FoundEquivalentDecl = false;
8750   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8751          I != E; ++I) {
8752     NamedDecl *D = (*I)->getUnderlyingDecl();
8753     // We can have UsingDecls in our Previous results because we use the same
8754     // LookupResult for checking whether the UsingDecl itself is a valid
8755     // redeclaration.
8756     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
8757       continue;
8758 
8759     if (IsEquivalentForUsingDecl(Context, D, Target)) {
8760       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8761         PrevShadow = Shadow;
8762       FoundEquivalentDecl = true;
8763     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8764       // We don't conflict with an existing using shadow decl of an equivalent
8765       // declaration, but we're not a redeclaration of it.
8766       FoundEquivalentDecl = true;
8767     }
8768 
8769     if (isVisible(D))
8770       (isa<TagDecl>(D) ? Tag : NonTag) = D;
8771   }
8772 
8773   if (FoundEquivalentDecl)
8774     return false;
8775 
8776   if (FunctionDecl *FD = Target->getAsFunction()) {
8777     NamedDecl *OldDecl = nullptr;
8778     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8779                           /*IsForUsingDecl*/ true)) {
8780     case Ovl_Overload:
8781       return false;
8782 
8783     case Ovl_NonFunction:
8784       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8785       break;
8786 
8787     // We found a decl with the exact signature.
8788     case Ovl_Match:
8789       // If we're in a record, we want to hide the target, so we
8790       // return true (without a diagnostic) to tell the caller not to
8791       // build a shadow decl.
8792       if (CurContext->isRecord())
8793         return true;
8794 
8795       // If we're not in a record, this is an error.
8796       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8797       break;
8798     }
8799 
8800     Diag(Target->getLocation(), diag::note_using_decl_target);
8801     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
8802     Using->setInvalidDecl();
8803     return true;
8804   }
8805 
8806   // Target is not a function.
8807 
8808   if (isa<TagDecl>(Target)) {
8809     // No conflict between a tag and a non-tag.
8810     if (!Tag) return false;
8811 
8812     Diag(Using->getLocation(), diag::err_using_decl_conflict);
8813     Diag(Target->getLocation(), diag::note_using_decl_target);
8814     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
8815     Using->setInvalidDecl();
8816     return true;
8817   }
8818 
8819   // No conflict between a tag and a non-tag.
8820   if (!NonTag) return false;
8821 
8822   Diag(Using->getLocation(), diag::err_using_decl_conflict);
8823   Diag(Target->getLocation(), diag::note_using_decl_target);
8824   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
8825   Using->setInvalidDecl();
8826   return true;
8827 }
8828 
8829 /// Determine whether a direct base class is a virtual base class.
8830 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
8831   if (!Derived->getNumVBases())
8832     return false;
8833   for (auto &B : Derived->bases())
8834     if (B.getType()->getAsCXXRecordDecl() == Base)
8835       return B.isVirtual();
8836   llvm_unreachable("not a direct base class");
8837 }
8838 
8839 /// Builds a shadow declaration corresponding to a 'using' declaration.
8840 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
8841                                             UsingDecl *UD,
8842                                             NamedDecl *Orig,
8843                                             UsingShadowDecl *PrevDecl) {
8844   // If we resolved to another shadow declaration, just coalesce them.
8845   NamedDecl *Target = Orig;
8846   if (isa<UsingShadowDecl>(Target)) {
8847     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8848     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
8849   }
8850 
8851   NamedDecl *NonTemplateTarget = Target;
8852   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
8853     NonTemplateTarget = TargetTD->getTemplatedDecl();
8854 
8855   UsingShadowDecl *Shadow;
8856   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
8857     bool IsVirtualBase =
8858         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
8859                             UD->getQualifier()->getAsRecordDecl());
8860     Shadow = ConstructorUsingShadowDecl::Create(
8861         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
8862   } else {
8863     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
8864                                      Target);
8865   }
8866   UD->addShadowDecl(Shadow);
8867 
8868   Shadow->setAccess(UD->getAccess());
8869   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
8870     Shadow->setInvalidDecl();
8871 
8872   Shadow->setPreviousDecl(PrevDecl);
8873 
8874   if (S)
8875     PushOnScopeChains(Shadow, S);
8876   else
8877     CurContext->addDecl(Shadow);
8878 
8879 
8880   return Shadow;
8881 }
8882 
8883 /// Hides a using shadow declaration.  This is required by the current
8884 /// using-decl implementation when a resolvable using declaration in a
8885 /// class is followed by a declaration which would hide or override
8886 /// one or more of the using decl's targets; for example:
8887 ///
8888 ///   struct Base { void foo(int); };
8889 ///   struct Derived : Base {
8890 ///     using Base::foo;
8891 ///     void foo(int);
8892 ///   };
8893 ///
8894 /// The governing language is C++03 [namespace.udecl]p12:
8895 ///
8896 ///   When a using-declaration brings names from a base class into a
8897 ///   derived class scope, member functions in the derived class
8898 ///   override and/or hide member functions with the same name and
8899 ///   parameter types in a base class (rather than conflicting).
8900 ///
8901 /// There are two ways to implement this:
8902 ///   (1) optimistically create shadow decls when they're not hidden
8903 ///       by existing declarations, or
8904 ///   (2) don't create any shadow decls (or at least don't make them
8905 ///       visible) until we've fully parsed/instantiated the class.
8906 /// The problem with (1) is that we might have to retroactively remove
8907 /// a shadow decl, which requires several O(n) operations because the
8908 /// decl structures are (very reasonably) not designed for removal.
8909 /// (2) avoids this but is very fiddly and phase-dependent.
8910 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
8911   if (Shadow->getDeclName().getNameKind() ==
8912         DeclarationName::CXXConversionFunctionName)
8913     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
8914 
8915   // Remove it from the DeclContext...
8916   Shadow->getDeclContext()->removeDecl(Shadow);
8917 
8918   // ...and the scope, if applicable...
8919   if (S) {
8920     S->RemoveDecl(Shadow);
8921     IdResolver.RemoveDecl(Shadow);
8922   }
8923 
8924   // ...and the using decl.
8925   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
8926 
8927   // TODO: complain somehow if Shadow was used.  It shouldn't
8928   // be possible for this to happen, because...?
8929 }
8930 
8931 /// Find the base specifier for a base class with the given type.
8932 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
8933                                                 QualType DesiredBase,
8934                                                 bool &AnyDependentBases) {
8935   // Check whether the named type is a direct base class.
8936   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
8937   for (auto &Base : Derived->bases()) {
8938     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
8939     if (CanonicalDesiredBase == BaseType)
8940       return &Base;
8941     if (BaseType->isDependentType())
8942       AnyDependentBases = true;
8943   }
8944   return nullptr;
8945 }
8946 
8947 namespace {
8948 class UsingValidatorCCC : public CorrectionCandidateCallback {
8949 public:
8950   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
8951                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
8952       : HasTypenameKeyword(HasTypenameKeyword),
8953         IsInstantiation(IsInstantiation), OldNNS(NNS),
8954         RequireMemberOf(RequireMemberOf) {}
8955 
8956   bool ValidateCandidate(const TypoCorrection &Candidate) override {
8957     NamedDecl *ND = Candidate.getCorrectionDecl();
8958 
8959     // Keywords are not valid here.
8960     if (!ND || isa<NamespaceDecl>(ND))
8961       return false;
8962 
8963     // Completely unqualified names are invalid for a 'using' declaration.
8964     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
8965       return false;
8966 
8967     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
8968     // reject.
8969 
8970     if (RequireMemberOf) {
8971       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
8972       if (FoundRecord && FoundRecord->isInjectedClassName()) {
8973         // No-one ever wants a using-declaration to name an injected-class-name
8974         // of a base class, unless they're declaring an inheriting constructor.
8975         ASTContext &Ctx = ND->getASTContext();
8976         if (!Ctx.getLangOpts().CPlusPlus11)
8977           return false;
8978         QualType FoundType = Ctx.getRecordType(FoundRecord);
8979 
8980         // Check that the injected-class-name is named as a member of its own
8981         // type; we don't want to suggest 'using Derived::Base;', since that
8982         // means something else.
8983         NestedNameSpecifier *Specifier =
8984             Candidate.WillReplaceSpecifier()
8985                 ? Candidate.getCorrectionSpecifier()
8986                 : OldNNS;
8987         if (!Specifier->getAsType() ||
8988             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
8989           return false;
8990 
8991         // Check that this inheriting constructor declaration actually names a
8992         // direct base class of the current class.
8993         bool AnyDependentBases = false;
8994         if (!findDirectBaseWithType(RequireMemberOf,
8995                                     Ctx.getRecordType(FoundRecord),
8996                                     AnyDependentBases) &&
8997             !AnyDependentBases)
8998           return false;
8999       } else {
9000         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9001         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9002           return false;
9003 
9004         // FIXME: Check that the base class member is accessible?
9005       }
9006     } else {
9007       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9008       if (FoundRecord && FoundRecord->isInjectedClassName())
9009         return false;
9010     }
9011 
9012     if (isa<TypeDecl>(ND))
9013       return HasTypenameKeyword || !IsInstantiation;
9014 
9015     return !HasTypenameKeyword;
9016   }
9017 
9018 private:
9019   bool HasTypenameKeyword;
9020   bool IsInstantiation;
9021   NestedNameSpecifier *OldNNS;
9022   CXXRecordDecl *RequireMemberOf;
9023 };
9024 } // end anonymous namespace
9025 
9026 /// Builds a using declaration.
9027 ///
9028 /// \param IsInstantiation - Whether this call arises from an
9029 ///   instantiation of an unresolved using declaration.  We treat
9030 ///   the lookup differently for these declarations.
9031 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9032                                        SourceLocation UsingLoc,
9033                                        bool HasTypenameKeyword,
9034                                        SourceLocation TypenameLoc,
9035                                        CXXScopeSpec &SS,
9036                                        DeclarationNameInfo NameInfo,
9037                                        SourceLocation EllipsisLoc,
9038                                        AttributeList *AttrList,
9039                                        bool IsInstantiation) {
9040   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9041   SourceLocation IdentLoc = NameInfo.getLoc();
9042   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9043 
9044   // FIXME: We ignore attributes for now.
9045 
9046   // For an inheriting constructor declaration, the name of the using
9047   // declaration is the name of a constructor in this class, not in the
9048   // base class.
9049   DeclarationNameInfo UsingName = NameInfo;
9050   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9051     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9052       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9053           Context.getCanonicalType(Context.getRecordType(RD))));
9054 
9055   // Do the redeclaration lookup in the current scope.
9056   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9057                         ForRedeclaration);
9058   Previous.setHideTags(false);
9059   if (S) {
9060     LookupName(Previous, S);
9061 
9062     // It is really dumb that we have to do this.
9063     LookupResult::Filter F = Previous.makeFilter();
9064     while (F.hasNext()) {
9065       NamedDecl *D = F.next();
9066       if (!isDeclInScope(D, CurContext, S))
9067         F.erase();
9068       // If we found a local extern declaration that's not ordinarily visible,
9069       // and this declaration is being added to a non-block scope, ignore it.
9070       // We're only checking for scope conflicts here, not also for violations
9071       // of the linkage rules.
9072       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9073                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9074         F.erase();
9075     }
9076     F.done();
9077   } else {
9078     assert(IsInstantiation && "no scope in non-instantiation");
9079     if (CurContext->isRecord())
9080       LookupQualifiedName(Previous, CurContext);
9081     else {
9082       // No redeclaration check is needed here; in non-member contexts we
9083       // diagnosed all possible conflicts with other using-declarations when
9084       // building the template:
9085       //
9086       // For a dependent non-type using declaration, the only valid case is
9087       // if we instantiate to a single enumerator. We check for conflicts
9088       // between shadow declarations we introduce, and we check in the template
9089       // definition for conflicts between a non-type using declaration and any
9090       // other declaration, which together covers all cases.
9091       //
9092       // A dependent typename using declaration will never successfully
9093       // instantiate, since it will always name a class member, so we reject
9094       // that in the template definition.
9095     }
9096   }
9097 
9098   // Check for invalid redeclarations.
9099   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9100                                   SS, IdentLoc, Previous))
9101     return nullptr;
9102 
9103   // Check for bad qualifiers.
9104   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9105                               IdentLoc))
9106     return nullptr;
9107 
9108   DeclContext *LookupContext = computeDeclContext(SS);
9109   NamedDecl *D;
9110   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9111   if (!LookupContext || EllipsisLoc.isValid()) {
9112     if (HasTypenameKeyword) {
9113       // FIXME: not all declaration name kinds are legal here
9114       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9115                                               UsingLoc, TypenameLoc,
9116                                               QualifierLoc,
9117                                               IdentLoc, NameInfo.getName(),
9118                                               EllipsisLoc);
9119     } else {
9120       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9121                                            QualifierLoc, NameInfo, EllipsisLoc);
9122     }
9123     D->setAccess(AS);
9124     CurContext->addDecl(D);
9125     return D;
9126   }
9127 
9128   auto Build = [&](bool Invalid) {
9129     UsingDecl *UD =
9130         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9131                           UsingName, HasTypenameKeyword);
9132     UD->setAccess(AS);
9133     CurContext->addDecl(UD);
9134     UD->setInvalidDecl(Invalid);
9135     return UD;
9136   };
9137   auto BuildInvalid = [&]{ return Build(true); };
9138   auto BuildValid = [&]{ return Build(false); };
9139 
9140   if (RequireCompleteDeclContext(SS, LookupContext))
9141     return BuildInvalid();
9142 
9143   // Look up the target name.
9144   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9145 
9146   // Unlike most lookups, we don't always want to hide tag
9147   // declarations: tag names are visible through the using declaration
9148   // even if hidden by ordinary names, *except* in a dependent context
9149   // where it's important for the sanity of two-phase lookup.
9150   if (!IsInstantiation)
9151     R.setHideTags(false);
9152 
9153   // For the purposes of this lookup, we have a base object type
9154   // equal to that of the current context.
9155   if (CurContext->isRecord()) {
9156     R.setBaseObjectType(
9157                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9158   }
9159 
9160   LookupQualifiedName(R, LookupContext);
9161 
9162   // Try to correct typos if possible. If constructor name lookup finds no
9163   // results, that means the named class has no explicit constructors, and we
9164   // suppressed declaring implicit ones (probably because it's dependent or
9165   // invalid).
9166   if (R.empty() &&
9167       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9168     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9169     // it will believe that glibc provides a ::gets in cases where it does not,
9170     // and will try to pull it into namespace std with a using-declaration.
9171     // Just ignore the using-declaration in that case.
9172     auto *II = NameInfo.getName().getAsIdentifierInfo();
9173     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9174         CurContext->isStdNamespace() &&
9175         isa<TranslationUnitDecl>(LookupContext) &&
9176         getSourceManager().isInSystemHeader(UsingLoc))
9177       return nullptr;
9178     if (TypoCorrection Corrected = CorrectTypo(
9179             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9180             llvm::make_unique<UsingValidatorCCC>(
9181                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9182                 dyn_cast<CXXRecordDecl>(CurContext)),
9183             CTK_ErrorRecovery)) {
9184       // We reject candidates where DroppedSpecifier == true, hence the
9185       // literal '0' below.
9186       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9187                                 << NameInfo.getName() << LookupContext << 0
9188                                 << SS.getRange());
9189 
9190       // If we picked a correction with no attached Decl we can't do anything
9191       // useful with it, bail out.
9192       NamedDecl *ND = Corrected.getCorrectionDecl();
9193       if (!ND)
9194         return BuildInvalid();
9195 
9196       // If we corrected to an inheriting constructor, handle it as one.
9197       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9198       if (RD && RD->isInjectedClassName()) {
9199         // The parent of the injected class name is the class itself.
9200         RD = cast<CXXRecordDecl>(RD->getParent());
9201 
9202         // Fix up the information we'll use to build the using declaration.
9203         if (Corrected.WillReplaceSpecifier()) {
9204           NestedNameSpecifierLocBuilder Builder;
9205           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9206                               QualifierLoc.getSourceRange());
9207           QualifierLoc = Builder.getWithLocInContext(Context);
9208         }
9209 
9210         // In this case, the name we introduce is the name of a derived class
9211         // constructor.
9212         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9213         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9214             Context.getCanonicalType(Context.getRecordType(CurClass))));
9215         UsingName.setNamedTypeInfo(nullptr);
9216         for (auto *Ctor : LookupConstructors(RD))
9217           R.addDecl(Ctor);
9218         R.resolveKind();
9219       } else {
9220         // FIXME: Pick up all the declarations if we found an overloaded
9221         // function.
9222         UsingName.setName(ND->getDeclName());
9223         R.addDecl(ND);
9224       }
9225     } else {
9226       Diag(IdentLoc, diag::err_no_member)
9227         << NameInfo.getName() << LookupContext << SS.getRange();
9228       return BuildInvalid();
9229     }
9230   }
9231 
9232   if (R.isAmbiguous())
9233     return BuildInvalid();
9234 
9235   if (HasTypenameKeyword) {
9236     // If we asked for a typename and got a non-type decl, error out.
9237     if (!R.getAsSingle<TypeDecl>()) {
9238       Diag(IdentLoc, diag::err_using_typename_non_type);
9239       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9240         Diag((*I)->getUnderlyingDecl()->getLocation(),
9241              diag::note_using_decl_target);
9242       return BuildInvalid();
9243     }
9244   } else {
9245     // If we asked for a non-typename and we got a type, error out,
9246     // but only if this is an instantiation of an unresolved using
9247     // decl.  Otherwise just silently find the type name.
9248     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9249       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9250       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9251       return BuildInvalid();
9252     }
9253   }
9254 
9255   // C++14 [namespace.udecl]p6:
9256   // A using-declaration shall not name a namespace.
9257   if (R.getAsSingle<NamespaceDecl>()) {
9258     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9259       << SS.getRange();
9260     return BuildInvalid();
9261   }
9262 
9263   // C++14 [namespace.udecl]p7:
9264   // A using-declaration shall not name a scoped enumerator.
9265   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9266     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9267       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9268         << SS.getRange();
9269       return BuildInvalid();
9270     }
9271   }
9272 
9273   UsingDecl *UD = BuildValid();
9274 
9275   // Some additional rules apply to inheriting constructors.
9276   if (UsingName.getName().getNameKind() ==
9277         DeclarationName::CXXConstructorName) {
9278     // Suppress access diagnostics; the access check is instead performed at the
9279     // point of use for an inheriting constructor.
9280     R.suppressDiagnostics();
9281     if (CheckInheritingConstructorUsingDecl(UD))
9282       return UD;
9283   }
9284 
9285   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9286     UsingShadowDecl *PrevDecl = nullptr;
9287     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9288       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9289   }
9290 
9291   return UD;
9292 }
9293 
9294 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9295                                     ArrayRef<NamedDecl *> Expansions) {
9296   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9297          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9298          isa<UsingPackDecl>(InstantiatedFrom));
9299 
9300   auto *UPD =
9301       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9302   UPD->setAccess(InstantiatedFrom->getAccess());
9303   CurContext->addDecl(UPD);
9304   return UPD;
9305 }
9306 
9307 /// Additional checks for a using declaration referring to a constructor name.
9308 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9309   assert(!UD->hasTypename() && "expecting a constructor name");
9310 
9311   const Type *SourceType = UD->getQualifier()->getAsType();
9312   assert(SourceType &&
9313          "Using decl naming constructor doesn't have type in scope spec.");
9314   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9315 
9316   // Check whether the named type is a direct base class.
9317   bool AnyDependentBases = false;
9318   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9319                                       AnyDependentBases);
9320   if (!Base && !AnyDependentBases) {
9321     Diag(UD->getUsingLoc(),
9322          diag::err_using_decl_constructor_not_in_direct_base)
9323       << UD->getNameInfo().getSourceRange()
9324       << QualType(SourceType, 0) << TargetClass;
9325     UD->setInvalidDecl();
9326     return true;
9327   }
9328 
9329   if (Base)
9330     Base->setInheritConstructors();
9331 
9332   return false;
9333 }
9334 
9335 /// Checks that the given using declaration is not an invalid
9336 /// redeclaration.  Note that this is checking only for the using decl
9337 /// itself, not for any ill-formedness among the UsingShadowDecls.
9338 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9339                                        bool HasTypenameKeyword,
9340                                        const CXXScopeSpec &SS,
9341                                        SourceLocation NameLoc,
9342                                        const LookupResult &Prev) {
9343   NestedNameSpecifier *Qual = SS.getScopeRep();
9344 
9345   // C++03 [namespace.udecl]p8:
9346   // C++0x [namespace.udecl]p10:
9347   //   A using-declaration is a declaration and can therefore be used
9348   //   repeatedly where (and only where) multiple declarations are
9349   //   allowed.
9350   //
9351   // That's in non-member contexts.
9352   if (!CurContext->getRedeclContext()->isRecord()) {
9353     // A dependent qualifier outside a class can only ever resolve to an
9354     // enumeration type. Therefore it conflicts with any other non-type
9355     // declaration in the same scope.
9356     // FIXME: How should we check for dependent type-type conflicts at block
9357     // scope?
9358     if (Qual->isDependent() && !HasTypenameKeyword) {
9359       for (auto *D : Prev) {
9360         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9361           bool OldCouldBeEnumerator =
9362               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9363           Diag(NameLoc,
9364                OldCouldBeEnumerator ? diag::err_redefinition
9365                                     : diag::err_redefinition_different_kind)
9366               << Prev.getLookupName();
9367           Diag(D->getLocation(), diag::note_previous_definition);
9368           return true;
9369         }
9370       }
9371     }
9372     return false;
9373   }
9374 
9375   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9376     NamedDecl *D = *I;
9377 
9378     bool DTypename;
9379     NestedNameSpecifier *DQual;
9380     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9381       DTypename = UD->hasTypename();
9382       DQual = UD->getQualifier();
9383     } else if (UnresolvedUsingValueDecl *UD
9384                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9385       DTypename = false;
9386       DQual = UD->getQualifier();
9387     } else if (UnresolvedUsingTypenameDecl *UD
9388                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9389       DTypename = true;
9390       DQual = UD->getQualifier();
9391     } else continue;
9392 
9393     // using decls differ if one says 'typename' and the other doesn't.
9394     // FIXME: non-dependent using decls?
9395     if (HasTypenameKeyword != DTypename) continue;
9396 
9397     // using decls differ if they name different scopes (but note that
9398     // template instantiation can cause this check to trigger when it
9399     // didn't before instantiation).
9400     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9401         Context.getCanonicalNestedNameSpecifier(DQual))
9402       continue;
9403 
9404     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9405     Diag(D->getLocation(), diag::note_using_decl) << 1;
9406     return true;
9407   }
9408 
9409   return false;
9410 }
9411 
9412 
9413 /// Checks that the given nested-name qualifier used in a using decl
9414 /// in the current context is appropriately related to the current
9415 /// scope.  If an error is found, diagnoses it and returns true.
9416 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9417                                    bool HasTypename,
9418                                    const CXXScopeSpec &SS,
9419                                    const DeclarationNameInfo &NameInfo,
9420                                    SourceLocation NameLoc) {
9421   DeclContext *NamedContext = computeDeclContext(SS);
9422 
9423   if (!CurContext->isRecord()) {
9424     // C++03 [namespace.udecl]p3:
9425     // C++0x [namespace.udecl]p8:
9426     //   A using-declaration for a class member shall be a member-declaration.
9427 
9428     // If we weren't able to compute a valid scope, it might validly be a
9429     // dependent class scope or a dependent enumeration unscoped scope. If
9430     // we have a 'typename' keyword, the scope must resolve to a class type.
9431     if ((HasTypename && !NamedContext) ||
9432         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
9433       auto *RD = NamedContext
9434                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9435                      : nullptr;
9436       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9437         RD = nullptr;
9438 
9439       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9440         << SS.getRange();
9441 
9442       // If we have a complete, non-dependent source type, try to suggest a
9443       // way to get the same effect.
9444       if (!RD)
9445         return true;
9446 
9447       // Find what this using-declaration was referring to.
9448       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9449       R.setHideTags(false);
9450       R.suppressDiagnostics();
9451       LookupQualifiedName(R, RD);
9452 
9453       if (R.getAsSingle<TypeDecl>()) {
9454         if (getLangOpts().CPlusPlus11) {
9455           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9456           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9457             << 0 // alias declaration
9458             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9459                                           NameInfo.getName().getAsString() +
9460                                               " = ");
9461         } else {
9462           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9463           SourceLocation InsertLoc =
9464               getLocForEndOfToken(NameInfo.getLocEnd());
9465           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9466             << 1 // typedef declaration
9467             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9468             << FixItHint::CreateInsertion(
9469                    InsertLoc, " " + NameInfo.getName().getAsString());
9470         }
9471       } else if (R.getAsSingle<VarDecl>()) {
9472         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9473         // repeating the type of the static data member here.
9474         FixItHint FixIt;
9475         if (getLangOpts().CPlusPlus11) {
9476           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9477           FixIt = FixItHint::CreateReplacement(
9478               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9479         }
9480 
9481         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9482           << 2 // reference declaration
9483           << FixIt;
9484       } else if (R.getAsSingle<EnumConstantDecl>()) {
9485         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9486         // repeating the type of the enumeration here, and we can't do so if
9487         // the type is anonymous.
9488         FixItHint FixIt;
9489         if (getLangOpts().CPlusPlus11) {
9490           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9491           FixIt = FixItHint::CreateReplacement(
9492               UsingLoc,
9493               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9494         }
9495 
9496         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9497           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9498           << FixIt;
9499       }
9500       return true;
9501     }
9502 
9503     // Otherwise, this might be valid.
9504     return false;
9505   }
9506 
9507   // The current scope is a record.
9508 
9509   // If the named context is dependent, we can't decide much.
9510   if (!NamedContext) {
9511     // FIXME: in C++0x, we can diagnose if we can prove that the
9512     // nested-name-specifier does not refer to a base class, which is
9513     // still possible in some cases.
9514 
9515     // Otherwise we have to conservatively report that things might be
9516     // okay.
9517     return false;
9518   }
9519 
9520   if (!NamedContext->isRecord()) {
9521     // Ideally this would point at the last name in the specifier,
9522     // but we don't have that level of source info.
9523     Diag(SS.getRange().getBegin(),
9524          diag::err_using_decl_nested_name_specifier_is_not_class)
9525       << SS.getScopeRep() << SS.getRange();
9526     return true;
9527   }
9528 
9529   if (!NamedContext->isDependentContext() &&
9530       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9531     return true;
9532 
9533   if (getLangOpts().CPlusPlus11) {
9534     // C++11 [namespace.udecl]p3:
9535     //   In a using-declaration used as a member-declaration, the
9536     //   nested-name-specifier shall name a base class of the class
9537     //   being defined.
9538 
9539     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9540                                  cast<CXXRecordDecl>(NamedContext))) {
9541       if (CurContext == NamedContext) {
9542         Diag(NameLoc,
9543              diag::err_using_decl_nested_name_specifier_is_current_class)
9544           << SS.getRange();
9545         return true;
9546       }
9547 
9548       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9549         Diag(SS.getRange().getBegin(),
9550              diag::err_using_decl_nested_name_specifier_is_not_base_class)
9551           << SS.getScopeRep()
9552           << cast<CXXRecordDecl>(CurContext)
9553           << SS.getRange();
9554       }
9555       return true;
9556     }
9557 
9558     return false;
9559   }
9560 
9561   // C++03 [namespace.udecl]p4:
9562   //   A using-declaration used as a member-declaration shall refer
9563   //   to a member of a base class of the class being defined [etc.].
9564 
9565   // Salient point: SS doesn't have to name a base class as long as
9566   // lookup only finds members from base classes.  Therefore we can
9567   // diagnose here only if we can prove that that can't happen,
9568   // i.e. if the class hierarchies provably don't intersect.
9569 
9570   // TODO: it would be nice if "definitely valid" results were cached
9571   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9572   // need to be repeated.
9573 
9574   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9575   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9576     Bases.insert(Base);
9577     return true;
9578   };
9579 
9580   // Collect all bases. Return false if we find a dependent base.
9581   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9582     return false;
9583 
9584   // Returns true if the base is dependent or is one of the accumulated base
9585   // classes.
9586   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9587     return !Bases.count(Base);
9588   };
9589 
9590   // Return false if the class has a dependent base or if it or one
9591   // of its bases is present in the base set of the current context.
9592   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9593       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9594     return false;
9595 
9596   Diag(SS.getRange().getBegin(),
9597        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9598     << SS.getScopeRep()
9599     << cast<CXXRecordDecl>(CurContext)
9600     << SS.getRange();
9601 
9602   return true;
9603 }
9604 
9605 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9606                                   AccessSpecifier AS,
9607                                   MultiTemplateParamsArg TemplateParamLists,
9608                                   SourceLocation UsingLoc,
9609                                   UnqualifiedId &Name,
9610                                   AttributeList *AttrList,
9611                                   TypeResult Type,
9612                                   Decl *DeclFromDeclSpec) {
9613   // Skip up to the relevant declaration scope.
9614   while (S->isTemplateParamScope())
9615     S = S->getParent();
9616   assert((S->getFlags() & Scope::DeclScope) &&
9617          "got alias-declaration outside of declaration scope");
9618 
9619   if (Type.isInvalid())
9620     return nullptr;
9621 
9622   bool Invalid = false;
9623   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9624   TypeSourceInfo *TInfo = nullptr;
9625   GetTypeFromParser(Type.get(), &TInfo);
9626 
9627   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9628     return nullptr;
9629 
9630   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9631                                       UPPC_DeclarationType)) {
9632     Invalid = true;
9633     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9634                                              TInfo->getTypeLoc().getBeginLoc());
9635   }
9636 
9637   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9638   LookupName(Previous, S);
9639 
9640   // Warn about shadowing the name of a template parameter.
9641   if (Previous.isSingleResult() &&
9642       Previous.getFoundDecl()->isTemplateParameter()) {
9643     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9644     Previous.clear();
9645   }
9646 
9647   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9648          "name in alias declaration must be an identifier");
9649   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9650                                                Name.StartLocation,
9651                                                Name.Identifier, TInfo);
9652 
9653   NewTD->setAccess(AS);
9654 
9655   if (Invalid)
9656     NewTD->setInvalidDecl();
9657 
9658   ProcessDeclAttributeList(S, NewTD, AttrList);
9659 
9660   CheckTypedefForVariablyModifiedType(S, NewTD);
9661   Invalid |= NewTD->isInvalidDecl();
9662 
9663   bool Redeclaration = false;
9664 
9665   NamedDecl *NewND;
9666   if (TemplateParamLists.size()) {
9667     TypeAliasTemplateDecl *OldDecl = nullptr;
9668     TemplateParameterList *OldTemplateParams = nullptr;
9669 
9670     if (TemplateParamLists.size() != 1) {
9671       Diag(UsingLoc, diag::err_alias_template_extra_headers)
9672         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9673          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9674     }
9675     TemplateParameterList *TemplateParams = TemplateParamLists[0];
9676 
9677     // Check that we can declare a template here.
9678     if (CheckTemplateDeclScope(S, TemplateParams))
9679       return nullptr;
9680 
9681     // Only consider previous declarations in the same scope.
9682     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9683                          /*ExplicitInstantiationOrSpecialization*/false);
9684     if (!Previous.empty()) {
9685       Redeclaration = true;
9686 
9687       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9688       if (!OldDecl && !Invalid) {
9689         Diag(UsingLoc, diag::err_redefinition_different_kind)
9690           << Name.Identifier;
9691 
9692         NamedDecl *OldD = Previous.getRepresentativeDecl();
9693         if (OldD->getLocation().isValid())
9694           Diag(OldD->getLocation(), diag::note_previous_definition);
9695 
9696         Invalid = true;
9697       }
9698 
9699       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9700         if (TemplateParameterListsAreEqual(TemplateParams,
9701                                            OldDecl->getTemplateParameters(),
9702                                            /*Complain=*/true,
9703                                            TPL_TemplateMatch))
9704           OldTemplateParams = OldDecl->getTemplateParameters();
9705         else
9706           Invalid = true;
9707 
9708         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9709         if (!Invalid &&
9710             !Context.hasSameType(OldTD->getUnderlyingType(),
9711                                  NewTD->getUnderlyingType())) {
9712           // FIXME: The C++0x standard does not clearly say this is ill-formed,
9713           // but we can't reasonably accept it.
9714           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9715             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9716           if (OldTD->getLocation().isValid())
9717             Diag(OldTD->getLocation(), diag::note_previous_definition);
9718           Invalid = true;
9719         }
9720       }
9721     }
9722 
9723     // Merge any previous default template arguments into our parameters,
9724     // and check the parameter list.
9725     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9726                                    TPC_TypeAliasTemplate))
9727       return nullptr;
9728 
9729     TypeAliasTemplateDecl *NewDecl =
9730       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9731                                     Name.Identifier, TemplateParams,
9732                                     NewTD);
9733     NewTD->setDescribedAliasTemplate(NewDecl);
9734 
9735     NewDecl->setAccess(AS);
9736 
9737     if (Invalid)
9738       NewDecl->setInvalidDecl();
9739     else if (OldDecl)
9740       NewDecl->setPreviousDecl(OldDecl);
9741 
9742     NewND = NewDecl;
9743   } else {
9744     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9745       setTagNameForLinkagePurposes(TD, NewTD);
9746       handleTagNumbering(TD, S);
9747     }
9748     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9749     NewND = NewTD;
9750   }
9751 
9752   PushOnScopeChains(NewND, S);
9753   ActOnDocumentableDecl(NewND);
9754   return NewND;
9755 }
9756 
9757 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9758                                    SourceLocation AliasLoc,
9759                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
9760                                    SourceLocation IdentLoc,
9761                                    IdentifierInfo *Ident) {
9762 
9763   // Lookup the namespace name.
9764   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9765   LookupParsedName(R, S, &SS);
9766 
9767   if (R.isAmbiguous())
9768     return nullptr;
9769 
9770   if (R.empty()) {
9771     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
9772       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9773       return nullptr;
9774     }
9775   }
9776   assert(!R.isAmbiguous() && !R.empty());
9777   NamedDecl *ND = R.getRepresentativeDecl();
9778 
9779   // Check if we have a previous declaration with the same name.
9780   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9781                      ForRedeclaration);
9782   LookupName(PrevR, S);
9783 
9784   // Check we're not shadowing a template parameter.
9785   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9786     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9787     PrevR.clear();
9788   }
9789 
9790   // Filter out any other lookup result from an enclosing scope.
9791   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9792                        /*AllowInlineNamespace*/false);
9793 
9794   // Find the previous declaration and check that we can redeclare it.
9795   NamespaceAliasDecl *Prev = nullptr;
9796   if (PrevR.isSingleResult()) {
9797     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
9798     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
9799       // We already have an alias with the same name that points to the same
9800       // namespace; check that it matches.
9801       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
9802         Prev = AD;
9803       } else if (isVisible(PrevDecl)) {
9804         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
9805           << Alias;
9806         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
9807           << AD->getNamespace();
9808         return nullptr;
9809       }
9810     } else if (isVisible(PrevDecl)) {
9811       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
9812                             ? diag::err_redefinition
9813                             : diag::err_redefinition_different_kind;
9814       Diag(AliasLoc, DiagID) << Alias;
9815       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
9816       return nullptr;
9817     }
9818   }
9819 
9820   // The use of a nested name specifier may trigger deprecation warnings.
9821   DiagnoseUseOfDecl(ND, IdentLoc);
9822 
9823   NamespaceAliasDecl *AliasDecl =
9824     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
9825                                Alias, SS.getWithLocInContext(Context),
9826                                IdentLoc, ND);
9827   if (Prev)
9828     AliasDecl->setPreviousDecl(Prev);
9829 
9830   PushOnScopeChains(AliasDecl, S);
9831   return AliasDecl;
9832 }
9833 
9834 Sema::ImplicitExceptionSpecification
9835 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
9836                                                CXXMethodDecl *MD) {
9837   CXXRecordDecl *ClassDecl = MD->getParent();
9838 
9839   // C++ [except.spec]p14:
9840   //   An implicitly declared special member function (Clause 12) shall have an
9841   //   exception-specification. [...]
9842   ImplicitExceptionSpecification ExceptSpec(*this);
9843   if (ClassDecl->isInvalidDecl())
9844     return ExceptSpec;
9845 
9846   // Direct base-class constructors.
9847   for (const auto &B : ClassDecl->bases()) {
9848     if (B.isVirtual()) // Handled below.
9849       continue;
9850 
9851     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9852       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9853       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9854       // If this is a deleted function, add it anyway. This might be conformant
9855       // with the standard. This might not. I'm not sure. It might not matter.
9856       if (Constructor)
9857         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9858     }
9859   }
9860 
9861   // Virtual base-class constructors.
9862   for (const auto &B : ClassDecl->vbases()) {
9863     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
9864       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9865       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
9866       // If this is a deleted function, add it anyway. This might be conformant
9867       // with the standard. This might not. I'm not sure. It might not matter.
9868       if (Constructor)
9869         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9870     }
9871   }
9872 
9873   // Field constructors.
9874   for (auto *F : ClassDecl->fields()) {
9875     if (F->hasInClassInitializer()) {
9876       Expr *E = F->getInClassInitializer();
9877       if (!E)
9878         // FIXME: It's a little wasteful to build and throw away a
9879         // CXXDefaultInitExpr here.
9880         E = BuildCXXDefaultInitExpr(Loc, F).get();
9881       if (E)
9882         ExceptSpec.CalledExpr(E);
9883     } else if (const RecordType *RecordTy
9884               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9885       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9886       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9887       // If this is a deleted function, add it anyway. This might be conformant
9888       // with the standard. This might not. I'm not sure. It might not matter.
9889       // In particular, the problem is that this function never gets called. It
9890       // might just be ill-formed because this function attempts to refer to
9891       // a deleted function here.
9892       if (Constructor)
9893         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9894     }
9895   }
9896 
9897   return ExceptSpec;
9898 }
9899 
9900 Sema::ImplicitExceptionSpecification
9901 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
9902                                          CXXConstructorDecl *CD) {
9903   CXXRecordDecl *ClassDecl = CD->getParent();
9904 
9905   // C++ [except.spec]p14:
9906   //   An inheriting constructor [...] shall have an exception-specification. [...]
9907   ImplicitExceptionSpecification ExceptSpec(*this);
9908   if (ClassDecl->isInvalidDecl())
9909     return ExceptSpec;
9910 
9911   auto Inherited = CD->getInheritedConstructor();
9912   InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
9913 
9914   // Direct and virtual base-class constructors.
9915   for (bool VBase : {false, true}) {
9916     for (CXXBaseSpecifier &B :
9917          VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
9918       // Don't visit direct vbases twice.
9919       if (B.isVirtual() != VBase)
9920         continue;
9921 
9922       CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
9923       if (!BaseClass)
9924         continue;
9925 
9926       CXXConstructorDecl *Constructor =
9927           ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
9928               .first;
9929       if (!Constructor)
9930         Constructor = LookupDefaultConstructor(BaseClass);
9931       if (Constructor)
9932         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
9933     }
9934   }
9935 
9936   // Field constructors.
9937   for (const auto *F : ClassDecl->fields()) {
9938     if (F->hasInClassInitializer()) {
9939       if (Expr *E = F->getInClassInitializer())
9940         ExceptSpec.CalledExpr(E);
9941     } else if (const RecordType *RecordTy
9942               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
9943       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
9944       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
9945       if (Constructor)
9946         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9947     }
9948   }
9949 
9950   return ExceptSpec;
9951 }
9952 
9953 namespace {
9954 /// RAII object to register a special member as being currently declared.
9955 struct DeclaringSpecialMember {
9956   Sema &S;
9957   Sema::SpecialMemberDecl D;
9958   Sema::ContextRAII SavedContext;
9959   bool WasAlreadyBeingDeclared;
9960 
9961   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
9962     : S(S), D(RD, CSM), SavedContext(S, RD) {
9963     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
9964     if (WasAlreadyBeingDeclared)
9965       // This almost never happens, but if it does, ensure that our cache
9966       // doesn't contain a stale result.
9967       S.SpecialMemberCache.clear();
9968 
9969     // FIXME: Register a note to be produced if we encounter an error while
9970     // declaring the special member.
9971   }
9972   ~DeclaringSpecialMember() {
9973     if (!WasAlreadyBeingDeclared)
9974       S.SpecialMembersBeingDeclared.erase(D);
9975   }
9976 
9977   /// \brief Are we already trying to declare this special member?
9978   bool isAlreadyBeingDeclared() const {
9979     return WasAlreadyBeingDeclared;
9980   }
9981 };
9982 }
9983 
9984 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
9985   // Look up any existing declarations, but don't trigger declaration of all
9986   // implicit special members with this name.
9987   DeclarationName Name = FD->getDeclName();
9988   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
9989                  ForRedeclaration);
9990   for (auto *D : FD->getParent()->lookup(Name))
9991     if (auto *Acceptable = R.getAcceptableDecl(D))
9992       R.addDecl(Acceptable);
9993   R.resolveKind();
9994   R.suppressDiagnostics();
9995 
9996   CheckFunctionDeclaration(S, FD, R, /*IsExplicitSpecialization*/false);
9997 }
9998 
9999 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10000                                                      CXXRecordDecl *ClassDecl) {
10001   // C++ [class.ctor]p5:
10002   //   A default constructor for a class X is a constructor of class X
10003   //   that can be called without an argument. If there is no
10004   //   user-declared constructor for class X, a default constructor is
10005   //   implicitly declared. An implicitly-declared default constructor
10006   //   is an inline public member of its class.
10007   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10008          "Should not build implicit default constructor!");
10009 
10010   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10011   if (DSM.isAlreadyBeingDeclared())
10012     return nullptr;
10013 
10014   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10015                                                      CXXDefaultConstructor,
10016                                                      false);
10017 
10018   // Create the actual constructor declaration.
10019   CanQualType ClassType
10020     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10021   SourceLocation ClassLoc = ClassDecl->getLocation();
10022   DeclarationName Name
10023     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10024   DeclarationNameInfo NameInfo(Name, ClassLoc);
10025   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10026       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10027       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10028       /*isImplicitlyDeclared=*/true, Constexpr);
10029   DefaultCon->setAccess(AS_public);
10030   DefaultCon->setDefaulted();
10031 
10032   if (getLangOpts().CUDA) {
10033     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10034                                             DefaultCon,
10035                                             /* ConstRHS */ false,
10036                                             /* Diagnose */ false);
10037   }
10038 
10039   // Build an exception specification pointing back at this constructor.
10040   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10041   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10042 
10043   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10044   // constructors is easy to compute.
10045   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10046 
10047   // Note that we have declared this constructor.
10048   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10049 
10050   Scope *S = getScopeForContext(ClassDecl);
10051   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10052 
10053   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10054     SetDeclDeleted(DefaultCon, ClassLoc);
10055 
10056   if (S)
10057     PushOnScopeChains(DefaultCon, S, false);
10058   ClassDecl->addDecl(DefaultCon);
10059 
10060   return DefaultCon;
10061 }
10062 
10063 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10064                                             CXXConstructorDecl *Constructor) {
10065   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10066           !Constructor->doesThisDeclarationHaveABody() &&
10067           !Constructor->isDeleted()) &&
10068     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10069 
10070   CXXRecordDecl *ClassDecl = Constructor->getParent();
10071   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10072 
10073   SynthesizedFunctionScope Scope(*this, Constructor);
10074   DiagnosticErrorTrap Trap(Diags);
10075   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
10076       Trap.hasErrorOccurred()) {
10077     Diag(CurrentLocation, diag::note_member_synthesized_at)
10078       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
10079     Constructor->setInvalidDecl();
10080     return;
10081   }
10082 
10083   // The exception specification is needed because we are defining the
10084   // function.
10085   ResolveExceptionSpec(CurrentLocation,
10086                        Constructor->getType()->castAs<FunctionProtoType>());
10087 
10088   SourceLocation Loc = Constructor->getLocEnd().isValid()
10089                            ? Constructor->getLocEnd()
10090                            : Constructor->getLocation();
10091   Constructor->setBody(new (Context) CompoundStmt(Loc));
10092 
10093   Constructor->markUsed(Context);
10094   MarkVTableUsed(CurrentLocation, ClassDecl);
10095 
10096   if (ASTMutationListener *L = getASTMutationListener()) {
10097     L->CompletedImplicitDefinition(Constructor);
10098   }
10099 
10100   DiagnoseUninitializedFields(*this, Constructor);
10101 }
10102 
10103 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10104   // Perform any delayed checks on exception specifications.
10105   CheckDelayedMemberExceptionSpecs();
10106 }
10107 
10108 /// Find or create the fake constructor we synthesize to model constructing an
10109 /// object of a derived class via a constructor of a base class.
10110 CXXConstructorDecl *
10111 Sema::findInheritingConstructor(SourceLocation Loc,
10112                                 CXXConstructorDecl *BaseCtor,
10113                                 ConstructorUsingShadowDecl *Shadow) {
10114   CXXRecordDecl *Derived = Shadow->getParent();
10115   SourceLocation UsingLoc = Shadow->getLocation();
10116 
10117   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10118   // For now we use the name of the base class constructor as a member of the
10119   // derived class to indicate a (fake) inherited constructor name.
10120   DeclarationName Name = BaseCtor->getDeclName();
10121 
10122   // Check to see if we already have a fake constructor for this inherited
10123   // constructor call.
10124   for (NamedDecl *Ctor : Derived->lookup(Name))
10125     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10126                                ->getInheritedConstructor()
10127                                .getConstructor(),
10128                            BaseCtor))
10129       return cast<CXXConstructorDecl>(Ctor);
10130 
10131   DeclarationNameInfo NameInfo(Name, UsingLoc);
10132   TypeSourceInfo *TInfo =
10133       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10134   FunctionProtoTypeLoc ProtoLoc =
10135       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10136 
10137   // Check the inherited constructor is valid and find the list of base classes
10138   // from which it was inherited.
10139   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10140 
10141   bool Constexpr =
10142       BaseCtor->isConstexpr() &&
10143       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10144                                         false, BaseCtor, &ICI);
10145 
10146   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10147       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10148       BaseCtor->isExplicit(), /*Inline=*/true,
10149       /*ImplicitlyDeclared=*/true, Constexpr,
10150       InheritedConstructor(Shadow, BaseCtor));
10151   if (Shadow->isInvalidDecl())
10152     DerivedCtor->setInvalidDecl();
10153 
10154   // Build an unevaluated exception specification for this fake constructor.
10155   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10156   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10157   EPI.ExceptionSpec.Type = EST_Unevaluated;
10158   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10159   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10160                                                FPT->getParamTypes(), EPI));
10161 
10162   // Build the parameter declarations.
10163   SmallVector<ParmVarDecl *, 16> ParamDecls;
10164   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10165     TypeSourceInfo *TInfo =
10166         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10167     ParmVarDecl *PD = ParmVarDecl::Create(
10168         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10169         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10170     PD->setScopeInfo(0, I);
10171     PD->setImplicit();
10172     // Ensure attributes are propagated onto parameters (this matters for
10173     // format, pass_object_size, ...).
10174     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10175     ParamDecls.push_back(PD);
10176     ProtoLoc.setParam(I, PD);
10177   }
10178 
10179   // Set up the new constructor.
10180   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10181   DerivedCtor->setAccess(BaseCtor->getAccess());
10182   DerivedCtor->setParams(ParamDecls);
10183   Derived->addDecl(DerivedCtor);
10184 
10185   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10186     SetDeclDeleted(DerivedCtor, UsingLoc);
10187 
10188   return DerivedCtor;
10189 }
10190 
10191 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10192   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10193                                Ctor->getInheritedConstructor().getShadowDecl());
10194   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10195                             /*Diagnose*/true);
10196 }
10197 
10198 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10199                                        CXXConstructorDecl *Constructor) {
10200   CXXRecordDecl *ClassDecl = Constructor->getParent();
10201   assert(Constructor->getInheritedConstructor() &&
10202          !Constructor->doesThisDeclarationHaveABody() &&
10203          !Constructor->isDeleted());
10204   if (Constructor->isInvalidDecl())
10205     return;
10206 
10207   ConstructorUsingShadowDecl *Shadow =
10208       Constructor->getInheritedConstructor().getShadowDecl();
10209   CXXConstructorDecl *InheritedCtor =
10210       Constructor->getInheritedConstructor().getConstructor();
10211 
10212   // [class.inhctor.init]p1:
10213   //   initialization proceeds as if a defaulted default constructor is used to
10214   //   initialize the D object and each base class subobject from which the
10215   //   constructor was inherited
10216 
10217   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10218   CXXRecordDecl *RD = Shadow->getParent();
10219   SourceLocation InitLoc = Shadow->getLocation();
10220 
10221   // Initializations are performed "as if by a defaulted default constructor",
10222   // so enter the appropriate scope.
10223   SynthesizedFunctionScope Scope(*this, Constructor);
10224   DiagnosticErrorTrap Trap(Diags);
10225 
10226   // Build explicit initializers for all base classes from which the
10227   // constructor was inherited.
10228   SmallVector<CXXCtorInitializer*, 8> Inits;
10229   for (bool VBase : {false, true}) {
10230     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10231       if (B.isVirtual() != VBase)
10232         continue;
10233 
10234       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10235       if (!BaseRD)
10236         continue;
10237 
10238       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10239       if (!BaseCtor.first)
10240         continue;
10241 
10242       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10243       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10244           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10245 
10246       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10247       Inits.push_back(new (Context) CXXCtorInitializer(
10248           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10249           SourceLocation()));
10250     }
10251   }
10252 
10253   // We now proceed as if for a defaulted default constructor, with the relevant
10254   // initializers replaced.
10255 
10256   bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10257   if (HadError || Trap.hasErrorOccurred()) {
10258     Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
10259     Constructor->setInvalidDecl();
10260     return;
10261   }
10262 
10263   // The exception specification is needed because we are defining the
10264   // function.
10265   ResolveExceptionSpec(CurrentLocation,
10266                        Constructor->getType()->castAs<FunctionProtoType>());
10267 
10268   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10269 
10270   Constructor->markUsed(Context);
10271   MarkVTableUsed(CurrentLocation, ClassDecl);
10272 
10273   if (ASTMutationListener *L = getASTMutationListener()) {
10274     L->CompletedImplicitDefinition(Constructor);
10275   }
10276 
10277   DiagnoseUninitializedFields(*this, Constructor);
10278 }
10279 
10280 Sema::ImplicitExceptionSpecification
10281 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10282   CXXRecordDecl *ClassDecl = MD->getParent();
10283 
10284   // C++ [except.spec]p14:
10285   //   An implicitly declared special member function (Clause 12) shall have
10286   //   an exception-specification.
10287   ImplicitExceptionSpecification ExceptSpec(*this);
10288   if (ClassDecl->isInvalidDecl())
10289     return ExceptSpec;
10290 
10291   // Direct base-class destructors.
10292   for (const auto &B : ClassDecl->bases()) {
10293     if (B.isVirtual()) // Handled below.
10294       continue;
10295 
10296     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10297       ExceptSpec.CalledDecl(B.getLocStart(),
10298                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10299   }
10300 
10301   // Virtual base-class destructors.
10302   for (const auto &B : ClassDecl->vbases()) {
10303     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10304       ExceptSpec.CalledDecl(B.getLocStart(),
10305                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10306   }
10307 
10308   // Field destructors.
10309   for (const auto *F : ClassDecl->fields()) {
10310     if (const RecordType *RecordTy
10311         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
10312       ExceptSpec.CalledDecl(F->getLocation(),
10313                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
10314   }
10315 
10316   return ExceptSpec;
10317 }
10318 
10319 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10320   // C++ [class.dtor]p2:
10321   //   If a class has no user-declared destructor, a destructor is
10322   //   declared implicitly. An implicitly-declared destructor is an
10323   //   inline public member of its class.
10324   assert(ClassDecl->needsImplicitDestructor());
10325 
10326   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10327   if (DSM.isAlreadyBeingDeclared())
10328     return nullptr;
10329 
10330   // Create the actual destructor declaration.
10331   CanQualType ClassType
10332     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10333   SourceLocation ClassLoc = ClassDecl->getLocation();
10334   DeclarationName Name
10335     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10336   DeclarationNameInfo NameInfo(Name, ClassLoc);
10337   CXXDestructorDecl *Destructor
10338       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10339                                   QualType(), nullptr, /*isInline=*/true,
10340                                   /*isImplicitlyDeclared=*/true);
10341   Destructor->setAccess(AS_public);
10342   Destructor->setDefaulted();
10343 
10344   if (getLangOpts().CUDA) {
10345     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10346                                             Destructor,
10347                                             /* ConstRHS */ false,
10348                                             /* Diagnose */ false);
10349   }
10350 
10351   // Build an exception specification pointing back at this destructor.
10352   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10353   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10354 
10355   // We don't need to use SpecialMemberIsTrivial here; triviality for
10356   // destructors is easy to compute.
10357   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10358 
10359   // Note that we have declared this destructor.
10360   ++ASTContext::NumImplicitDestructorsDeclared;
10361 
10362   Scope *S = getScopeForContext(ClassDecl);
10363   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10364 
10365   // We can't check whether an implicit destructor is deleted before we complete
10366   // the definition of the class, because its validity depends on the alignment
10367   // of the class. We'll check this from ActOnFields once the class is complete.
10368   if (ClassDecl->isCompleteDefinition() &&
10369       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10370     SetDeclDeleted(Destructor, ClassLoc);
10371 
10372   // Introduce this destructor into its scope.
10373   if (S)
10374     PushOnScopeChains(Destructor, S, false);
10375   ClassDecl->addDecl(Destructor);
10376 
10377   return Destructor;
10378 }
10379 
10380 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10381                                     CXXDestructorDecl *Destructor) {
10382   assert((Destructor->isDefaulted() &&
10383           !Destructor->doesThisDeclarationHaveABody() &&
10384           !Destructor->isDeleted()) &&
10385          "DefineImplicitDestructor - call it for implicit default dtor");
10386   CXXRecordDecl *ClassDecl = Destructor->getParent();
10387   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10388 
10389   if (Destructor->isInvalidDecl())
10390     return;
10391 
10392   SynthesizedFunctionScope Scope(*this, Destructor);
10393 
10394   DiagnosticErrorTrap Trap(Diags);
10395   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10396                                          Destructor->getParent());
10397 
10398   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
10399     Diag(CurrentLocation, diag::note_member_synthesized_at)
10400       << CXXDestructor << Context.getTagDeclType(ClassDecl);
10401 
10402     Destructor->setInvalidDecl();
10403     return;
10404   }
10405 
10406   // The exception specification is needed because we are defining the
10407   // function.
10408   ResolveExceptionSpec(CurrentLocation,
10409                        Destructor->getType()->castAs<FunctionProtoType>());
10410 
10411   SourceLocation Loc = Destructor->getLocEnd().isValid()
10412                            ? Destructor->getLocEnd()
10413                            : Destructor->getLocation();
10414   Destructor->setBody(new (Context) CompoundStmt(Loc));
10415   Destructor->markUsed(Context);
10416   MarkVTableUsed(CurrentLocation, ClassDecl);
10417 
10418   if (ASTMutationListener *L = getASTMutationListener()) {
10419     L->CompletedImplicitDefinition(Destructor);
10420   }
10421 }
10422 
10423 /// \brief Perform any semantic analysis which needs to be delayed until all
10424 /// pending class member declarations have been parsed.
10425 void Sema::ActOnFinishCXXMemberDecls() {
10426   // If the context is an invalid C++ class, just suppress these checks.
10427   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10428     if (Record->isInvalidDecl()) {
10429       DelayedDefaultedMemberExceptionSpecs.clear();
10430       DelayedExceptionSpecChecks.clear();
10431       return;
10432     }
10433     checkForMultipleExportedDefaultConstructors(*this, Record);
10434   }
10435 }
10436 
10437 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10438   referenceDLLExportedClassMethods();
10439 }
10440 
10441 void Sema::referenceDLLExportedClassMethods() {
10442   if (!DelayedDllExportClasses.empty()) {
10443     // Calling ReferenceDllExportedMethods might cause the current function to
10444     // be called again, so use a local copy of DelayedDllExportClasses.
10445     SmallVector<CXXRecordDecl *, 4> WorkList;
10446     std::swap(DelayedDllExportClasses, WorkList);
10447     for (CXXRecordDecl *Class : WorkList)
10448       ReferenceDllExportedMethods(*this, Class);
10449   }
10450 }
10451 
10452 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10453                                          CXXDestructorDecl *Destructor) {
10454   assert(getLangOpts().CPlusPlus11 &&
10455          "adjusting dtor exception specs was introduced in c++11");
10456 
10457   // C++11 [class.dtor]p3:
10458   //   A declaration of a destructor that does not have an exception-
10459   //   specification is implicitly considered to have the same exception-
10460   //   specification as an implicit declaration.
10461   const FunctionProtoType *DtorType = Destructor->getType()->
10462                                         getAs<FunctionProtoType>();
10463   if (DtorType->hasExceptionSpec())
10464     return;
10465 
10466   // Replace the destructor's type, building off the existing one. Fortunately,
10467   // the only thing of interest in the destructor type is its extended info.
10468   // The return and arguments are fixed.
10469   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10470   EPI.ExceptionSpec.Type = EST_Unevaluated;
10471   EPI.ExceptionSpec.SourceDecl = Destructor;
10472   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10473 
10474   // FIXME: If the destructor has a body that could throw, and the newly created
10475   // spec doesn't allow exceptions, we should emit a warning, because this
10476   // change in behavior can break conforming C++03 programs at runtime.
10477   // However, we don't have a body or an exception specification yet, so it
10478   // needs to be done somewhere else.
10479 }
10480 
10481 namespace {
10482 /// \brief An abstract base class for all helper classes used in building the
10483 //  copy/move operators. These classes serve as factory functions and help us
10484 //  avoid using the same Expr* in the AST twice.
10485 class ExprBuilder {
10486   ExprBuilder(const ExprBuilder&) = delete;
10487   ExprBuilder &operator=(const ExprBuilder&) = delete;
10488 
10489 protected:
10490   static Expr *assertNotNull(Expr *E) {
10491     assert(E && "Expression construction must not fail.");
10492     return E;
10493   }
10494 
10495 public:
10496   ExprBuilder() {}
10497   virtual ~ExprBuilder() {}
10498 
10499   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10500 };
10501 
10502 class RefBuilder: public ExprBuilder {
10503   VarDecl *Var;
10504   QualType VarType;
10505 
10506 public:
10507   Expr *build(Sema &S, SourceLocation Loc) const override {
10508     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10509   }
10510 
10511   RefBuilder(VarDecl *Var, QualType VarType)
10512       : Var(Var), VarType(VarType) {}
10513 };
10514 
10515 class ThisBuilder: public ExprBuilder {
10516 public:
10517   Expr *build(Sema &S, SourceLocation Loc) const override {
10518     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10519   }
10520 };
10521 
10522 class CastBuilder: public ExprBuilder {
10523   const ExprBuilder &Builder;
10524   QualType Type;
10525   ExprValueKind Kind;
10526   const CXXCastPath &Path;
10527 
10528 public:
10529   Expr *build(Sema &S, SourceLocation Loc) const override {
10530     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10531                                              CK_UncheckedDerivedToBase, Kind,
10532                                              &Path).get());
10533   }
10534 
10535   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10536               const CXXCastPath &Path)
10537       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10538 };
10539 
10540 class DerefBuilder: public ExprBuilder {
10541   const ExprBuilder &Builder;
10542 
10543 public:
10544   Expr *build(Sema &S, SourceLocation Loc) const override {
10545     return assertNotNull(
10546         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10547   }
10548 
10549   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10550 };
10551 
10552 class MemberBuilder: public ExprBuilder {
10553   const ExprBuilder &Builder;
10554   QualType Type;
10555   CXXScopeSpec SS;
10556   bool IsArrow;
10557   LookupResult &MemberLookup;
10558 
10559 public:
10560   Expr *build(Sema &S, SourceLocation Loc) const override {
10561     return assertNotNull(S.BuildMemberReferenceExpr(
10562         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10563         nullptr, MemberLookup, nullptr, nullptr).get());
10564   }
10565 
10566   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10567                 LookupResult &MemberLookup)
10568       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10569         MemberLookup(MemberLookup) {}
10570 };
10571 
10572 class MoveCastBuilder: public ExprBuilder {
10573   const ExprBuilder &Builder;
10574 
10575 public:
10576   Expr *build(Sema &S, SourceLocation Loc) const override {
10577     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10578   }
10579 
10580   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10581 };
10582 
10583 class LvalueConvBuilder: public ExprBuilder {
10584   const ExprBuilder &Builder;
10585 
10586 public:
10587   Expr *build(Sema &S, SourceLocation Loc) const override {
10588     return assertNotNull(
10589         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10590   }
10591 
10592   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10593 };
10594 
10595 class SubscriptBuilder: public ExprBuilder {
10596   const ExprBuilder &Base;
10597   const ExprBuilder &Index;
10598 
10599 public:
10600   Expr *build(Sema &S, SourceLocation Loc) const override {
10601     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10602         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10603   }
10604 
10605   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10606       : Base(Base), Index(Index) {}
10607 };
10608 
10609 } // end anonymous namespace
10610 
10611 /// When generating a defaulted copy or move assignment operator, if a field
10612 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10613 /// do so. This optimization only applies for arrays of scalars, and for arrays
10614 /// of class type where the selected copy/move-assignment operator is trivial.
10615 static StmtResult
10616 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10617                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10618   // Compute the size of the memory buffer to be copied.
10619   QualType SizeType = S.Context.getSizeType();
10620   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10621                    S.Context.getTypeSizeInChars(T).getQuantity());
10622 
10623   // Take the address of the field references for "from" and "to". We
10624   // directly construct UnaryOperators here because semantic analysis
10625   // does not permit us to take the address of an xvalue.
10626   Expr *From = FromB.build(S, Loc);
10627   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10628                          S.Context.getPointerType(From->getType()),
10629                          VK_RValue, OK_Ordinary, Loc);
10630   Expr *To = ToB.build(S, Loc);
10631   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10632                        S.Context.getPointerType(To->getType()),
10633                        VK_RValue, OK_Ordinary, Loc);
10634 
10635   const Type *E = T->getBaseElementTypeUnsafe();
10636   bool NeedsCollectableMemCpy =
10637     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10638 
10639   // Create a reference to the __builtin_objc_memmove_collectable function
10640   StringRef MemCpyName = NeedsCollectableMemCpy ?
10641     "__builtin_objc_memmove_collectable" :
10642     "__builtin_memcpy";
10643   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10644                  Sema::LookupOrdinaryName);
10645   S.LookupName(R, S.TUScope, true);
10646 
10647   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10648   if (!MemCpy)
10649     // Something went horribly wrong earlier, and we will have complained
10650     // about it.
10651     return StmtError();
10652 
10653   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10654                                             VK_RValue, Loc, nullptr);
10655   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10656 
10657   Expr *CallArgs[] = {
10658     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10659   };
10660   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10661                                     Loc, CallArgs, Loc);
10662 
10663   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10664   return Call.getAs<Stmt>();
10665 }
10666 
10667 /// \brief Builds a statement that copies/moves the given entity from \p From to
10668 /// \c To.
10669 ///
10670 /// This routine is used to copy/move the members of a class with an
10671 /// implicitly-declared copy/move assignment operator. When the entities being
10672 /// copied are arrays, this routine builds for loops to copy them.
10673 ///
10674 /// \param S The Sema object used for type-checking.
10675 ///
10676 /// \param Loc The location where the implicit copy/move is being generated.
10677 ///
10678 /// \param T The type of the expressions being copied/moved. Both expressions
10679 /// must have this type.
10680 ///
10681 /// \param To The expression we are copying/moving to.
10682 ///
10683 /// \param From The expression we are copying/moving from.
10684 ///
10685 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10686 /// Otherwise, it's a non-static member subobject.
10687 ///
10688 /// \param Copying Whether we're copying or moving.
10689 ///
10690 /// \param Depth Internal parameter recording the depth of the recursion.
10691 ///
10692 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10693 /// if a memcpy should be used instead.
10694 static StmtResult
10695 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10696                                  const ExprBuilder &To, const ExprBuilder &From,
10697                                  bool CopyingBaseSubobject, bool Copying,
10698                                  unsigned Depth = 0) {
10699   // C++11 [class.copy]p28:
10700   //   Each subobject is assigned in the manner appropriate to its type:
10701   //
10702   //     - if the subobject is of class type, as if by a call to operator= with
10703   //       the subobject as the object expression and the corresponding
10704   //       subobject of x as a single function argument (as if by explicit
10705   //       qualification; that is, ignoring any possible virtual overriding
10706   //       functions in more derived classes);
10707   //
10708   // C++03 [class.copy]p13:
10709   //     - if the subobject is of class type, the copy assignment operator for
10710   //       the class is used (as if by explicit qualification; that is,
10711   //       ignoring any possible virtual overriding functions in more derived
10712   //       classes);
10713   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10714     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10715 
10716     // Look for operator=.
10717     DeclarationName Name
10718       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10719     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10720     S.LookupQualifiedName(OpLookup, ClassDecl, false);
10721 
10722     // Prior to C++11, filter out any result that isn't a copy/move-assignment
10723     // operator.
10724     if (!S.getLangOpts().CPlusPlus11) {
10725       LookupResult::Filter F = OpLookup.makeFilter();
10726       while (F.hasNext()) {
10727         NamedDecl *D = F.next();
10728         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10729           if (Method->isCopyAssignmentOperator() ||
10730               (!Copying && Method->isMoveAssignmentOperator()))
10731             continue;
10732 
10733         F.erase();
10734       }
10735       F.done();
10736     }
10737 
10738     // Suppress the protected check (C++ [class.protected]) for each of the
10739     // assignment operators we found. This strange dance is required when
10740     // we're assigning via a base classes's copy-assignment operator. To
10741     // ensure that we're getting the right base class subobject (without
10742     // ambiguities), we need to cast "this" to that subobject type; to
10743     // ensure that we don't go through the virtual call mechanism, we need
10744     // to qualify the operator= name with the base class (see below). However,
10745     // this means that if the base class has a protected copy assignment
10746     // operator, the protected member access check will fail. So, we
10747     // rewrite "protected" access to "public" access in this case, since we
10748     // know by construction that we're calling from a derived class.
10749     if (CopyingBaseSubobject) {
10750       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10751            L != LEnd; ++L) {
10752         if (L.getAccess() == AS_protected)
10753           L.setAccess(AS_public);
10754       }
10755     }
10756 
10757     // Create the nested-name-specifier that will be used to qualify the
10758     // reference to operator=; this is required to suppress the virtual
10759     // call mechanism.
10760     CXXScopeSpec SS;
10761     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
10762     SS.MakeTrivial(S.Context,
10763                    NestedNameSpecifier::Create(S.Context, nullptr, false,
10764                                                CanonicalT),
10765                    Loc);
10766 
10767     // Create the reference to operator=.
10768     ExprResult OpEqualRef
10769       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10770                                    SS, /*TemplateKWLoc=*/SourceLocation(),
10771                                    /*FirstQualifierInScope=*/nullptr,
10772                                    OpLookup,
10773                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
10774                                    /*SuppressQualifierCheck=*/true);
10775     if (OpEqualRef.isInvalid())
10776       return StmtError();
10777 
10778     // Build the call to the assignment operator.
10779 
10780     Expr *FromInst = From.build(S, Loc);
10781     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
10782                                                   OpEqualRef.getAs<Expr>(),
10783                                                   Loc, FromInst, Loc);
10784     if (Call.isInvalid())
10785       return StmtError();
10786 
10787     // If we built a call to a trivial 'operator=' while copying an array,
10788     // bail out. We'll replace the whole shebang with a memcpy.
10789     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10790     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
10791       return StmtResult((Stmt*)nullptr);
10792 
10793     // Convert to an expression-statement, and clean up any produced
10794     // temporaries.
10795     return S.ActOnExprStmt(Call);
10796   }
10797 
10798   //     - if the subobject is of scalar type, the built-in assignment
10799   //       operator is used.
10800   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
10801   if (!ArrayTy) {
10802     ExprResult Assignment = S.CreateBuiltinBinOp(
10803         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
10804     if (Assignment.isInvalid())
10805       return StmtError();
10806     return S.ActOnExprStmt(Assignment);
10807   }
10808 
10809   //     - if the subobject is an array, each element is assigned, in the
10810   //       manner appropriate to the element type;
10811 
10812   // Construct a loop over the array bounds, e.g.,
10813   //
10814   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
10815   //
10816   // that will copy each of the array elements.
10817   QualType SizeType = S.Context.getSizeType();
10818 
10819   // Create the iteration variable.
10820   IdentifierInfo *IterationVarName = nullptr;
10821   {
10822     SmallString<8> Str;
10823     llvm::raw_svector_ostream OS(Str);
10824     OS << "__i" << Depth;
10825     IterationVarName = &S.Context.Idents.get(OS.str());
10826   }
10827   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10828                                           IterationVarName, SizeType,
10829                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10830                                           SC_None);
10831 
10832   // Initialize the iteration variable to zero.
10833   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
10834   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
10835 
10836   // Creates a reference to the iteration variable.
10837   RefBuilder IterationVarRef(IterationVar, SizeType);
10838   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
10839 
10840   // Create the DeclStmt that holds the iteration variable.
10841   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
10842 
10843   // Subscript the "from" and "to" expressions with the iteration variable.
10844   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
10845   MoveCastBuilder FromIndexMove(FromIndexCopy);
10846   const ExprBuilder *FromIndex;
10847   if (Copying)
10848     FromIndex = &FromIndexCopy;
10849   else
10850     FromIndex = &FromIndexMove;
10851 
10852   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
10853 
10854   // Build the copy/move for an individual element of the array.
10855   StmtResult Copy =
10856     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
10857                                      ToIndex, *FromIndex, CopyingBaseSubobject,
10858                                      Copying, Depth + 1);
10859   // Bail out if copying fails or if we determined that we should use memcpy.
10860   if (Copy.isInvalid() || !Copy.get())
10861     return Copy;
10862 
10863   // Create the comparison against the array bound.
10864   llvm::APInt Upper
10865     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
10866   Expr *Comparison
10867     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
10868                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
10869                                      BO_NE, S.Context.BoolTy,
10870                                      VK_RValue, OK_Ordinary, Loc, false);
10871 
10872   // Create the pre-increment of the iteration variable.
10873   Expr *Increment
10874     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
10875                                     SizeType, VK_LValue, OK_Ordinary, Loc);
10876 
10877   // Construct the loop that copies all elements of this array.
10878   return S.ActOnForStmt(
10879       Loc, Loc, InitStmt,
10880       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
10881       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
10882 }
10883 
10884 static StmtResult
10885 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
10886                       const ExprBuilder &To, const ExprBuilder &From,
10887                       bool CopyingBaseSubobject, bool Copying) {
10888   // Maybe we should use a memcpy?
10889   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
10890       T.isTriviallyCopyableType(S.Context))
10891     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10892 
10893   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
10894                                                      CopyingBaseSubobject,
10895                                                      Copying, 0));
10896 
10897   // If we ended up picking a trivial assignment operator for an array of a
10898   // non-trivially-copyable class type, just emit a memcpy.
10899   if (!Result.isInvalid() && !Result.get())
10900     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
10901 
10902   return Result;
10903 }
10904 
10905 Sema::ImplicitExceptionSpecification
10906 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
10907   CXXRecordDecl *ClassDecl = MD->getParent();
10908 
10909   ImplicitExceptionSpecification ExceptSpec(*this);
10910   if (ClassDecl->isInvalidDecl())
10911     return ExceptSpec;
10912 
10913   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10914   assert(T->getNumParams() == 1 && "not a copy assignment op");
10915   unsigned ArgQuals =
10916       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
10917 
10918   // C++ [except.spec]p14:
10919   //   An implicitly declared special member function (Clause 12) shall have an
10920   //   exception-specification. [...]
10921 
10922   // It is unspecified whether or not an implicit copy assignment operator
10923   // attempts to deduplicate calls to assignment operators of virtual bases are
10924   // made. As such, this exception specification is effectively unspecified.
10925   // Based on a similar decision made for constness in C++0x, we're erring on
10926   // the side of assuming such calls to be made regardless of whether they
10927   // actually happen.
10928   for (const auto &Base : ClassDecl->bases()) {
10929     if (Base.isVirtual())
10930       continue;
10931 
10932     CXXRecordDecl *BaseClassDecl
10933       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10934     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10935                                                             ArgQuals, false, 0))
10936       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10937   }
10938 
10939   for (const auto &Base : ClassDecl->vbases()) {
10940     CXXRecordDecl *BaseClassDecl
10941       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
10942     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
10943                                                             ArgQuals, false, 0))
10944       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
10945   }
10946 
10947   for (const auto *Field : ClassDecl->fields()) {
10948     QualType FieldType = Context.getBaseElementType(Field->getType());
10949     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10950       if (CXXMethodDecl *CopyAssign =
10951           LookupCopyingAssignment(FieldClassDecl,
10952                                   ArgQuals | FieldType.getCVRQualifiers(),
10953                                   false, 0))
10954         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
10955     }
10956   }
10957 
10958   return ExceptSpec;
10959 }
10960 
10961 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
10962   // Note: The following rules are largely analoguous to the copy
10963   // constructor rules. Note that virtual bases are not taken into account
10964   // for determining the argument type of the operator. Note also that
10965   // operators taking an object instead of a reference are allowed.
10966   assert(ClassDecl->needsImplicitCopyAssignment());
10967 
10968   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
10969   if (DSM.isAlreadyBeingDeclared())
10970     return nullptr;
10971 
10972   QualType ArgType = Context.getTypeDeclType(ClassDecl);
10973   QualType RetType = Context.getLValueReferenceType(ArgType);
10974   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
10975   if (Const)
10976     ArgType = ArgType.withConst();
10977   ArgType = Context.getLValueReferenceType(ArgType);
10978 
10979   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10980                                                      CXXCopyAssignment,
10981                                                      Const);
10982 
10983   //   An implicitly-declared copy assignment operator is an inline public
10984   //   member of its class.
10985   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10986   SourceLocation ClassLoc = ClassDecl->getLocation();
10987   DeclarationNameInfo NameInfo(Name, ClassLoc);
10988   CXXMethodDecl *CopyAssignment =
10989       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
10990                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
10991                             /*isInline=*/true, Constexpr, SourceLocation());
10992   CopyAssignment->setAccess(AS_public);
10993   CopyAssignment->setDefaulted();
10994   CopyAssignment->setImplicit();
10995 
10996   if (getLangOpts().CUDA) {
10997     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
10998                                             CopyAssignment,
10999                                             /* ConstRHS */ Const,
11000                                             /* Diagnose */ false);
11001   }
11002 
11003   // Build an exception specification pointing back at this member.
11004   FunctionProtoType::ExtProtoInfo EPI =
11005       getImplicitMethodEPI(*this, CopyAssignment);
11006   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11007 
11008   // Add the parameter to the operator.
11009   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11010                                                ClassLoc, ClassLoc,
11011                                                /*Id=*/nullptr, ArgType,
11012                                                /*TInfo=*/nullptr, SC_None,
11013                                                nullptr);
11014   CopyAssignment->setParams(FromParam);
11015 
11016   CopyAssignment->setTrivial(
11017     ClassDecl->needsOverloadResolutionForCopyAssignment()
11018       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11019       : ClassDecl->hasTrivialCopyAssignment());
11020 
11021   // Note that we have added this copy-assignment operator.
11022   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11023 
11024   Scope *S = getScopeForContext(ClassDecl);
11025   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11026 
11027   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11028     SetDeclDeleted(CopyAssignment, ClassLoc);
11029 
11030   if (S)
11031     PushOnScopeChains(CopyAssignment, S, false);
11032   ClassDecl->addDecl(CopyAssignment);
11033 
11034   return CopyAssignment;
11035 }
11036 
11037 /// Diagnose an implicit copy operation for a class which is odr-used, but
11038 /// which is deprecated because the class has a user-declared copy constructor,
11039 /// copy assignment operator, or destructor.
11040 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11041                                             SourceLocation UseLoc) {
11042   assert(CopyOp->isImplicit());
11043 
11044   CXXRecordDecl *RD = CopyOp->getParent();
11045   CXXMethodDecl *UserDeclaredOperation = nullptr;
11046 
11047   // In Microsoft mode, assignment operations don't affect constructors and
11048   // vice versa.
11049   if (RD->hasUserDeclaredDestructor()) {
11050     UserDeclaredOperation = RD->getDestructor();
11051   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11052              RD->hasUserDeclaredCopyConstructor() &&
11053              !S.getLangOpts().MSVCCompat) {
11054     // Find any user-declared copy constructor.
11055     for (auto *I : RD->ctors()) {
11056       if (I->isCopyConstructor()) {
11057         UserDeclaredOperation = I;
11058         break;
11059       }
11060     }
11061     assert(UserDeclaredOperation);
11062   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11063              RD->hasUserDeclaredCopyAssignment() &&
11064              !S.getLangOpts().MSVCCompat) {
11065     // Find any user-declared move assignment operator.
11066     for (auto *I : RD->methods()) {
11067       if (I->isCopyAssignmentOperator()) {
11068         UserDeclaredOperation = I;
11069         break;
11070       }
11071     }
11072     assert(UserDeclaredOperation);
11073   }
11074 
11075   if (UserDeclaredOperation) {
11076     S.Diag(UserDeclaredOperation->getLocation(),
11077          diag::warn_deprecated_copy_operation)
11078       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11079       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11080     S.Diag(UseLoc, diag::note_member_synthesized_at)
11081       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11082                                           : Sema::CXXCopyAssignment)
11083       << RD;
11084   }
11085 }
11086 
11087 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11088                                         CXXMethodDecl *CopyAssignOperator) {
11089   assert((CopyAssignOperator->isDefaulted() &&
11090           CopyAssignOperator->isOverloadedOperator() &&
11091           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11092           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11093           !CopyAssignOperator->isDeleted()) &&
11094          "DefineImplicitCopyAssignment called for wrong function");
11095 
11096   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11097 
11098   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11099     CopyAssignOperator->setInvalidDecl();
11100     return;
11101   }
11102 
11103   // C++11 [class.copy]p18:
11104   //   The [definition of an implicitly declared copy assignment operator] is
11105   //   deprecated if the class has a user-declared copy constructor or a
11106   //   user-declared destructor.
11107   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11108     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11109 
11110   CopyAssignOperator->markUsed(Context);
11111 
11112   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11113   DiagnosticErrorTrap Trap(Diags);
11114 
11115   // C++0x [class.copy]p30:
11116   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11117   //   for a non-union class X performs memberwise copy assignment of its
11118   //   subobjects. The direct base classes of X are assigned first, in the
11119   //   order of their declaration in the base-specifier-list, and then the
11120   //   immediate non-static data members of X are assigned, in the order in
11121   //   which they were declared in the class definition.
11122 
11123   // The statements that form the synthesized function body.
11124   SmallVector<Stmt*, 8> Statements;
11125 
11126   // The parameter for the "other" object, which we are copying from.
11127   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11128   Qualifiers OtherQuals = Other->getType().getQualifiers();
11129   QualType OtherRefType = Other->getType();
11130   if (const LValueReferenceType *OtherRef
11131                                 = OtherRefType->getAs<LValueReferenceType>()) {
11132     OtherRefType = OtherRef->getPointeeType();
11133     OtherQuals = OtherRefType.getQualifiers();
11134   }
11135 
11136   // Our location for everything implicitly-generated.
11137   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11138                            ? CopyAssignOperator->getLocEnd()
11139                            : CopyAssignOperator->getLocation();
11140 
11141   // Builds a DeclRefExpr for the "other" object.
11142   RefBuilder OtherRef(Other, OtherRefType);
11143 
11144   // Builds the "this" pointer.
11145   ThisBuilder This;
11146 
11147   // Assign base classes.
11148   bool Invalid = false;
11149   for (auto &Base : ClassDecl->bases()) {
11150     // Form the assignment:
11151     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11152     QualType BaseType = Base.getType().getUnqualifiedType();
11153     if (!BaseType->isRecordType()) {
11154       Invalid = true;
11155       continue;
11156     }
11157 
11158     CXXCastPath BasePath;
11159     BasePath.push_back(&Base);
11160 
11161     // Construct the "from" expression, which is an implicit cast to the
11162     // appropriately-qualified base type.
11163     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11164                      VK_LValue, BasePath);
11165 
11166     // Dereference "this".
11167     DerefBuilder DerefThis(This);
11168     CastBuilder To(DerefThis,
11169                    Context.getCVRQualifiedType(
11170                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11171                    VK_LValue, BasePath);
11172 
11173     // Build the copy.
11174     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11175                                             To, From,
11176                                             /*CopyingBaseSubobject=*/true,
11177                                             /*Copying=*/true);
11178     if (Copy.isInvalid()) {
11179       Diag(CurrentLocation, diag::note_member_synthesized_at)
11180         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11181       CopyAssignOperator->setInvalidDecl();
11182       return;
11183     }
11184 
11185     // Success! Record the copy.
11186     Statements.push_back(Copy.getAs<Expr>());
11187   }
11188 
11189   // Assign non-static members.
11190   for (auto *Field : ClassDecl->fields()) {
11191     // FIXME: We should form some kind of AST representation for the implied
11192     // memcpy in a union copy operation.
11193     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11194       continue;
11195 
11196     if (Field->isInvalidDecl()) {
11197       Invalid = true;
11198       continue;
11199     }
11200 
11201     // Check for members of reference type; we can't copy those.
11202     if (Field->getType()->isReferenceType()) {
11203       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11204         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11205       Diag(Field->getLocation(), diag::note_declared_at);
11206       Diag(CurrentLocation, diag::note_member_synthesized_at)
11207         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11208       Invalid = true;
11209       continue;
11210     }
11211 
11212     // Check for members of const-qualified, non-class type.
11213     QualType BaseType = Context.getBaseElementType(Field->getType());
11214     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11215       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11216         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11217       Diag(Field->getLocation(), diag::note_declared_at);
11218       Diag(CurrentLocation, diag::note_member_synthesized_at)
11219         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11220       Invalid = true;
11221       continue;
11222     }
11223 
11224     // Suppress assigning zero-width bitfields.
11225     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11226       continue;
11227 
11228     QualType FieldType = Field->getType().getNonReferenceType();
11229     if (FieldType->isIncompleteArrayType()) {
11230       assert(ClassDecl->hasFlexibleArrayMember() &&
11231              "Incomplete array type is not valid");
11232       continue;
11233     }
11234 
11235     // Build references to the field in the object we're copying from and to.
11236     CXXScopeSpec SS; // Intentionally empty
11237     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11238                               LookupMemberName);
11239     MemberLookup.addDecl(Field);
11240     MemberLookup.resolveKind();
11241 
11242     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11243 
11244     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11245 
11246     // Build the copy of this field.
11247     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11248                                             To, From,
11249                                             /*CopyingBaseSubobject=*/false,
11250                                             /*Copying=*/true);
11251     if (Copy.isInvalid()) {
11252       Diag(CurrentLocation, diag::note_member_synthesized_at)
11253         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11254       CopyAssignOperator->setInvalidDecl();
11255       return;
11256     }
11257 
11258     // Success! Record the copy.
11259     Statements.push_back(Copy.getAs<Stmt>());
11260   }
11261 
11262   if (!Invalid) {
11263     // Add a "return *this;"
11264     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11265 
11266     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11267     if (Return.isInvalid())
11268       Invalid = true;
11269     else {
11270       Statements.push_back(Return.getAs<Stmt>());
11271 
11272       if (Trap.hasErrorOccurred()) {
11273         Diag(CurrentLocation, diag::note_member_synthesized_at)
11274           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11275         Invalid = true;
11276       }
11277     }
11278   }
11279 
11280   // The exception specification is needed because we are defining the
11281   // function.
11282   ResolveExceptionSpec(CurrentLocation,
11283                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11284 
11285   if (Invalid) {
11286     CopyAssignOperator->setInvalidDecl();
11287     return;
11288   }
11289 
11290   StmtResult Body;
11291   {
11292     CompoundScopeRAII CompoundScope(*this);
11293     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11294                              /*isStmtExpr=*/false);
11295     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11296   }
11297   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11298 
11299   if (ASTMutationListener *L = getASTMutationListener()) {
11300     L->CompletedImplicitDefinition(CopyAssignOperator);
11301   }
11302 }
11303 
11304 Sema::ImplicitExceptionSpecification
11305 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11306   CXXRecordDecl *ClassDecl = MD->getParent();
11307 
11308   ImplicitExceptionSpecification ExceptSpec(*this);
11309   if (ClassDecl->isInvalidDecl())
11310     return ExceptSpec;
11311 
11312   // C++0x [except.spec]p14:
11313   //   An implicitly declared special member function (Clause 12) shall have an
11314   //   exception-specification. [...]
11315 
11316   // It is unspecified whether or not an implicit move assignment operator
11317   // attempts to deduplicate calls to assignment operators of virtual bases are
11318   // made. As such, this exception specification is effectively unspecified.
11319   // Based on a similar decision made for constness in C++0x, we're erring on
11320   // the side of assuming such calls to be made regardless of whether they
11321   // actually happen.
11322   // Note that a move constructor is not implicitly declared when there are
11323   // virtual bases, but it can still be user-declared and explicitly defaulted.
11324   for (const auto &Base : ClassDecl->bases()) {
11325     if (Base.isVirtual())
11326       continue;
11327 
11328     CXXRecordDecl *BaseClassDecl
11329       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11330     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11331                                                            0, false, 0))
11332       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11333   }
11334 
11335   for (const auto &Base : ClassDecl->vbases()) {
11336     CXXRecordDecl *BaseClassDecl
11337       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11338     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11339                                                            0, false, 0))
11340       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11341   }
11342 
11343   for (const auto *Field : ClassDecl->fields()) {
11344     QualType FieldType = Context.getBaseElementType(Field->getType());
11345     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11346       if (CXXMethodDecl *MoveAssign =
11347               LookupMovingAssignment(FieldClassDecl,
11348                                      FieldType.getCVRQualifiers(),
11349                                      false, 0))
11350         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
11351     }
11352   }
11353 
11354   return ExceptSpec;
11355 }
11356 
11357 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11358   assert(ClassDecl->needsImplicitMoveAssignment());
11359 
11360   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11361   if (DSM.isAlreadyBeingDeclared())
11362     return nullptr;
11363 
11364   // Note: The following rules are largely analoguous to the move
11365   // constructor rules.
11366 
11367   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11368   QualType RetType = Context.getLValueReferenceType(ArgType);
11369   ArgType = Context.getRValueReferenceType(ArgType);
11370 
11371   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11372                                                      CXXMoveAssignment,
11373                                                      false);
11374 
11375   //   An implicitly-declared move assignment operator is an inline public
11376   //   member of its class.
11377   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11378   SourceLocation ClassLoc = ClassDecl->getLocation();
11379   DeclarationNameInfo NameInfo(Name, ClassLoc);
11380   CXXMethodDecl *MoveAssignment =
11381       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11382                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11383                             /*isInline=*/true, Constexpr, SourceLocation());
11384   MoveAssignment->setAccess(AS_public);
11385   MoveAssignment->setDefaulted();
11386   MoveAssignment->setImplicit();
11387 
11388   if (getLangOpts().CUDA) {
11389     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11390                                             MoveAssignment,
11391                                             /* ConstRHS */ false,
11392                                             /* Diagnose */ false);
11393   }
11394 
11395   // Build an exception specification pointing back at this member.
11396   FunctionProtoType::ExtProtoInfo EPI =
11397       getImplicitMethodEPI(*this, MoveAssignment);
11398   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11399 
11400   // Add the parameter to the operator.
11401   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11402                                                ClassLoc, ClassLoc,
11403                                                /*Id=*/nullptr, ArgType,
11404                                                /*TInfo=*/nullptr, SC_None,
11405                                                nullptr);
11406   MoveAssignment->setParams(FromParam);
11407 
11408   MoveAssignment->setTrivial(
11409     ClassDecl->needsOverloadResolutionForMoveAssignment()
11410       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11411       : ClassDecl->hasTrivialMoveAssignment());
11412 
11413   // Note that we have added this copy-assignment operator.
11414   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11415 
11416   Scope *S = getScopeForContext(ClassDecl);
11417   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11418 
11419   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11420     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11421     SetDeclDeleted(MoveAssignment, ClassLoc);
11422   }
11423 
11424   if (S)
11425     PushOnScopeChains(MoveAssignment, S, false);
11426   ClassDecl->addDecl(MoveAssignment);
11427 
11428   return MoveAssignment;
11429 }
11430 
11431 /// Check if we're implicitly defining a move assignment operator for a class
11432 /// with virtual bases. Such a move assignment might move-assign the virtual
11433 /// base multiple times.
11434 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11435                                                SourceLocation CurrentLocation) {
11436   assert(!Class->isDependentContext() && "should not define dependent move");
11437 
11438   // Only a virtual base could get implicitly move-assigned multiple times.
11439   // Only a non-trivial move assignment can observe this. We only want to
11440   // diagnose if we implicitly define an assignment operator that assigns
11441   // two base classes, both of which move-assign the same virtual base.
11442   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11443       Class->getNumBases() < 2)
11444     return;
11445 
11446   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11447   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11448   VBaseMap VBases;
11449 
11450   for (auto &BI : Class->bases()) {
11451     Worklist.push_back(&BI);
11452     while (!Worklist.empty()) {
11453       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11454       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11455 
11456       // If the base has no non-trivial move assignment operators,
11457       // we don't care about moves from it.
11458       if (!Base->hasNonTrivialMoveAssignment())
11459         continue;
11460 
11461       // If there's nothing virtual here, skip it.
11462       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11463         continue;
11464 
11465       // If we're not actually going to call a move assignment for this base,
11466       // or the selected move assignment is trivial, skip it.
11467       Sema::SpecialMemberOverloadResult *SMOR =
11468         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11469                               /*ConstArg*/false, /*VolatileArg*/false,
11470                               /*RValueThis*/true, /*ConstThis*/false,
11471                               /*VolatileThis*/false);
11472       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11473           !SMOR->getMethod()->isMoveAssignmentOperator())
11474         continue;
11475 
11476       if (BaseSpec->isVirtual()) {
11477         // We're going to move-assign this virtual base, and its move
11478         // assignment operator is not trivial. If this can happen for
11479         // multiple distinct direct bases of Class, diagnose it. (If it
11480         // only happens in one base, we'll diagnose it when synthesizing
11481         // that base class's move assignment operator.)
11482         CXXBaseSpecifier *&Existing =
11483             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11484                 .first->second;
11485         if (Existing && Existing != &BI) {
11486           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11487             << Class << Base;
11488           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11489             << (Base->getCanonicalDecl() ==
11490                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11491             << Base << Existing->getType() << Existing->getSourceRange();
11492           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11493             << (Base->getCanonicalDecl() ==
11494                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11495             << Base << BI.getType() << BaseSpec->getSourceRange();
11496 
11497           // Only diagnose each vbase once.
11498           Existing = nullptr;
11499         }
11500       } else {
11501         // Only walk over bases that have defaulted move assignment operators.
11502         // We assume that any user-provided move assignment operator handles
11503         // the multiple-moves-of-vbase case itself somehow.
11504         if (!SMOR->getMethod()->isDefaulted())
11505           continue;
11506 
11507         // We're going to move the base classes of Base. Add them to the list.
11508         for (auto &BI : Base->bases())
11509           Worklist.push_back(&BI);
11510       }
11511     }
11512   }
11513 }
11514 
11515 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11516                                         CXXMethodDecl *MoveAssignOperator) {
11517   assert((MoveAssignOperator->isDefaulted() &&
11518           MoveAssignOperator->isOverloadedOperator() &&
11519           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11520           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11521           !MoveAssignOperator->isDeleted()) &&
11522          "DefineImplicitMoveAssignment called for wrong function");
11523 
11524   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11525 
11526   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11527     MoveAssignOperator->setInvalidDecl();
11528     return;
11529   }
11530 
11531   MoveAssignOperator->markUsed(Context);
11532 
11533   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11534   DiagnosticErrorTrap Trap(Diags);
11535 
11536   // C++0x [class.copy]p28:
11537   //   The implicitly-defined or move assignment operator for a non-union class
11538   //   X performs memberwise move assignment of its subobjects. The direct base
11539   //   classes of X are assigned first, in the order of their declaration in the
11540   //   base-specifier-list, and then the immediate non-static data members of X
11541   //   are assigned, in the order in which they were declared in the class
11542   //   definition.
11543 
11544   // Issue a warning if our implicit move assignment operator will move
11545   // from a virtual base more than once.
11546   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11547 
11548   // The statements that form the synthesized function body.
11549   SmallVector<Stmt*, 8> Statements;
11550 
11551   // The parameter for the "other" object, which we are move from.
11552   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11553   QualType OtherRefType = Other->getType()->
11554       getAs<RValueReferenceType>()->getPointeeType();
11555   assert(!OtherRefType.getQualifiers() &&
11556          "Bad argument type of defaulted move assignment");
11557 
11558   // Our location for everything implicitly-generated.
11559   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11560                            ? MoveAssignOperator->getLocEnd()
11561                            : MoveAssignOperator->getLocation();
11562 
11563   // Builds a reference to the "other" object.
11564   RefBuilder OtherRef(Other, OtherRefType);
11565   // Cast to rvalue.
11566   MoveCastBuilder MoveOther(OtherRef);
11567 
11568   // Builds the "this" pointer.
11569   ThisBuilder This;
11570 
11571   // Assign base classes.
11572   bool Invalid = false;
11573   for (auto &Base : ClassDecl->bases()) {
11574     // C++11 [class.copy]p28:
11575     //   It is unspecified whether subobjects representing virtual base classes
11576     //   are assigned more than once by the implicitly-defined copy assignment
11577     //   operator.
11578     // FIXME: Do not assign to a vbase that will be assigned by some other base
11579     // class. For a move-assignment, this can result in the vbase being moved
11580     // multiple times.
11581 
11582     // Form the assignment:
11583     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11584     QualType BaseType = Base.getType().getUnqualifiedType();
11585     if (!BaseType->isRecordType()) {
11586       Invalid = true;
11587       continue;
11588     }
11589 
11590     CXXCastPath BasePath;
11591     BasePath.push_back(&Base);
11592 
11593     // Construct the "from" expression, which is an implicit cast to the
11594     // appropriately-qualified base type.
11595     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11596 
11597     // Dereference "this".
11598     DerefBuilder DerefThis(This);
11599 
11600     // Implicitly cast "this" to the appropriately-qualified base type.
11601     CastBuilder To(DerefThis,
11602                    Context.getCVRQualifiedType(
11603                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11604                    VK_LValue, BasePath);
11605 
11606     // Build the move.
11607     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11608                                             To, From,
11609                                             /*CopyingBaseSubobject=*/true,
11610                                             /*Copying=*/false);
11611     if (Move.isInvalid()) {
11612       Diag(CurrentLocation, diag::note_member_synthesized_at)
11613         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11614       MoveAssignOperator->setInvalidDecl();
11615       return;
11616     }
11617 
11618     // Success! Record the move.
11619     Statements.push_back(Move.getAs<Expr>());
11620   }
11621 
11622   // Assign non-static members.
11623   for (auto *Field : ClassDecl->fields()) {
11624     // FIXME: We should form some kind of AST representation for the implied
11625     // memcpy in a union copy operation.
11626     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11627       continue;
11628 
11629     if (Field->isInvalidDecl()) {
11630       Invalid = true;
11631       continue;
11632     }
11633 
11634     // Check for members of reference type; we can't move those.
11635     if (Field->getType()->isReferenceType()) {
11636       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11637         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11638       Diag(Field->getLocation(), diag::note_declared_at);
11639       Diag(CurrentLocation, diag::note_member_synthesized_at)
11640         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11641       Invalid = true;
11642       continue;
11643     }
11644 
11645     // Check for members of const-qualified, non-class type.
11646     QualType BaseType = Context.getBaseElementType(Field->getType());
11647     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11648       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11649         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11650       Diag(Field->getLocation(), diag::note_declared_at);
11651       Diag(CurrentLocation, diag::note_member_synthesized_at)
11652         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11653       Invalid = true;
11654       continue;
11655     }
11656 
11657     // Suppress assigning zero-width bitfields.
11658     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11659       continue;
11660 
11661     QualType FieldType = Field->getType().getNonReferenceType();
11662     if (FieldType->isIncompleteArrayType()) {
11663       assert(ClassDecl->hasFlexibleArrayMember() &&
11664              "Incomplete array type is not valid");
11665       continue;
11666     }
11667 
11668     // Build references to the field in the object we're copying from and to.
11669     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11670                               LookupMemberName);
11671     MemberLookup.addDecl(Field);
11672     MemberLookup.resolveKind();
11673     MemberBuilder From(MoveOther, OtherRefType,
11674                        /*IsArrow=*/false, MemberLookup);
11675     MemberBuilder To(This, getCurrentThisType(),
11676                      /*IsArrow=*/true, MemberLookup);
11677 
11678     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11679         "Member reference with rvalue base must be rvalue except for reference "
11680         "members, which aren't allowed for move assignment.");
11681 
11682     // Build the move of this field.
11683     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11684                                             To, From,
11685                                             /*CopyingBaseSubobject=*/false,
11686                                             /*Copying=*/false);
11687     if (Move.isInvalid()) {
11688       Diag(CurrentLocation, diag::note_member_synthesized_at)
11689         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11690       MoveAssignOperator->setInvalidDecl();
11691       return;
11692     }
11693 
11694     // Success! Record the copy.
11695     Statements.push_back(Move.getAs<Stmt>());
11696   }
11697 
11698   if (!Invalid) {
11699     // Add a "return *this;"
11700     ExprResult ThisObj =
11701         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11702 
11703     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11704     if (Return.isInvalid())
11705       Invalid = true;
11706     else {
11707       Statements.push_back(Return.getAs<Stmt>());
11708 
11709       if (Trap.hasErrorOccurred()) {
11710         Diag(CurrentLocation, diag::note_member_synthesized_at)
11711           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11712         Invalid = true;
11713       }
11714     }
11715   }
11716 
11717   // The exception specification is needed because we are defining the
11718   // function.
11719   ResolveExceptionSpec(CurrentLocation,
11720                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11721 
11722   if (Invalid) {
11723     MoveAssignOperator->setInvalidDecl();
11724     return;
11725   }
11726 
11727   StmtResult Body;
11728   {
11729     CompoundScopeRAII CompoundScope(*this);
11730     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11731                              /*isStmtExpr=*/false);
11732     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11733   }
11734   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11735 
11736   if (ASTMutationListener *L = getASTMutationListener()) {
11737     L->CompletedImplicitDefinition(MoveAssignOperator);
11738   }
11739 }
11740 
11741 Sema::ImplicitExceptionSpecification
11742 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11743   CXXRecordDecl *ClassDecl = MD->getParent();
11744 
11745   ImplicitExceptionSpecification ExceptSpec(*this);
11746   if (ClassDecl->isInvalidDecl())
11747     return ExceptSpec;
11748 
11749   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
11750   assert(T->getNumParams() >= 1 && "not a copy ctor");
11751   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
11752 
11753   // C++ [except.spec]p14:
11754   //   An implicitly declared special member function (Clause 12) shall have an
11755   //   exception-specification. [...]
11756   for (const auto &Base : ClassDecl->bases()) {
11757     // Virtual bases are handled below.
11758     if (Base.isVirtual())
11759       continue;
11760 
11761     CXXRecordDecl *BaseClassDecl
11762       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11763     if (CXXConstructorDecl *CopyConstructor =
11764           LookupCopyingConstructor(BaseClassDecl, Quals))
11765       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11766   }
11767   for (const auto &Base : ClassDecl->vbases()) {
11768     CXXRecordDecl *BaseClassDecl
11769       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11770     if (CXXConstructorDecl *CopyConstructor =
11771           LookupCopyingConstructor(BaseClassDecl, Quals))
11772       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11773   }
11774   for (const auto *Field : ClassDecl->fields()) {
11775     QualType FieldType = Context.getBaseElementType(Field->getType());
11776     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11777       if (CXXConstructorDecl *CopyConstructor =
11778               LookupCopyingConstructor(FieldClassDecl,
11779                                        Quals | FieldType.getCVRQualifiers()))
11780       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
11781     }
11782   }
11783 
11784   return ExceptSpec;
11785 }
11786 
11787 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11788                                                     CXXRecordDecl *ClassDecl) {
11789   // C++ [class.copy]p4:
11790   //   If the class definition does not explicitly declare a copy
11791   //   constructor, one is declared implicitly.
11792   assert(ClassDecl->needsImplicitCopyConstructor());
11793 
11794   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11795   if (DSM.isAlreadyBeingDeclared())
11796     return nullptr;
11797 
11798   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11799   QualType ArgType = ClassType;
11800   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11801   if (Const)
11802     ArgType = ArgType.withConst();
11803   ArgType = Context.getLValueReferenceType(ArgType);
11804 
11805   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11806                                                      CXXCopyConstructor,
11807                                                      Const);
11808 
11809   DeclarationName Name
11810     = Context.DeclarationNames.getCXXConstructorName(
11811                                            Context.getCanonicalType(ClassType));
11812   SourceLocation ClassLoc = ClassDecl->getLocation();
11813   DeclarationNameInfo NameInfo(Name, ClassLoc);
11814 
11815   //   An implicitly-declared copy constructor is an inline public
11816   //   member of its class.
11817   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11818       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11819       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11820       Constexpr);
11821   CopyConstructor->setAccess(AS_public);
11822   CopyConstructor->setDefaulted();
11823 
11824   if (getLangOpts().CUDA) {
11825     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11826                                             CopyConstructor,
11827                                             /* ConstRHS */ Const,
11828                                             /* Diagnose */ false);
11829   }
11830 
11831   // Build an exception specification pointing back at this member.
11832   FunctionProtoType::ExtProtoInfo EPI =
11833       getImplicitMethodEPI(*this, CopyConstructor);
11834   CopyConstructor->setType(
11835       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11836 
11837   // Add the parameter to the constructor.
11838   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11839                                                ClassLoc, ClassLoc,
11840                                                /*IdentifierInfo=*/nullptr,
11841                                                ArgType, /*TInfo=*/nullptr,
11842                                                SC_None, nullptr);
11843   CopyConstructor->setParams(FromParam);
11844 
11845   CopyConstructor->setTrivial(
11846     ClassDecl->needsOverloadResolutionForCopyConstructor()
11847       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11848       : ClassDecl->hasTrivialCopyConstructor());
11849 
11850   // Note that we have declared this constructor.
11851   ++ASTContext::NumImplicitCopyConstructorsDeclared;
11852 
11853   Scope *S = getScopeForContext(ClassDecl);
11854   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11855 
11856   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11857     SetDeclDeleted(CopyConstructor, ClassLoc);
11858 
11859   if (S)
11860     PushOnScopeChains(CopyConstructor, S, false);
11861   ClassDecl->addDecl(CopyConstructor);
11862 
11863   return CopyConstructor;
11864 }
11865 
11866 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11867                                    CXXConstructorDecl *CopyConstructor) {
11868   assert((CopyConstructor->isDefaulted() &&
11869           CopyConstructor->isCopyConstructor() &&
11870           !CopyConstructor->doesThisDeclarationHaveABody() &&
11871           !CopyConstructor->isDeleted()) &&
11872          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11873 
11874   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11875   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11876 
11877   // C++11 [class.copy]p7:
11878   //   The [definition of an implicitly declared copy constructor] is
11879   //   deprecated if the class has a user-declared copy assignment operator
11880   //   or a user-declared destructor.
11881   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11882     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
11883 
11884   SynthesizedFunctionScope Scope(*this, CopyConstructor);
11885   DiagnosticErrorTrap Trap(Diags);
11886 
11887   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
11888       Trap.hasErrorOccurred()) {
11889     Diag(CurrentLocation, diag::note_member_synthesized_at)
11890       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
11891     CopyConstructor->setInvalidDecl();
11892   }  else {
11893     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11894                              ? CopyConstructor->getLocEnd()
11895                              : CopyConstructor->getLocation();
11896     Sema::CompoundScopeRAII CompoundScope(*this);
11897     CopyConstructor->setBody(
11898         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11899   }
11900 
11901   // The exception specification is needed because we are defining the
11902   // function.
11903   ResolveExceptionSpec(CurrentLocation,
11904                        CopyConstructor->getType()->castAs<FunctionProtoType>());
11905 
11906   CopyConstructor->markUsed(Context);
11907   MarkVTableUsed(CurrentLocation, ClassDecl);
11908 
11909   if (ASTMutationListener *L = getASTMutationListener()) {
11910     L->CompletedImplicitDefinition(CopyConstructor);
11911   }
11912 }
11913 
11914 Sema::ImplicitExceptionSpecification
11915 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
11916   CXXRecordDecl *ClassDecl = MD->getParent();
11917 
11918   // C++ [except.spec]p14:
11919   //   An implicitly declared special member function (Clause 12) shall have an
11920   //   exception-specification. [...]
11921   ImplicitExceptionSpecification ExceptSpec(*this);
11922   if (ClassDecl->isInvalidDecl())
11923     return ExceptSpec;
11924 
11925   // Direct base-class constructors.
11926   for (const auto &B : ClassDecl->bases()) {
11927     if (B.isVirtual()) // Handled below.
11928       continue;
11929 
11930     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11931       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11932       CXXConstructorDecl *Constructor =
11933           LookupMovingConstructor(BaseClassDecl, 0);
11934       // If this is a deleted function, add it anyway. This might be conformant
11935       // with the standard. This might not. I'm not sure. It might not matter.
11936       if (Constructor)
11937         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11938     }
11939   }
11940 
11941   // Virtual base-class constructors.
11942   for (const auto &B : ClassDecl->vbases()) {
11943     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
11944       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
11945       CXXConstructorDecl *Constructor =
11946           LookupMovingConstructor(BaseClassDecl, 0);
11947       // If this is a deleted function, add it anyway. This might be conformant
11948       // with the standard. This might not. I'm not sure. It might not matter.
11949       if (Constructor)
11950         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
11951     }
11952   }
11953 
11954   // Field constructors.
11955   for (const auto *F : ClassDecl->fields()) {
11956     QualType FieldType = Context.getBaseElementType(F->getType());
11957     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
11958       CXXConstructorDecl *Constructor =
11959           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
11960       // If this is a deleted function, add it anyway. This might be conformant
11961       // with the standard. This might not. I'm not sure. It might not matter.
11962       // In particular, the problem is that this function never gets called. It
11963       // might just be ill-formed because this function attempts to refer to
11964       // a deleted function here.
11965       if (Constructor)
11966         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
11967     }
11968   }
11969 
11970   return ExceptSpec;
11971 }
11972 
11973 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11974                                                     CXXRecordDecl *ClassDecl) {
11975   assert(ClassDecl->needsImplicitMoveConstructor());
11976 
11977   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11978   if (DSM.isAlreadyBeingDeclared())
11979     return nullptr;
11980 
11981   QualType ClassType = Context.getTypeDeclType(ClassDecl);
11982   QualType ArgType = Context.getRValueReferenceType(ClassType);
11983 
11984   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11985                                                      CXXMoveConstructor,
11986                                                      false);
11987 
11988   DeclarationName Name
11989     = Context.DeclarationNames.getCXXConstructorName(
11990                                            Context.getCanonicalType(ClassType));
11991   SourceLocation ClassLoc = ClassDecl->getLocation();
11992   DeclarationNameInfo NameInfo(Name, ClassLoc);
11993 
11994   // C++11 [class.copy]p11:
11995   //   An implicitly-declared copy/move constructor is an inline public
11996   //   member of its class.
11997   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
11998       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11999       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12000       Constexpr);
12001   MoveConstructor->setAccess(AS_public);
12002   MoveConstructor->setDefaulted();
12003 
12004   if (getLangOpts().CUDA) {
12005     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12006                                             MoveConstructor,
12007                                             /* ConstRHS */ false,
12008                                             /* Diagnose */ false);
12009   }
12010 
12011   // Build an exception specification pointing back at this member.
12012   FunctionProtoType::ExtProtoInfo EPI =
12013       getImplicitMethodEPI(*this, MoveConstructor);
12014   MoveConstructor->setType(
12015       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12016 
12017   // Add the parameter to the constructor.
12018   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12019                                                ClassLoc, ClassLoc,
12020                                                /*IdentifierInfo=*/nullptr,
12021                                                ArgType, /*TInfo=*/nullptr,
12022                                                SC_None, nullptr);
12023   MoveConstructor->setParams(FromParam);
12024 
12025   MoveConstructor->setTrivial(
12026     ClassDecl->needsOverloadResolutionForMoveConstructor()
12027       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12028       : ClassDecl->hasTrivialMoveConstructor());
12029 
12030   // Note that we have declared this constructor.
12031   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12032 
12033   Scope *S = getScopeForContext(ClassDecl);
12034   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12035 
12036   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12037     ClassDecl->setImplicitMoveConstructorIsDeleted();
12038     SetDeclDeleted(MoveConstructor, ClassLoc);
12039   }
12040 
12041   if (S)
12042     PushOnScopeChains(MoveConstructor, S, false);
12043   ClassDecl->addDecl(MoveConstructor);
12044 
12045   return MoveConstructor;
12046 }
12047 
12048 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12049                                    CXXConstructorDecl *MoveConstructor) {
12050   assert((MoveConstructor->isDefaulted() &&
12051           MoveConstructor->isMoveConstructor() &&
12052           !MoveConstructor->doesThisDeclarationHaveABody() &&
12053           !MoveConstructor->isDeleted()) &&
12054          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12055 
12056   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12057   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12058 
12059   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12060   DiagnosticErrorTrap Trap(Diags);
12061 
12062   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
12063       Trap.hasErrorOccurred()) {
12064     Diag(CurrentLocation, diag::note_member_synthesized_at)
12065       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12066     MoveConstructor->setInvalidDecl();
12067   }  else {
12068     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12069                              ? MoveConstructor->getLocEnd()
12070                              : MoveConstructor->getLocation();
12071     Sema::CompoundScopeRAII CompoundScope(*this);
12072     MoveConstructor->setBody(ActOnCompoundStmt(
12073         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12074   }
12075 
12076   // The exception specification is needed because we are defining the
12077   // function.
12078   ResolveExceptionSpec(CurrentLocation,
12079                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12080 
12081   MoveConstructor->markUsed(Context);
12082   MarkVTableUsed(CurrentLocation, ClassDecl);
12083 
12084   if (ASTMutationListener *L = getASTMutationListener()) {
12085     L->CompletedImplicitDefinition(MoveConstructor);
12086   }
12087 }
12088 
12089 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12090   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12091 }
12092 
12093 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12094                             SourceLocation CurrentLocation,
12095                             CXXConversionDecl *Conv) {
12096   CXXRecordDecl *Lambda = Conv->getParent();
12097   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12098   // If we are defining a specialization of a conversion to function-ptr
12099   // cache the deduced template arguments for this specialization
12100   // so that we can use them to retrieve the corresponding call-operator
12101   // and static-invoker.
12102   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12103 
12104   // Retrieve the corresponding call-operator specialization.
12105   if (Lambda->isGenericLambda()) {
12106     assert(Conv->isFunctionTemplateSpecialization());
12107     FunctionTemplateDecl *CallOpTemplate =
12108         CallOp->getDescribedFunctionTemplate();
12109     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12110     void *InsertPos = nullptr;
12111     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12112                                                 DeducedTemplateArgs->asArray(),
12113                                                 InsertPos);
12114     assert(CallOpSpec &&
12115           "Conversion operator must have a corresponding call operator");
12116     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12117   }
12118   // Mark the call operator referenced (and add to pending instantiations
12119   // if necessary).
12120   // For both the conversion and static-invoker template specializations
12121   // we construct their body's in this function, so no need to add them
12122   // to the PendingInstantiations.
12123   MarkFunctionReferenced(CurrentLocation, CallOp);
12124 
12125   SynthesizedFunctionScope Scope(*this, Conv);
12126   DiagnosticErrorTrap Trap(Diags);
12127 
12128   // Retrieve the static invoker...
12129   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12130   // ... and get the corresponding specialization for a generic lambda.
12131   if (Lambda->isGenericLambda()) {
12132     assert(DeducedTemplateArgs &&
12133       "Must have deduced template arguments from Conversion Operator");
12134     FunctionTemplateDecl *InvokeTemplate =
12135                           Invoker->getDescribedFunctionTemplate();
12136     void *InsertPos = nullptr;
12137     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12138                                                 DeducedTemplateArgs->asArray(),
12139                                                 InsertPos);
12140     assert(InvokeSpec &&
12141       "Must have a corresponding static invoker specialization");
12142     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12143   }
12144   // Construct the body of the conversion function { return __invoke; }.
12145   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12146                                         VK_LValue, Conv->getLocation()).get();
12147    assert(FunctionRef && "Can't refer to __invoke function?");
12148    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12149    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12150                                             Conv->getLocation(),
12151                                             Conv->getLocation()));
12152 
12153   Conv->markUsed(Context);
12154   Conv->setReferenced();
12155 
12156   // Fill in the __invoke function with a dummy implementation. IR generation
12157   // will fill in the actual details.
12158   Invoker->markUsed(Context);
12159   Invoker->setReferenced();
12160   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12161 
12162   if (ASTMutationListener *L = getASTMutationListener()) {
12163     L->CompletedImplicitDefinition(Conv);
12164     L->CompletedImplicitDefinition(Invoker);
12165    }
12166 }
12167 
12168 
12169 
12170 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12171        SourceLocation CurrentLocation,
12172        CXXConversionDecl *Conv)
12173 {
12174   assert(!Conv->getParent()->isGenericLambda());
12175 
12176   Conv->markUsed(Context);
12177 
12178   SynthesizedFunctionScope Scope(*this, Conv);
12179   DiagnosticErrorTrap Trap(Diags);
12180 
12181   // Copy-initialize the lambda object as needed to capture it.
12182   Expr *This = ActOnCXXThis(CurrentLocation).get();
12183   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12184 
12185   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12186                                                         Conv->getLocation(),
12187                                                         Conv, DerefThis);
12188 
12189   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12190   // behavior.  Note that only the general conversion function does this
12191   // (since it's unusable otherwise); in the case where we inline the
12192   // block literal, it has block literal lifetime semantics.
12193   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12194     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12195                                           CK_CopyAndAutoreleaseBlockObject,
12196                                           BuildBlock.get(), nullptr, VK_RValue);
12197 
12198   if (BuildBlock.isInvalid()) {
12199     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12200     Conv->setInvalidDecl();
12201     return;
12202   }
12203 
12204   // Create the return statement that returns the block from the conversion
12205   // function.
12206   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12207   if (Return.isInvalid()) {
12208     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12209     Conv->setInvalidDecl();
12210     return;
12211   }
12212 
12213   // Set the body of the conversion function.
12214   Stmt *ReturnS = Return.get();
12215   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12216                                            Conv->getLocation(),
12217                                            Conv->getLocation()));
12218 
12219   // We're done; notify the mutation listener, if any.
12220   if (ASTMutationListener *L = getASTMutationListener()) {
12221     L->CompletedImplicitDefinition(Conv);
12222   }
12223 }
12224 
12225 /// \brief Determine whether the given list arguments contains exactly one
12226 /// "real" (non-default) argument.
12227 static bool hasOneRealArgument(MultiExprArg Args) {
12228   switch (Args.size()) {
12229   case 0:
12230     return false;
12231 
12232   default:
12233     if (!Args[1]->isDefaultArgument())
12234       return false;
12235 
12236     // fall through
12237   case 1:
12238     return !Args[0]->isDefaultArgument();
12239   }
12240 
12241   return false;
12242 }
12243 
12244 ExprResult
12245 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12246                             NamedDecl *FoundDecl,
12247                             CXXConstructorDecl *Constructor,
12248                             MultiExprArg ExprArgs,
12249                             bool HadMultipleCandidates,
12250                             bool IsListInitialization,
12251                             bool IsStdInitListInitialization,
12252                             bool RequiresZeroInit,
12253                             unsigned ConstructKind,
12254                             SourceRange ParenRange) {
12255   bool Elidable = false;
12256 
12257   // C++0x [class.copy]p34:
12258   //   When certain criteria are met, an implementation is allowed to
12259   //   omit the copy/move construction of a class object, even if the
12260   //   copy/move constructor and/or destructor for the object have
12261   //   side effects. [...]
12262   //     - when a temporary class object that has not been bound to a
12263   //       reference (12.2) would be copied/moved to a class object
12264   //       with the same cv-unqualified type, the copy/move operation
12265   //       can be omitted by constructing the temporary object
12266   //       directly into the target of the omitted copy/move
12267   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12268       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12269     Expr *SubExpr = ExprArgs[0];
12270     Elidable = SubExpr->isTemporaryObject(
12271         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12272   }
12273 
12274   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12275                                FoundDecl, Constructor,
12276                                Elidable, ExprArgs, HadMultipleCandidates,
12277                                IsListInitialization,
12278                                IsStdInitListInitialization, RequiresZeroInit,
12279                                ConstructKind, ParenRange);
12280 }
12281 
12282 ExprResult
12283 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12284                             NamedDecl *FoundDecl,
12285                             CXXConstructorDecl *Constructor,
12286                             bool Elidable,
12287                             MultiExprArg ExprArgs,
12288                             bool HadMultipleCandidates,
12289                             bool IsListInitialization,
12290                             bool IsStdInitListInitialization,
12291                             bool RequiresZeroInit,
12292                             unsigned ConstructKind,
12293                             SourceRange ParenRange) {
12294   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12295     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12296     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12297       return ExprError();
12298   }
12299 
12300   return BuildCXXConstructExpr(
12301       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12302       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12303       RequiresZeroInit, ConstructKind, ParenRange);
12304 }
12305 
12306 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12307 /// including handling of its default argument expressions.
12308 ExprResult
12309 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12310                             CXXConstructorDecl *Constructor,
12311                             bool Elidable,
12312                             MultiExprArg ExprArgs,
12313                             bool HadMultipleCandidates,
12314                             bool IsListInitialization,
12315                             bool IsStdInitListInitialization,
12316                             bool RequiresZeroInit,
12317                             unsigned ConstructKind,
12318                             SourceRange ParenRange) {
12319   assert(declaresSameEntity(
12320              Constructor->getParent(),
12321              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12322          "given constructor for wrong type");
12323   MarkFunctionReferenced(ConstructLoc, Constructor);
12324   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12325     return ExprError();
12326 
12327   return CXXConstructExpr::Create(
12328       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12329       ExprArgs, HadMultipleCandidates, IsListInitialization,
12330       IsStdInitListInitialization, RequiresZeroInit,
12331       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12332       ParenRange);
12333 }
12334 
12335 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12336   assert(Field->hasInClassInitializer());
12337 
12338   // If we already have the in-class initializer nothing needs to be done.
12339   if (Field->getInClassInitializer())
12340     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12341 
12342   // If we might have already tried and failed to instantiate, don't try again.
12343   if (Field->isInvalidDecl())
12344     return ExprError();
12345 
12346   // Maybe we haven't instantiated the in-class initializer. Go check the
12347   // pattern FieldDecl to see if it has one.
12348   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12349 
12350   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12351     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12352     DeclContext::lookup_result Lookup =
12353         ClassPattern->lookup(Field->getDeclName());
12354 
12355     // Lookup can return at most two results: the pattern for the field, or the
12356     // injected class name of the parent record. No other member can have the
12357     // same name as the field.
12358     // In modules mode, lookup can return multiple results (coming from
12359     // different modules).
12360     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12361            "more than two lookup results for field name");
12362     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12363     if (!Pattern) {
12364       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12365              "cannot have other non-field member with same name");
12366       for (auto L : Lookup)
12367         if (isa<FieldDecl>(L)) {
12368           Pattern = cast<FieldDecl>(L);
12369           break;
12370         }
12371       assert(Pattern && "We must have set the Pattern!");
12372     }
12373 
12374     if (InstantiateInClassInitializer(Loc, Field, Pattern,
12375                                       getTemplateInstantiationArgs(Field))) {
12376       // Don't diagnose this again.
12377       Field->setInvalidDecl();
12378       return ExprError();
12379     }
12380     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12381   }
12382 
12383   // DR1351:
12384   //   If the brace-or-equal-initializer of a non-static data member
12385   //   invokes a defaulted default constructor of its class or of an
12386   //   enclosing class in a potentially evaluated subexpression, the
12387   //   program is ill-formed.
12388   //
12389   // This resolution is unworkable: the exception specification of the
12390   // default constructor can be needed in an unevaluated context, in
12391   // particular, in the operand of a noexcept-expression, and we can be
12392   // unable to compute an exception specification for an enclosed class.
12393   //
12394   // Any attempt to resolve the exception specification of a defaulted default
12395   // constructor before the initializer is lexically complete will ultimately
12396   // come here at which point we can diagnose it.
12397   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12398   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12399       << OutermostClass << Field;
12400   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12401   // Recover by marking the field invalid, unless we're in a SFINAE context.
12402   if (!isSFINAEContext())
12403     Field->setInvalidDecl();
12404   return ExprError();
12405 }
12406 
12407 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12408   if (VD->isInvalidDecl()) return;
12409 
12410   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12411   if (ClassDecl->isInvalidDecl()) return;
12412   if (ClassDecl->hasIrrelevantDestructor()) return;
12413   if (ClassDecl->isDependentContext()) return;
12414 
12415   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12416   MarkFunctionReferenced(VD->getLocation(), Destructor);
12417   CheckDestructorAccess(VD->getLocation(), Destructor,
12418                         PDiag(diag::err_access_dtor_var)
12419                         << VD->getDeclName()
12420                         << VD->getType());
12421   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12422 
12423   if (Destructor->isTrivial()) return;
12424   if (!VD->hasGlobalStorage()) return;
12425 
12426   // Emit warning for non-trivial dtor in global scope (a real global,
12427   // class-static, function-static).
12428   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12429 
12430   // TODO: this should be re-enabled for static locals by !CXAAtExit
12431   if (!VD->isStaticLocal())
12432     Diag(VD->getLocation(), diag::warn_global_destructor);
12433 }
12434 
12435 /// \brief Given a constructor and the set of arguments provided for the
12436 /// constructor, convert the arguments and add any required default arguments
12437 /// to form a proper call to this constructor.
12438 ///
12439 /// \returns true if an error occurred, false otherwise.
12440 bool
12441 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12442                               MultiExprArg ArgsPtr,
12443                               SourceLocation Loc,
12444                               SmallVectorImpl<Expr*> &ConvertedArgs,
12445                               bool AllowExplicit,
12446                               bool IsListInitialization) {
12447   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12448   unsigned NumArgs = ArgsPtr.size();
12449   Expr **Args = ArgsPtr.data();
12450 
12451   const FunctionProtoType *Proto
12452     = Constructor->getType()->getAs<FunctionProtoType>();
12453   assert(Proto && "Constructor without a prototype?");
12454   unsigned NumParams = Proto->getNumParams();
12455 
12456   // If too few arguments are available, we'll fill in the rest with defaults.
12457   if (NumArgs < NumParams)
12458     ConvertedArgs.reserve(NumParams);
12459   else
12460     ConvertedArgs.reserve(NumArgs);
12461 
12462   VariadicCallType CallType =
12463     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12464   SmallVector<Expr *, 8> AllArgs;
12465   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12466                                         Proto, 0,
12467                                         llvm::makeArrayRef(Args, NumArgs),
12468                                         AllArgs,
12469                                         CallType, AllowExplicit,
12470                                         IsListInitialization);
12471   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12472 
12473   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12474 
12475   CheckConstructorCall(Constructor,
12476                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12477                        Proto, Loc);
12478 
12479   return Invalid;
12480 }
12481 
12482 static inline bool
12483 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12484                                        const FunctionDecl *FnDecl) {
12485   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12486   if (isa<NamespaceDecl>(DC)) {
12487     return SemaRef.Diag(FnDecl->getLocation(),
12488                         diag::err_operator_new_delete_declared_in_namespace)
12489       << FnDecl->getDeclName();
12490   }
12491 
12492   if (isa<TranslationUnitDecl>(DC) &&
12493       FnDecl->getStorageClass() == SC_Static) {
12494     return SemaRef.Diag(FnDecl->getLocation(),
12495                         diag::err_operator_new_delete_declared_static)
12496       << FnDecl->getDeclName();
12497   }
12498 
12499   return false;
12500 }
12501 
12502 static inline bool
12503 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12504                             CanQualType ExpectedResultType,
12505                             CanQualType ExpectedFirstParamType,
12506                             unsigned DependentParamTypeDiag,
12507                             unsigned InvalidParamTypeDiag) {
12508   QualType ResultType =
12509       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12510 
12511   // Check that the result type is not dependent.
12512   if (ResultType->isDependentType())
12513     return SemaRef.Diag(FnDecl->getLocation(),
12514                         diag::err_operator_new_delete_dependent_result_type)
12515     << FnDecl->getDeclName() << ExpectedResultType;
12516 
12517   // Check that the result type is what we expect.
12518   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12519     return SemaRef.Diag(FnDecl->getLocation(),
12520                         diag::err_operator_new_delete_invalid_result_type)
12521     << FnDecl->getDeclName() << ExpectedResultType;
12522 
12523   // A function template must have at least 2 parameters.
12524   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12525     return SemaRef.Diag(FnDecl->getLocation(),
12526                       diag::err_operator_new_delete_template_too_few_parameters)
12527         << FnDecl->getDeclName();
12528 
12529   // The function decl must have at least 1 parameter.
12530   if (FnDecl->getNumParams() == 0)
12531     return SemaRef.Diag(FnDecl->getLocation(),
12532                         diag::err_operator_new_delete_too_few_parameters)
12533       << FnDecl->getDeclName();
12534 
12535   // Check the first parameter type is not dependent.
12536   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12537   if (FirstParamType->isDependentType())
12538     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12539       << FnDecl->getDeclName() << ExpectedFirstParamType;
12540 
12541   // Check that the first parameter type is what we expect.
12542   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12543       ExpectedFirstParamType)
12544     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12545     << FnDecl->getDeclName() << ExpectedFirstParamType;
12546 
12547   return false;
12548 }
12549 
12550 static bool
12551 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12552   // C++ [basic.stc.dynamic.allocation]p1:
12553   //   A program is ill-formed if an allocation function is declared in a
12554   //   namespace scope other than global scope or declared static in global
12555   //   scope.
12556   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12557     return true;
12558 
12559   CanQualType SizeTy =
12560     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12561 
12562   // C++ [basic.stc.dynamic.allocation]p1:
12563   //  The return type shall be void*. The first parameter shall have type
12564   //  std::size_t.
12565   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12566                                   SizeTy,
12567                                   diag::err_operator_new_dependent_param_type,
12568                                   diag::err_operator_new_param_type))
12569     return true;
12570 
12571   // C++ [basic.stc.dynamic.allocation]p1:
12572   //  The first parameter shall not have an associated default argument.
12573   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12574     return SemaRef.Diag(FnDecl->getLocation(),
12575                         diag::err_operator_new_default_arg)
12576       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12577 
12578   return false;
12579 }
12580 
12581 static bool
12582 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12583   // C++ [basic.stc.dynamic.deallocation]p1:
12584   //   A program is ill-formed if deallocation functions are declared in a
12585   //   namespace scope other than global scope or declared static in global
12586   //   scope.
12587   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12588     return true;
12589 
12590   // C++ [basic.stc.dynamic.deallocation]p2:
12591   //   Each deallocation function shall return void and its first parameter
12592   //   shall be void*.
12593   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12594                                   SemaRef.Context.VoidPtrTy,
12595                                  diag::err_operator_delete_dependent_param_type,
12596                                  diag::err_operator_delete_param_type))
12597     return true;
12598 
12599   return false;
12600 }
12601 
12602 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12603 /// of this overloaded operator is well-formed. If so, returns false;
12604 /// otherwise, emits appropriate diagnostics and returns true.
12605 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12606   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12607          "Expected an overloaded operator declaration");
12608 
12609   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12610 
12611   // C++ [over.oper]p5:
12612   //   The allocation and deallocation functions, operator new,
12613   //   operator new[], operator delete and operator delete[], are
12614   //   described completely in 3.7.3. The attributes and restrictions
12615   //   found in the rest of this subclause do not apply to them unless
12616   //   explicitly stated in 3.7.3.
12617   if (Op == OO_Delete || Op == OO_Array_Delete)
12618     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12619 
12620   if (Op == OO_New || Op == OO_Array_New)
12621     return CheckOperatorNewDeclaration(*this, FnDecl);
12622 
12623   // C++ [over.oper]p6:
12624   //   An operator function shall either be a non-static member
12625   //   function or be a non-member function and have at least one
12626   //   parameter whose type is a class, a reference to a class, an
12627   //   enumeration, or a reference to an enumeration.
12628   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12629     if (MethodDecl->isStatic())
12630       return Diag(FnDecl->getLocation(),
12631                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12632   } else {
12633     bool ClassOrEnumParam = false;
12634     for (auto Param : FnDecl->parameters()) {
12635       QualType ParamType = Param->getType().getNonReferenceType();
12636       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12637           ParamType->isEnumeralType()) {
12638         ClassOrEnumParam = true;
12639         break;
12640       }
12641     }
12642 
12643     if (!ClassOrEnumParam)
12644       return Diag(FnDecl->getLocation(),
12645                   diag::err_operator_overload_needs_class_or_enum)
12646         << FnDecl->getDeclName();
12647   }
12648 
12649   // C++ [over.oper]p8:
12650   //   An operator function cannot have default arguments (8.3.6),
12651   //   except where explicitly stated below.
12652   //
12653   // Only the function-call operator allows default arguments
12654   // (C++ [over.call]p1).
12655   if (Op != OO_Call) {
12656     for (auto Param : FnDecl->parameters()) {
12657       if (Param->hasDefaultArg())
12658         return Diag(Param->getLocation(),
12659                     diag::err_operator_overload_default_arg)
12660           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12661     }
12662   }
12663 
12664   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12665     { false, false, false }
12666 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12667     , { Unary, Binary, MemberOnly }
12668 #include "clang/Basic/OperatorKinds.def"
12669   };
12670 
12671   bool CanBeUnaryOperator = OperatorUses[Op][0];
12672   bool CanBeBinaryOperator = OperatorUses[Op][1];
12673   bool MustBeMemberOperator = OperatorUses[Op][2];
12674 
12675   // C++ [over.oper]p8:
12676   //   [...] Operator functions cannot have more or fewer parameters
12677   //   than the number required for the corresponding operator, as
12678   //   described in the rest of this subclause.
12679   unsigned NumParams = FnDecl->getNumParams()
12680                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12681   if (Op != OO_Call &&
12682       ((NumParams == 1 && !CanBeUnaryOperator) ||
12683        (NumParams == 2 && !CanBeBinaryOperator) ||
12684        (NumParams < 1) || (NumParams > 2))) {
12685     // We have the wrong number of parameters.
12686     unsigned ErrorKind;
12687     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12688       ErrorKind = 2;  // 2 -> unary or binary.
12689     } else if (CanBeUnaryOperator) {
12690       ErrorKind = 0;  // 0 -> unary
12691     } else {
12692       assert(CanBeBinaryOperator &&
12693              "All non-call overloaded operators are unary or binary!");
12694       ErrorKind = 1;  // 1 -> binary
12695     }
12696 
12697     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12698       << FnDecl->getDeclName() << NumParams << ErrorKind;
12699   }
12700 
12701   // Overloaded operators other than operator() cannot be variadic.
12702   if (Op != OO_Call &&
12703       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12704     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12705       << FnDecl->getDeclName();
12706   }
12707 
12708   // Some operators must be non-static member functions.
12709   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12710     return Diag(FnDecl->getLocation(),
12711                 diag::err_operator_overload_must_be_member)
12712       << FnDecl->getDeclName();
12713   }
12714 
12715   // C++ [over.inc]p1:
12716   //   The user-defined function called operator++ implements the
12717   //   prefix and postfix ++ operator. If this function is a member
12718   //   function with no parameters, or a non-member function with one
12719   //   parameter of class or enumeration type, it defines the prefix
12720   //   increment operator ++ for objects of that type. If the function
12721   //   is a member function with one parameter (which shall be of type
12722   //   int) or a non-member function with two parameters (the second
12723   //   of which shall be of type int), it defines the postfix
12724   //   increment operator ++ for objects of that type.
12725   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12726     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12727     QualType ParamType = LastParam->getType();
12728 
12729     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12730         !ParamType->isDependentType())
12731       return Diag(LastParam->getLocation(),
12732                   diag::err_operator_overload_post_incdec_must_be_int)
12733         << LastParam->getType() << (Op == OO_MinusMinus);
12734   }
12735 
12736   return false;
12737 }
12738 
12739 static bool
12740 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12741                                           FunctionTemplateDecl *TpDecl) {
12742   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12743 
12744   // Must have one or two template parameters.
12745   if (TemplateParams->size() == 1) {
12746     NonTypeTemplateParmDecl *PmDecl =
12747         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12748 
12749     // The template parameter must be a char parameter pack.
12750     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12751         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12752       return false;
12753 
12754   } else if (TemplateParams->size() == 2) {
12755     TemplateTypeParmDecl *PmType =
12756         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12757     NonTypeTemplateParmDecl *PmArgs =
12758         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12759 
12760     // The second template parameter must be a parameter pack with the
12761     // first template parameter as its type.
12762     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12763         PmArgs->isTemplateParameterPack()) {
12764       const TemplateTypeParmType *TArgs =
12765           PmArgs->getType()->getAs<TemplateTypeParmType>();
12766       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12767           TArgs->getIndex() == PmType->getIndex()) {
12768         if (SemaRef.ActiveTemplateInstantiations.empty())
12769           SemaRef.Diag(TpDecl->getLocation(),
12770                        diag::ext_string_literal_operator_template);
12771         return false;
12772       }
12773     }
12774   }
12775 
12776   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12777                diag::err_literal_operator_template)
12778       << TpDecl->getTemplateParameters()->getSourceRange();
12779   return true;
12780 }
12781 
12782 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12783 /// of this literal operator function is well-formed. If so, returns
12784 /// false; otherwise, emits appropriate diagnostics and returns true.
12785 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12786   if (isa<CXXMethodDecl>(FnDecl)) {
12787     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12788       << FnDecl->getDeclName();
12789     return true;
12790   }
12791 
12792   if (FnDecl->isExternC()) {
12793     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12794     if (const LinkageSpecDecl *LSD =
12795             FnDecl->getDeclContext()->getExternCContext())
12796       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
12797     return true;
12798   }
12799 
12800   // This might be the definition of a literal operator template.
12801   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12802 
12803   // This might be a specialization of a literal operator template.
12804   if (!TpDecl)
12805     TpDecl = FnDecl->getPrimaryTemplate();
12806 
12807   // template <char...> type operator "" name() and
12808   // template <class T, T...> type operator "" name() are the only valid
12809   // template signatures, and the only valid signatures with no parameters.
12810   if (TpDecl) {
12811     if (FnDecl->param_size() != 0) {
12812       Diag(FnDecl->getLocation(),
12813            diag::err_literal_operator_template_with_params);
12814       return true;
12815     }
12816 
12817     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12818       return true;
12819 
12820   } else if (FnDecl->param_size() == 1) {
12821     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12822 
12823     QualType ParamType = Param->getType().getUnqualifiedType();
12824 
12825     // Only unsigned long long int, long double, any character type, and const
12826     // char * are allowed as the only parameters.
12827     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12828         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12829         Context.hasSameType(ParamType, Context.CharTy) ||
12830         Context.hasSameType(ParamType, Context.WideCharTy) ||
12831         Context.hasSameType(ParamType, Context.Char16Ty) ||
12832         Context.hasSameType(ParamType, Context.Char32Ty)) {
12833     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12834       QualType InnerType = Ptr->getPointeeType();
12835 
12836       // Pointer parameter must be a const char *.
12837       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12838                                 Context.CharTy) &&
12839             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12840         Diag(Param->getSourceRange().getBegin(),
12841              diag::err_literal_operator_param)
12842             << ParamType << "'const char *'" << Param->getSourceRange();
12843         return true;
12844       }
12845 
12846     } else if (ParamType->isRealFloatingType()) {
12847       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12848           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12849       return true;
12850 
12851     } else if (ParamType->isIntegerType()) {
12852       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12853           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12854       return true;
12855 
12856     } else {
12857       Diag(Param->getSourceRange().getBegin(),
12858            diag::err_literal_operator_invalid_param)
12859           << ParamType << Param->getSourceRange();
12860       return true;
12861     }
12862 
12863   } else if (FnDecl->param_size() == 2) {
12864     FunctionDecl::param_iterator Param = FnDecl->param_begin();
12865 
12866     // First, verify that the first parameter is correct.
12867 
12868     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12869 
12870     // Two parameter function must have a pointer to const as a
12871     // first parameter; let's strip those qualifiers.
12872     const PointerType *PT = FirstParamType->getAs<PointerType>();
12873 
12874     if (!PT) {
12875       Diag((*Param)->getSourceRange().getBegin(),
12876            diag::err_literal_operator_param)
12877           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12878       return true;
12879     }
12880 
12881     QualType PointeeType = PT->getPointeeType();
12882     // First parameter must be const
12883     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12884       Diag((*Param)->getSourceRange().getBegin(),
12885            diag::err_literal_operator_param)
12886           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12887       return true;
12888     }
12889 
12890     QualType InnerType = PointeeType.getUnqualifiedType();
12891     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12892     // are allowed as the first parameter to a two-parameter function
12893     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12894           Context.hasSameType(InnerType, Context.WideCharTy) ||
12895           Context.hasSameType(InnerType, Context.Char16Ty) ||
12896           Context.hasSameType(InnerType, Context.Char32Ty))) {
12897       Diag((*Param)->getSourceRange().getBegin(),
12898            diag::err_literal_operator_param)
12899           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12900       return true;
12901     }
12902 
12903     // Move on to the second and final parameter.
12904     ++Param;
12905 
12906     // The second parameter must be a std::size_t.
12907     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12908     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12909       Diag((*Param)->getSourceRange().getBegin(),
12910            diag::err_literal_operator_param)
12911           << SecondParamType << Context.getSizeType()
12912           << (*Param)->getSourceRange();
12913       return true;
12914     }
12915   } else {
12916     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12917     return true;
12918   }
12919 
12920   // Parameters are good.
12921 
12922   // A parameter-declaration-clause containing a default argument is not
12923   // equivalent to any of the permitted forms.
12924   for (auto Param : FnDecl->parameters()) {
12925     if (Param->hasDefaultArg()) {
12926       Diag(Param->getDefaultArgRange().getBegin(),
12927            diag::err_literal_operator_default_argument)
12928         << Param->getDefaultArgRange();
12929       break;
12930     }
12931   }
12932 
12933   StringRef LiteralName
12934     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12935   if (LiteralName[0] != '_') {
12936     // C++11 [usrlit.suffix]p1:
12937     //   Literal suffix identifiers that do not start with an underscore
12938     //   are reserved for future standardization.
12939     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12940       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12941   }
12942 
12943   return false;
12944 }
12945 
12946 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12947 /// linkage specification, including the language and (if present)
12948 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12949 /// language string literal. LBraceLoc, if valid, provides the location of
12950 /// the '{' brace. Otherwise, this linkage specification does not
12951 /// have any braces.
12952 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12953                                            Expr *LangStr,
12954                                            SourceLocation LBraceLoc) {
12955   StringLiteral *Lit = cast<StringLiteral>(LangStr);
12956   if (!Lit->isAscii()) {
12957     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12958       << LangStr->getSourceRange();
12959     return nullptr;
12960   }
12961 
12962   StringRef Lang = Lit->getString();
12963   LinkageSpecDecl::LanguageIDs Language;
12964   if (Lang == "C")
12965     Language = LinkageSpecDecl::lang_c;
12966   else if (Lang == "C++")
12967     Language = LinkageSpecDecl::lang_cxx;
12968   else {
12969     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12970       << LangStr->getSourceRange();
12971     return nullptr;
12972   }
12973 
12974   // FIXME: Add all the various semantics of linkage specifications
12975 
12976   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12977                                                LangStr->getExprLoc(), Language,
12978                                                LBraceLoc.isValid());
12979   CurContext->addDecl(D);
12980   PushDeclContext(S, D);
12981   return D;
12982 }
12983 
12984 /// ActOnFinishLinkageSpecification - Complete the definition of
12985 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12986 /// valid, it's the position of the closing '}' brace in a linkage
12987 /// specification that uses braces.
12988 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12989                                             Decl *LinkageSpec,
12990                                             SourceLocation RBraceLoc) {
12991   if (RBraceLoc.isValid()) {
12992     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12993     LSDecl->setRBraceLoc(RBraceLoc);
12994   }
12995   PopDeclContext();
12996   return LinkageSpec;
12997 }
12998 
12999 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13000                                   AttributeList *AttrList,
13001                                   SourceLocation SemiLoc) {
13002   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13003   // Attribute declarations appertain to empty declaration so we handle
13004   // them here.
13005   if (AttrList)
13006     ProcessDeclAttributeList(S, ED, AttrList);
13007 
13008   CurContext->addDecl(ED);
13009   return ED;
13010 }
13011 
13012 /// \brief Perform semantic analysis for the variable declaration that
13013 /// occurs within a C++ catch clause, returning the newly-created
13014 /// variable.
13015 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13016                                          TypeSourceInfo *TInfo,
13017                                          SourceLocation StartLoc,
13018                                          SourceLocation Loc,
13019                                          IdentifierInfo *Name) {
13020   bool Invalid = false;
13021   QualType ExDeclType = TInfo->getType();
13022 
13023   // Arrays and functions decay.
13024   if (ExDeclType->isArrayType())
13025     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13026   else if (ExDeclType->isFunctionType())
13027     ExDeclType = Context.getPointerType(ExDeclType);
13028 
13029   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13030   // The exception-declaration shall not denote a pointer or reference to an
13031   // incomplete type, other than [cv] void*.
13032   // N2844 forbids rvalue references.
13033   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13034     Diag(Loc, diag::err_catch_rvalue_ref);
13035     Invalid = true;
13036   }
13037 
13038   if (ExDeclType->isVariablyModifiedType()) {
13039     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13040     Invalid = true;
13041   }
13042 
13043   QualType BaseType = ExDeclType;
13044   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13045   unsigned DK = diag::err_catch_incomplete;
13046   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13047     BaseType = Ptr->getPointeeType();
13048     Mode = 1;
13049     DK = diag::err_catch_incomplete_ptr;
13050   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13051     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13052     BaseType = Ref->getPointeeType();
13053     Mode = 2;
13054     DK = diag::err_catch_incomplete_ref;
13055   }
13056   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13057       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13058     Invalid = true;
13059 
13060   if (!Invalid && !ExDeclType->isDependentType() &&
13061       RequireNonAbstractType(Loc, ExDeclType,
13062                              diag::err_abstract_type_in_decl,
13063                              AbstractVariableType))
13064     Invalid = true;
13065 
13066   // Only the non-fragile NeXT runtime currently supports C++ catches
13067   // of ObjC types, and no runtime supports catching ObjC types by value.
13068   if (!Invalid && getLangOpts().ObjC1) {
13069     QualType T = ExDeclType;
13070     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13071       T = RT->getPointeeType();
13072 
13073     if (T->isObjCObjectType()) {
13074       Diag(Loc, diag::err_objc_object_catch);
13075       Invalid = true;
13076     } else if (T->isObjCObjectPointerType()) {
13077       // FIXME: should this be a test for macosx-fragile specifically?
13078       if (getLangOpts().ObjCRuntime.isFragile())
13079         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13080     }
13081   }
13082 
13083   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13084                                     ExDeclType, TInfo, SC_None);
13085   ExDecl->setExceptionVariable(true);
13086 
13087   // In ARC, infer 'retaining' for variables of retainable type.
13088   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13089     Invalid = true;
13090 
13091   if (!Invalid && !ExDeclType->isDependentType()) {
13092     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13093       // Insulate this from anything else we might currently be parsing.
13094       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13095 
13096       // C++ [except.handle]p16:
13097       //   The object declared in an exception-declaration or, if the
13098       //   exception-declaration does not specify a name, a temporary (12.2) is
13099       //   copy-initialized (8.5) from the exception object. [...]
13100       //   The object is destroyed when the handler exits, after the destruction
13101       //   of any automatic objects initialized within the handler.
13102       //
13103       // We just pretend to initialize the object with itself, then make sure
13104       // it can be destroyed later.
13105       QualType initType = Context.getExceptionObjectType(ExDeclType);
13106 
13107       InitializedEntity entity =
13108         InitializedEntity::InitializeVariable(ExDecl);
13109       InitializationKind initKind =
13110         InitializationKind::CreateCopy(Loc, SourceLocation());
13111 
13112       Expr *opaqueValue =
13113         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13114       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13115       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13116       if (result.isInvalid())
13117         Invalid = true;
13118       else {
13119         // If the constructor used was non-trivial, set this as the
13120         // "initializer".
13121         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13122         if (!construct->getConstructor()->isTrivial()) {
13123           Expr *init = MaybeCreateExprWithCleanups(construct);
13124           ExDecl->setInit(init);
13125         }
13126 
13127         // And make sure it's destructable.
13128         FinalizeVarWithDestructor(ExDecl, recordType);
13129       }
13130     }
13131   }
13132 
13133   if (Invalid)
13134     ExDecl->setInvalidDecl();
13135 
13136   return ExDecl;
13137 }
13138 
13139 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13140 /// handler.
13141 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13142   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13143   bool Invalid = D.isInvalidType();
13144 
13145   // Check for unexpanded parameter packs.
13146   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13147                                       UPPC_ExceptionType)) {
13148     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13149                                              D.getIdentifierLoc());
13150     Invalid = true;
13151   }
13152 
13153   IdentifierInfo *II = D.getIdentifier();
13154   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13155                                              LookupOrdinaryName,
13156                                              ForRedeclaration)) {
13157     // The scope should be freshly made just for us. There is just no way
13158     // it contains any previous declaration, except for function parameters in
13159     // a function-try-block's catch statement.
13160     assert(!S->isDeclScope(PrevDecl));
13161     if (isDeclInScope(PrevDecl, CurContext, S)) {
13162       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13163         << D.getIdentifier();
13164       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13165       Invalid = true;
13166     } else if (PrevDecl->isTemplateParameter())
13167       // Maybe we will complain about the shadowed template parameter.
13168       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13169   }
13170 
13171   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13172     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13173       << D.getCXXScopeSpec().getRange();
13174     Invalid = true;
13175   }
13176 
13177   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13178                                               D.getLocStart(),
13179                                               D.getIdentifierLoc(),
13180                                               D.getIdentifier());
13181   if (Invalid)
13182     ExDecl->setInvalidDecl();
13183 
13184   // Add the exception declaration into this scope.
13185   if (II)
13186     PushOnScopeChains(ExDecl, S);
13187   else
13188     CurContext->addDecl(ExDecl);
13189 
13190   ProcessDeclAttributes(S, ExDecl, D);
13191   return ExDecl;
13192 }
13193 
13194 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13195                                          Expr *AssertExpr,
13196                                          Expr *AssertMessageExpr,
13197                                          SourceLocation RParenLoc) {
13198   StringLiteral *AssertMessage =
13199       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13200 
13201   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13202     return nullptr;
13203 
13204   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13205                                       AssertMessage, RParenLoc, false);
13206 }
13207 
13208 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13209                                          Expr *AssertExpr,
13210                                          StringLiteral *AssertMessage,
13211                                          SourceLocation RParenLoc,
13212                                          bool Failed) {
13213   assert(AssertExpr != nullptr && "Expected non-null condition");
13214   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13215       !Failed) {
13216     // In a static_assert-declaration, the constant-expression shall be a
13217     // constant expression that can be contextually converted to bool.
13218     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13219     if (Converted.isInvalid())
13220       Failed = true;
13221 
13222     llvm::APSInt Cond;
13223     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13224           diag::err_static_assert_expression_is_not_constant,
13225           /*AllowFold=*/false).isInvalid())
13226       Failed = true;
13227 
13228     if (!Failed && !Cond) {
13229       SmallString<256> MsgBuffer;
13230       llvm::raw_svector_ostream Msg(MsgBuffer);
13231       if (AssertMessage)
13232         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13233       Diag(StaticAssertLoc, diag::err_static_assert_failed)
13234         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13235       Failed = true;
13236     }
13237   }
13238 
13239   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13240                                         AssertExpr, AssertMessage, RParenLoc,
13241                                         Failed);
13242 
13243   CurContext->addDecl(Decl);
13244   return Decl;
13245 }
13246 
13247 /// \brief Perform semantic analysis of the given friend type declaration.
13248 ///
13249 /// \returns A friend declaration that.
13250 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13251                                       SourceLocation FriendLoc,
13252                                       TypeSourceInfo *TSInfo) {
13253   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13254 
13255   QualType T = TSInfo->getType();
13256   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13257 
13258   // C++03 [class.friend]p2:
13259   //   An elaborated-type-specifier shall be used in a friend declaration
13260   //   for a class.*
13261   //
13262   //   * The class-key of the elaborated-type-specifier is required.
13263   if (!ActiveTemplateInstantiations.empty()) {
13264     // Do not complain about the form of friend template types during
13265     // template instantiation; we will already have complained when the
13266     // template was declared.
13267   } else {
13268     if (!T->isElaboratedTypeSpecifier()) {
13269       // If we evaluated the type to a record type, suggest putting
13270       // a tag in front.
13271       if (const RecordType *RT = T->getAs<RecordType>()) {
13272         RecordDecl *RD = RT->getDecl();
13273 
13274         SmallString<16> InsertionText(" ");
13275         InsertionText += RD->getKindName();
13276 
13277         Diag(TypeRange.getBegin(),
13278              getLangOpts().CPlusPlus11 ?
13279                diag::warn_cxx98_compat_unelaborated_friend_type :
13280                diag::ext_unelaborated_friend_type)
13281           << (unsigned) RD->getTagKind()
13282           << T
13283           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13284                                         InsertionText);
13285       } else {
13286         Diag(FriendLoc,
13287              getLangOpts().CPlusPlus11 ?
13288                diag::warn_cxx98_compat_nonclass_type_friend :
13289                diag::ext_nonclass_type_friend)
13290           << T
13291           << TypeRange;
13292       }
13293     } else if (T->getAs<EnumType>()) {
13294       Diag(FriendLoc,
13295            getLangOpts().CPlusPlus11 ?
13296              diag::warn_cxx98_compat_enum_friend :
13297              diag::ext_enum_friend)
13298         << T
13299         << TypeRange;
13300     }
13301 
13302     // C++11 [class.friend]p3:
13303     //   A friend declaration that does not declare a function shall have one
13304     //   of the following forms:
13305     //     friend elaborated-type-specifier ;
13306     //     friend simple-type-specifier ;
13307     //     friend typename-specifier ;
13308     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13309       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13310   }
13311 
13312   //   If the type specifier in a friend declaration designates a (possibly
13313   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13314   //   the friend declaration is ignored.
13315   return FriendDecl::Create(Context, CurContext,
13316                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13317                             FriendLoc);
13318 }
13319 
13320 /// Handle a friend tag declaration where the scope specifier was
13321 /// templated.
13322 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13323                                     unsigned TagSpec, SourceLocation TagLoc,
13324                                     CXXScopeSpec &SS,
13325                                     IdentifierInfo *Name,
13326                                     SourceLocation NameLoc,
13327                                     AttributeList *Attr,
13328                                     MultiTemplateParamsArg TempParamLists) {
13329   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13330 
13331   bool isExplicitSpecialization = false;
13332   bool Invalid = false;
13333 
13334   if (TemplateParameterList *TemplateParams =
13335           MatchTemplateParametersToScopeSpecifier(
13336               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13337               isExplicitSpecialization, Invalid)) {
13338     if (TemplateParams->size() > 0) {
13339       // This is a declaration of a class template.
13340       if (Invalid)
13341         return nullptr;
13342 
13343       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13344                                 NameLoc, Attr, TemplateParams, AS_public,
13345                                 /*ModulePrivateLoc=*/SourceLocation(),
13346                                 FriendLoc, TempParamLists.size() - 1,
13347                                 TempParamLists.data()).get();
13348     } else {
13349       // The "template<>" header is extraneous.
13350       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13351         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13352       isExplicitSpecialization = true;
13353     }
13354   }
13355 
13356   if (Invalid) return nullptr;
13357 
13358   bool isAllExplicitSpecializations = true;
13359   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13360     if (TempParamLists[I]->size()) {
13361       isAllExplicitSpecializations = false;
13362       break;
13363     }
13364   }
13365 
13366   // FIXME: don't ignore attributes.
13367 
13368   // If it's explicit specializations all the way down, just forget
13369   // about the template header and build an appropriate non-templated
13370   // friend.  TODO: for source fidelity, remember the headers.
13371   if (isAllExplicitSpecializations) {
13372     if (SS.isEmpty()) {
13373       bool Owned = false;
13374       bool IsDependent = false;
13375       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13376                       Attr, AS_public,
13377                       /*ModulePrivateLoc=*/SourceLocation(),
13378                       MultiTemplateParamsArg(), Owned, IsDependent,
13379                       /*ScopedEnumKWLoc=*/SourceLocation(),
13380                       /*ScopedEnumUsesClassTag=*/false,
13381                       /*UnderlyingType=*/TypeResult(),
13382                       /*IsTypeSpecifier=*/false);
13383     }
13384 
13385     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13386     ElaboratedTypeKeyword Keyword
13387       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13388     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13389                                    *Name, NameLoc);
13390     if (T.isNull())
13391       return nullptr;
13392 
13393     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13394     if (isa<DependentNameType>(T)) {
13395       DependentNameTypeLoc TL =
13396           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13397       TL.setElaboratedKeywordLoc(TagLoc);
13398       TL.setQualifierLoc(QualifierLoc);
13399       TL.setNameLoc(NameLoc);
13400     } else {
13401       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13402       TL.setElaboratedKeywordLoc(TagLoc);
13403       TL.setQualifierLoc(QualifierLoc);
13404       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13405     }
13406 
13407     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13408                                             TSI, FriendLoc, TempParamLists);
13409     Friend->setAccess(AS_public);
13410     CurContext->addDecl(Friend);
13411     return Friend;
13412   }
13413 
13414   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13415 
13416 
13417 
13418   // Handle the case of a templated-scope friend class.  e.g.
13419   //   template <class T> class A<T>::B;
13420   // FIXME: we don't support these right now.
13421   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13422     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13423   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13424   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13425   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13426   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13427   TL.setElaboratedKeywordLoc(TagLoc);
13428   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13429   TL.setNameLoc(NameLoc);
13430 
13431   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13432                                           TSI, FriendLoc, TempParamLists);
13433   Friend->setAccess(AS_public);
13434   Friend->setUnsupportedFriend(true);
13435   CurContext->addDecl(Friend);
13436   return Friend;
13437 }
13438 
13439 
13440 /// Handle a friend type declaration.  This works in tandem with
13441 /// ActOnTag.
13442 ///
13443 /// Notes on friend class templates:
13444 ///
13445 /// We generally treat friend class declarations as if they were
13446 /// declaring a class.  So, for example, the elaborated type specifier
13447 /// in a friend declaration is required to obey the restrictions of a
13448 /// class-head (i.e. no typedefs in the scope chain), template
13449 /// parameters are required to match up with simple template-ids, &c.
13450 /// However, unlike when declaring a template specialization, it's
13451 /// okay to refer to a template specialization without an empty
13452 /// template parameter declaration, e.g.
13453 ///   friend class A<T>::B<unsigned>;
13454 /// We permit this as a special case; if there are any template
13455 /// parameters present at all, require proper matching, i.e.
13456 ///   template <> template \<class T> friend class A<int>::B;
13457 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13458                                 MultiTemplateParamsArg TempParams) {
13459   SourceLocation Loc = DS.getLocStart();
13460 
13461   assert(DS.isFriendSpecified());
13462   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13463 
13464   // Try to convert the decl specifier to a type.  This works for
13465   // friend templates because ActOnTag never produces a ClassTemplateDecl
13466   // for a TUK_Friend.
13467   Declarator TheDeclarator(DS, Declarator::MemberContext);
13468   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13469   QualType T = TSI->getType();
13470   if (TheDeclarator.isInvalidType())
13471     return nullptr;
13472 
13473   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13474     return nullptr;
13475 
13476   // This is definitely an error in C++98.  It's probably meant to
13477   // be forbidden in C++0x, too, but the specification is just
13478   // poorly written.
13479   //
13480   // The problem is with declarations like the following:
13481   //   template <T> friend A<T>::foo;
13482   // where deciding whether a class C is a friend or not now hinges
13483   // on whether there exists an instantiation of A that causes
13484   // 'foo' to equal C.  There are restrictions on class-heads
13485   // (which we declare (by fiat) elaborated friend declarations to
13486   // be) that makes this tractable.
13487   //
13488   // FIXME: handle "template <> friend class A<T>;", which
13489   // is possibly well-formed?  Who even knows?
13490   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13491     Diag(Loc, diag::err_tagless_friend_type_template)
13492       << DS.getSourceRange();
13493     return nullptr;
13494   }
13495 
13496   // C++98 [class.friend]p1: A friend of a class is a function
13497   //   or class that is not a member of the class . . .
13498   // This is fixed in DR77, which just barely didn't make the C++03
13499   // deadline.  It's also a very silly restriction that seriously
13500   // affects inner classes and which nobody else seems to implement;
13501   // thus we never diagnose it, not even in -pedantic.
13502   //
13503   // But note that we could warn about it: it's always useless to
13504   // friend one of your own members (it's not, however, worthless to
13505   // friend a member of an arbitrary specialization of your template).
13506 
13507   Decl *D;
13508   if (!TempParams.empty())
13509     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13510                                    TempParams,
13511                                    TSI,
13512                                    DS.getFriendSpecLoc());
13513   else
13514     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13515 
13516   if (!D)
13517     return nullptr;
13518 
13519   D->setAccess(AS_public);
13520   CurContext->addDecl(D);
13521 
13522   return D;
13523 }
13524 
13525 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13526                                         MultiTemplateParamsArg TemplateParams) {
13527   const DeclSpec &DS = D.getDeclSpec();
13528 
13529   assert(DS.isFriendSpecified());
13530   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13531 
13532   SourceLocation Loc = D.getIdentifierLoc();
13533   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13534 
13535   // C++ [class.friend]p1
13536   //   A friend of a class is a function or class....
13537   // Note that this sees through typedefs, which is intended.
13538   // It *doesn't* see through dependent types, which is correct
13539   // according to [temp.arg.type]p3:
13540   //   If a declaration acquires a function type through a
13541   //   type dependent on a template-parameter and this causes
13542   //   a declaration that does not use the syntactic form of a
13543   //   function declarator to have a function type, the program
13544   //   is ill-formed.
13545   if (!TInfo->getType()->isFunctionType()) {
13546     Diag(Loc, diag::err_unexpected_friend);
13547 
13548     // It might be worthwhile to try to recover by creating an
13549     // appropriate declaration.
13550     return nullptr;
13551   }
13552 
13553   // C++ [namespace.memdef]p3
13554   //  - If a friend declaration in a non-local class first declares a
13555   //    class or function, the friend class or function is a member
13556   //    of the innermost enclosing namespace.
13557   //  - The name of the friend is not found by simple name lookup
13558   //    until a matching declaration is provided in that namespace
13559   //    scope (either before or after the class declaration granting
13560   //    friendship).
13561   //  - If a friend function is called, its name may be found by the
13562   //    name lookup that considers functions from namespaces and
13563   //    classes associated with the types of the function arguments.
13564   //  - When looking for a prior declaration of a class or a function
13565   //    declared as a friend, scopes outside the innermost enclosing
13566   //    namespace scope are not considered.
13567 
13568   CXXScopeSpec &SS = D.getCXXScopeSpec();
13569   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13570   DeclarationName Name = NameInfo.getName();
13571   assert(Name);
13572 
13573   // Check for unexpanded parameter packs.
13574   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13575       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13576       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13577     return nullptr;
13578 
13579   // The context we found the declaration in, or in which we should
13580   // create the declaration.
13581   DeclContext *DC;
13582   Scope *DCScope = S;
13583   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13584                         ForRedeclaration);
13585 
13586   // There are five cases here.
13587   //   - There's no scope specifier and we're in a local class. Only look
13588   //     for functions declared in the immediately-enclosing block scope.
13589   // We recover from invalid scope qualifiers as if they just weren't there.
13590   FunctionDecl *FunctionContainingLocalClass = nullptr;
13591   if ((SS.isInvalid() || !SS.isSet()) &&
13592       (FunctionContainingLocalClass =
13593            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13594     // C++11 [class.friend]p11:
13595     //   If a friend declaration appears in a local class and the name
13596     //   specified is an unqualified name, a prior declaration is
13597     //   looked up without considering scopes that are outside the
13598     //   innermost enclosing non-class scope. For a friend function
13599     //   declaration, if there is no prior declaration, the program is
13600     //   ill-formed.
13601 
13602     // Find the innermost enclosing non-class scope. This is the block
13603     // scope containing the local class definition (or for a nested class,
13604     // the outer local class).
13605     DCScope = S->getFnParent();
13606 
13607     // Look up the function name in the scope.
13608     Previous.clear(LookupLocalFriendName);
13609     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13610 
13611     if (!Previous.empty()) {
13612       // All possible previous declarations must have the same context:
13613       // either they were declared at block scope or they are members of
13614       // one of the enclosing local classes.
13615       DC = Previous.getRepresentativeDecl()->getDeclContext();
13616     } else {
13617       // This is ill-formed, but provide the context that we would have
13618       // declared the function in, if we were permitted to, for error recovery.
13619       DC = FunctionContainingLocalClass;
13620     }
13621     adjustContextForLocalExternDecl(DC);
13622 
13623     // C++ [class.friend]p6:
13624     //   A function can be defined in a friend declaration of a class if and
13625     //   only if the class is a non-local class (9.8), the function name is
13626     //   unqualified, and the function has namespace scope.
13627     if (D.isFunctionDefinition()) {
13628       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13629     }
13630 
13631   //   - There's no scope specifier, in which case we just go to the
13632   //     appropriate scope and look for a function or function template
13633   //     there as appropriate.
13634   } else if (SS.isInvalid() || !SS.isSet()) {
13635     // C++11 [namespace.memdef]p3:
13636     //   If the name in a friend declaration is neither qualified nor
13637     //   a template-id and the declaration is a function or an
13638     //   elaborated-type-specifier, the lookup to determine whether
13639     //   the entity has been previously declared shall not consider
13640     //   any scopes outside the innermost enclosing namespace.
13641     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13642 
13643     // Find the appropriate context according to the above.
13644     DC = CurContext;
13645 
13646     // Skip class contexts.  If someone can cite chapter and verse
13647     // for this behavior, that would be nice --- it's what GCC and
13648     // EDG do, and it seems like a reasonable intent, but the spec
13649     // really only says that checks for unqualified existing
13650     // declarations should stop at the nearest enclosing namespace,
13651     // not that they should only consider the nearest enclosing
13652     // namespace.
13653     while (DC->isRecord())
13654       DC = DC->getParent();
13655 
13656     DeclContext *LookupDC = DC;
13657     while (LookupDC->isTransparentContext())
13658       LookupDC = LookupDC->getParent();
13659 
13660     while (true) {
13661       LookupQualifiedName(Previous, LookupDC);
13662 
13663       if (!Previous.empty()) {
13664         DC = LookupDC;
13665         break;
13666       }
13667 
13668       if (isTemplateId) {
13669         if (isa<TranslationUnitDecl>(LookupDC)) break;
13670       } else {
13671         if (LookupDC->isFileContext()) break;
13672       }
13673       LookupDC = LookupDC->getParent();
13674     }
13675 
13676     DCScope = getScopeForDeclContext(S, DC);
13677 
13678   //   - There's a non-dependent scope specifier, in which case we
13679   //     compute it and do a previous lookup there for a function
13680   //     or function template.
13681   } else if (!SS.getScopeRep()->isDependent()) {
13682     DC = computeDeclContext(SS);
13683     if (!DC) return nullptr;
13684 
13685     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13686 
13687     LookupQualifiedName(Previous, DC);
13688 
13689     // Ignore things found implicitly in the wrong scope.
13690     // TODO: better diagnostics for this case.  Suggesting the right
13691     // qualified scope would be nice...
13692     LookupResult::Filter F = Previous.makeFilter();
13693     while (F.hasNext()) {
13694       NamedDecl *D = F.next();
13695       if (!DC->InEnclosingNamespaceSetOf(
13696               D->getDeclContext()->getRedeclContext()))
13697         F.erase();
13698     }
13699     F.done();
13700 
13701     if (Previous.empty()) {
13702       D.setInvalidType();
13703       Diag(Loc, diag::err_qualified_friend_not_found)
13704           << Name << TInfo->getType();
13705       return nullptr;
13706     }
13707 
13708     // C++ [class.friend]p1: A friend of a class is a function or
13709     //   class that is not a member of the class . . .
13710     if (DC->Equals(CurContext))
13711       Diag(DS.getFriendSpecLoc(),
13712            getLangOpts().CPlusPlus11 ?
13713              diag::warn_cxx98_compat_friend_is_member :
13714              diag::err_friend_is_member);
13715 
13716     if (D.isFunctionDefinition()) {
13717       // C++ [class.friend]p6:
13718       //   A function can be defined in a friend declaration of a class if and
13719       //   only if the class is a non-local class (9.8), the function name is
13720       //   unqualified, and the function has namespace scope.
13721       SemaDiagnosticBuilder DB
13722         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13723 
13724       DB << SS.getScopeRep();
13725       if (DC->isFileContext())
13726         DB << FixItHint::CreateRemoval(SS.getRange());
13727       SS.clear();
13728     }
13729 
13730   //   - There's a scope specifier that does not match any template
13731   //     parameter lists, in which case we use some arbitrary context,
13732   //     create a method or method template, and wait for instantiation.
13733   //   - There's a scope specifier that does match some template
13734   //     parameter lists, which we don't handle right now.
13735   } else {
13736     if (D.isFunctionDefinition()) {
13737       // C++ [class.friend]p6:
13738       //   A function can be defined in a friend declaration of a class if and
13739       //   only if the class is a non-local class (9.8), the function name is
13740       //   unqualified, and the function has namespace scope.
13741       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13742         << SS.getScopeRep();
13743     }
13744 
13745     DC = CurContext;
13746     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13747   }
13748 
13749   if (!DC->isRecord()) {
13750     int DiagArg = -1;
13751     switch (D.getName().getKind()) {
13752     case UnqualifiedId::IK_ConstructorTemplateId:
13753     case UnqualifiedId::IK_ConstructorName:
13754       DiagArg = 0;
13755       break;
13756     case UnqualifiedId::IK_DestructorName:
13757       DiagArg = 1;
13758       break;
13759     case UnqualifiedId::IK_ConversionFunctionId:
13760       DiagArg = 2;
13761       break;
13762     case UnqualifiedId::IK_DeductionGuideName:
13763       DiagArg = 3;
13764       break;
13765     case UnqualifiedId::IK_Identifier:
13766     case UnqualifiedId::IK_ImplicitSelfParam:
13767     case UnqualifiedId::IK_LiteralOperatorId:
13768     case UnqualifiedId::IK_OperatorFunctionId:
13769     case UnqualifiedId::IK_TemplateId:
13770       break;
13771     }
13772     // This implies that it has to be an operator or function.
13773     if (DiagArg >= 0) {
13774       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13775       return nullptr;
13776     }
13777   }
13778 
13779   // FIXME: This is an egregious hack to cope with cases where the scope stack
13780   // does not contain the declaration context, i.e., in an out-of-line
13781   // definition of a class.
13782   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13783   if (!DCScope) {
13784     FakeDCScope.setEntity(DC);
13785     DCScope = &FakeDCScope;
13786   }
13787 
13788   bool AddToScope = true;
13789   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13790                                           TemplateParams, AddToScope);
13791   if (!ND) return nullptr;
13792 
13793   assert(ND->getLexicalDeclContext() == CurContext);
13794 
13795   // If we performed typo correction, we might have added a scope specifier
13796   // and changed the decl context.
13797   DC = ND->getDeclContext();
13798 
13799   // Add the function declaration to the appropriate lookup tables,
13800   // adjusting the redeclarations list as necessary.  We don't
13801   // want to do this yet if the friending class is dependent.
13802   //
13803   // Also update the scope-based lookup if the target context's
13804   // lookup context is in lexical scope.
13805   if (!CurContext->isDependentContext()) {
13806     DC = DC->getRedeclContext();
13807     DC->makeDeclVisibleInContext(ND);
13808     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13809       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13810   }
13811 
13812   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13813                                        D.getIdentifierLoc(), ND,
13814                                        DS.getFriendSpecLoc());
13815   FrD->setAccess(AS_public);
13816   CurContext->addDecl(FrD);
13817 
13818   if (ND->isInvalidDecl()) {
13819     FrD->setInvalidDecl();
13820   } else {
13821     if (DC->isRecord()) CheckFriendAccess(ND);
13822 
13823     FunctionDecl *FD;
13824     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13825       FD = FTD->getTemplatedDecl();
13826     else
13827       FD = cast<FunctionDecl>(ND);
13828 
13829     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13830     // default argument expression, that declaration shall be a definition
13831     // and shall be the only declaration of the function or function
13832     // template in the translation unit.
13833     if (functionDeclHasDefaultArgument(FD)) {
13834       // We can't look at FD->getPreviousDecl() because it may not have been set
13835       // if we're in a dependent context. If the function is known to be a
13836       // redeclaration, we will have narrowed Previous down to the right decl.
13837       if (D.isRedeclaration()) {
13838         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13839         Diag(Previous.getRepresentativeDecl()->getLocation(),
13840              diag::note_previous_declaration);
13841       } else if (!D.isFunctionDefinition())
13842         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13843     }
13844 
13845     // Mark templated-scope function declarations as unsupported.
13846     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13847       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13848         << SS.getScopeRep() << SS.getRange()
13849         << cast<CXXRecordDecl>(CurContext);
13850       FrD->setUnsupportedFriend(true);
13851     }
13852   }
13853 
13854   return ND;
13855 }
13856 
13857 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13858   AdjustDeclIfTemplate(Dcl);
13859 
13860   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13861   if (!Fn) {
13862     Diag(DelLoc, diag::err_deleted_non_function);
13863     return;
13864   }
13865 
13866   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13867     // Don't consider the implicit declaration we generate for explicit
13868     // specializations. FIXME: Do not generate these implicit declarations.
13869     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13870          Prev->getPreviousDecl()) &&
13871         !Prev->isDefined()) {
13872       Diag(DelLoc, diag::err_deleted_decl_not_first);
13873       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13874            Prev->isImplicit() ? diag::note_previous_implicit_declaration
13875                               : diag::note_previous_declaration);
13876     }
13877     // If the declaration wasn't the first, we delete the function anyway for
13878     // recovery.
13879     Fn = Fn->getCanonicalDecl();
13880   }
13881 
13882   // dllimport/dllexport cannot be deleted.
13883   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13884     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13885     Fn->setInvalidDecl();
13886   }
13887 
13888   if (Fn->isDeleted())
13889     return;
13890 
13891   // See if we're deleting a function which is already known to override a
13892   // non-deleted virtual function.
13893   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13894     bool IssuedDiagnostic = false;
13895     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13896                                         E = MD->end_overridden_methods();
13897          I != E; ++I) {
13898       if (!(*MD->begin_overridden_methods())->isDeleted()) {
13899         if (!IssuedDiagnostic) {
13900           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13901           IssuedDiagnostic = true;
13902         }
13903         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13904       }
13905     }
13906     // If this function was implicitly deleted because it was defaulted,
13907     // explain why it was deleted.
13908     if (IssuedDiagnostic && MD->isDefaulted())
13909       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13910                                 /*Diagnose*/true);
13911   }
13912 
13913   // C++11 [basic.start.main]p3:
13914   //   A program that defines main as deleted [...] is ill-formed.
13915   if (Fn->isMain())
13916     Diag(DelLoc, diag::err_deleted_main);
13917 
13918   // C++11 [dcl.fct.def.delete]p4:
13919   //  A deleted function is implicitly inline.
13920   Fn->setImplicitlyInline();
13921   Fn->setDeletedAsWritten();
13922 }
13923 
13924 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13925   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13926 
13927   if (MD) {
13928     if (MD->getParent()->isDependentType()) {
13929       MD->setDefaulted();
13930       MD->setExplicitlyDefaulted();
13931       return;
13932     }
13933 
13934     CXXSpecialMember Member = getSpecialMember(MD);
13935     if (Member == CXXInvalid) {
13936       if (!MD->isInvalidDecl())
13937         Diag(DefaultLoc, diag::err_default_special_members);
13938       return;
13939     }
13940 
13941     MD->setDefaulted();
13942     MD->setExplicitlyDefaulted();
13943 
13944     // If this definition appears within the record, do the checking when
13945     // the record is complete.
13946     const FunctionDecl *Primary = MD;
13947     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13948       // Ask the template instantiation pattern that actually had the
13949       // '= default' on it.
13950       Primary = Pattern;
13951 
13952     // If the method was defaulted on its first declaration, we will have
13953     // already performed the checking in CheckCompletedCXXClass. Such a
13954     // declaration doesn't trigger an implicit definition.
13955     if (Primary->getCanonicalDecl()->isDefaulted())
13956       return;
13957 
13958     CheckExplicitlyDefaultedSpecialMember(MD);
13959 
13960     if (!MD->isInvalidDecl())
13961       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13962   } else {
13963     Diag(DefaultLoc, diag::err_default_special_members);
13964   }
13965 }
13966 
13967 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13968   for (Stmt *SubStmt : S->children()) {
13969     if (!SubStmt)
13970       continue;
13971     if (isa<ReturnStmt>(SubStmt))
13972       Self.Diag(SubStmt->getLocStart(),
13973            diag::err_return_in_constructor_handler);
13974     if (!isa<Expr>(SubStmt))
13975       SearchForReturnInStmt(Self, SubStmt);
13976   }
13977 }
13978 
13979 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
13980   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
13981     CXXCatchStmt *Handler = TryBlock->getHandler(I);
13982     SearchForReturnInStmt(*this, Handler);
13983   }
13984 }
13985 
13986 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
13987                                              const CXXMethodDecl *Old) {
13988   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
13989   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
13990 
13991   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
13992 
13993   // If the calling conventions match, everything is fine
13994   if (NewCC == OldCC)
13995     return false;
13996 
13997   // If the calling conventions mismatch because the new function is static,
13998   // suppress the calling convention mismatch error; the error about static
13999   // function override (err_static_overrides_virtual from
14000   // Sema::CheckFunctionDeclaration) is more clear.
14001   if (New->getStorageClass() == SC_Static)
14002     return false;
14003 
14004   Diag(New->getLocation(),
14005        diag::err_conflicting_overriding_cc_attributes)
14006     << New->getDeclName() << New->getType() << Old->getType();
14007   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14008   return true;
14009 }
14010 
14011 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14012                                              const CXXMethodDecl *Old) {
14013   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14014   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14015 
14016   if (Context.hasSameType(NewTy, OldTy) ||
14017       NewTy->isDependentType() || OldTy->isDependentType())
14018     return false;
14019 
14020   // Check if the return types are covariant
14021   QualType NewClassTy, OldClassTy;
14022 
14023   /// Both types must be pointers or references to classes.
14024   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14025     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14026       NewClassTy = NewPT->getPointeeType();
14027       OldClassTy = OldPT->getPointeeType();
14028     }
14029   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14030     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14031       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14032         NewClassTy = NewRT->getPointeeType();
14033         OldClassTy = OldRT->getPointeeType();
14034       }
14035     }
14036   }
14037 
14038   // The return types aren't either both pointers or references to a class type.
14039   if (NewClassTy.isNull()) {
14040     Diag(New->getLocation(),
14041          diag::err_different_return_type_for_overriding_virtual_function)
14042         << New->getDeclName() << NewTy << OldTy
14043         << New->getReturnTypeSourceRange();
14044     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14045         << Old->getReturnTypeSourceRange();
14046 
14047     return true;
14048   }
14049 
14050   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14051     // C++14 [class.virtual]p8:
14052     //   If the class type in the covariant return type of D::f differs from
14053     //   that of B::f, the class type in the return type of D::f shall be
14054     //   complete at the point of declaration of D::f or shall be the class
14055     //   type D.
14056     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14057       if (!RT->isBeingDefined() &&
14058           RequireCompleteType(New->getLocation(), NewClassTy,
14059                               diag::err_covariant_return_incomplete,
14060                               New->getDeclName()))
14061         return true;
14062     }
14063 
14064     // Check if the new class derives from the old class.
14065     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14066       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14067           << New->getDeclName() << NewTy << OldTy
14068           << New->getReturnTypeSourceRange();
14069       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14070           << Old->getReturnTypeSourceRange();
14071       return true;
14072     }
14073 
14074     // Check if we the conversion from derived to base is valid.
14075     if (CheckDerivedToBaseConversion(
14076             NewClassTy, OldClassTy,
14077             diag::err_covariant_return_inaccessible_base,
14078             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14079             New->getLocation(), New->getReturnTypeSourceRange(),
14080             New->getDeclName(), nullptr)) {
14081       // FIXME: this note won't trigger for delayed access control
14082       // diagnostics, and it's impossible to get an undelayed error
14083       // here from access control during the original parse because
14084       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14085       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14086           << Old->getReturnTypeSourceRange();
14087       return true;
14088     }
14089   }
14090 
14091   // The qualifiers of the return types must be the same.
14092   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14093     Diag(New->getLocation(),
14094          diag::err_covariant_return_type_different_qualifications)
14095         << New->getDeclName() << NewTy << OldTy
14096         << New->getReturnTypeSourceRange();
14097     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14098         << Old->getReturnTypeSourceRange();
14099     return true;
14100   }
14101 
14102 
14103   // The new class type must have the same or less qualifiers as the old type.
14104   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14105     Diag(New->getLocation(),
14106          diag::err_covariant_return_type_class_type_more_qualified)
14107         << New->getDeclName() << NewTy << OldTy
14108         << New->getReturnTypeSourceRange();
14109     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14110         << Old->getReturnTypeSourceRange();
14111     return true;
14112   }
14113 
14114   return false;
14115 }
14116 
14117 /// \brief Mark the given method pure.
14118 ///
14119 /// \param Method the method to be marked pure.
14120 ///
14121 /// \param InitRange the source range that covers the "0" initializer.
14122 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14123   SourceLocation EndLoc = InitRange.getEnd();
14124   if (EndLoc.isValid())
14125     Method->setRangeEnd(EndLoc);
14126 
14127   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14128     Method->setPure();
14129     return false;
14130   }
14131 
14132   if (!Method->isInvalidDecl())
14133     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14134       << Method->getDeclName() << InitRange;
14135   return true;
14136 }
14137 
14138 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14139   if (D->getFriendObjectKind())
14140     Diag(D->getLocation(), diag::err_pure_friend);
14141   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14142     CheckPureMethod(M, ZeroLoc);
14143   else
14144     Diag(D->getLocation(), diag::err_illegal_initializer);
14145 }
14146 
14147 /// \brief Determine whether the given declaration is a static data member.
14148 static bool isStaticDataMember(const Decl *D) {
14149   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14150     return Var->isStaticDataMember();
14151 
14152   return false;
14153 }
14154 
14155 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14156 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
14157 /// is a fresh scope pushed for just this purpose.
14158 ///
14159 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14160 /// static data member of class X, names should be looked up in the scope of
14161 /// class X.
14162 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14163   // If there is no declaration, there was an error parsing it.
14164   if (!D || D->isInvalidDecl())
14165     return;
14166 
14167   // We will always have a nested name specifier here, but this declaration
14168   // might not be out of line if the specifier names the current namespace:
14169   //   extern int n;
14170   //   int ::n = 0;
14171   if (D->isOutOfLine())
14172     EnterDeclaratorContext(S, D->getDeclContext());
14173 
14174   // If we are parsing the initializer for a static data member, push a
14175   // new expression evaluation context that is associated with this static
14176   // data member.
14177   if (isStaticDataMember(D))
14178     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
14179 }
14180 
14181 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14182 /// initializer for the out-of-line declaration 'D'.
14183 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14184   // If there is no declaration, there was an error parsing it.
14185   if (!D || D->isInvalidDecl())
14186     return;
14187 
14188   if (isStaticDataMember(D))
14189     PopExpressionEvaluationContext();
14190 
14191   if (D->isOutOfLine())
14192     ExitDeclaratorContext(S);
14193 }
14194 
14195 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14196 /// C++ if/switch/while/for statement.
14197 /// e.g: "if (int x = f()) {...}"
14198 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14199   // C++ 6.4p2:
14200   // The declarator shall not specify a function or an array.
14201   // The type-specifier-seq shall not contain typedef and shall not declare a
14202   // new class or enumeration.
14203   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14204          "Parser allowed 'typedef' as storage class of condition decl.");
14205 
14206   Decl *Dcl = ActOnDeclarator(S, D);
14207   if (!Dcl)
14208     return true;
14209 
14210   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14211     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14212       << D.getSourceRange();
14213     return true;
14214   }
14215 
14216   return Dcl;
14217 }
14218 
14219 void Sema::LoadExternalVTableUses() {
14220   if (!ExternalSource)
14221     return;
14222 
14223   SmallVector<ExternalVTableUse, 4> VTables;
14224   ExternalSource->ReadUsedVTables(VTables);
14225   SmallVector<VTableUse, 4> NewUses;
14226   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14227     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14228       = VTablesUsed.find(VTables[I].Record);
14229     // Even if a definition wasn't required before, it may be required now.
14230     if (Pos != VTablesUsed.end()) {
14231       if (!Pos->second && VTables[I].DefinitionRequired)
14232         Pos->second = true;
14233       continue;
14234     }
14235 
14236     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14237     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14238   }
14239 
14240   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14241 }
14242 
14243 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14244                           bool DefinitionRequired) {
14245   // Ignore any vtable uses in unevaluated operands or for classes that do
14246   // not have a vtable.
14247   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14248       CurContext->isDependentContext() || isUnevaluatedContext())
14249     return;
14250 
14251   // Try to insert this class into the map.
14252   LoadExternalVTableUses();
14253   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14254   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14255     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14256   if (!Pos.second) {
14257     // If we already had an entry, check to see if we are promoting this vtable
14258     // to require a definition. If so, we need to reappend to the VTableUses
14259     // list, since we may have already processed the first entry.
14260     if (DefinitionRequired && !Pos.first->second) {
14261       Pos.first->second = true;
14262     } else {
14263       // Otherwise, we can early exit.
14264       return;
14265     }
14266   } else {
14267     // The Microsoft ABI requires that we perform the destructor body
14268     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14269     // the deleting destructor is emitted with the vtable, not with the
14270     // destructor definition as in the Itanium ABI.
14271     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14272       CXXDestructorDecl *DD = Class->getDestructor();
14273       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14274         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14275           // If this is an out-of-line declaration, marking it referenced will
14276           // not do anything. Manually call CheckDestructor to look up operator
14277           // delete().
14278           ContextRAII SavedContext(*this, DD);
14279           CheckDestructor(DD);
14280         } else {
14281           MarkFunctionReferenced(Loc, Class->getDestructor());
14282         }
14283       }
14284     }
14285   }
14286 
14287   // Local classes need to have their virtual members marked
14288   // immediately. For all other classes, we mark their virtual members
14289   // at the end of the translation unit.
14290   if (Class->isLocalClass())
14291     MarkVirtualMembersReferenced(Loc, Class);
14292   else
14293     VTableUses.push_back(std::make_pair(Class, Loc));
14294 }
14295 
14296 bool Sema::DefineUsedVTables() {
14297   LoadExternalVTableUses();
14298   if (VTableUses.empty())
14299     return false;
14300 
14301   // Note: The VTableUses vector could grow as a result of marking
14302   // the members of a class as "used", so we check the size each
14303   // time through the loop and prefer indices (which are stable) to
14304   // iterators (which are not).
14305   bool DefinedAnything = false;
14306   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14307     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14308     if (!Class)
14309       continue;
14310     TemplateSpecializationKind ClassTSK =
14311         Class->getTemplateSpecializationKind();
14312 
14313     SourceLocation Loc = VTableUses[I].second;
14314 
14315     bool DefineVTable = true;
14316 
14317     // If this class has a key function, but that key function is
14318     // defined in another translation unit, we don't need to emit the
14319     // vtable even though we're using it.
14320     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14321     if (KeyFunction && !KeyFunction->hasBody()) {
14322       // The key function is in another translation unit.
14323       DefineVTable = false;
14324       TemplateSpecializationKind TSK =
14325           KeyFunction->getTemplateSpecializationKind();
14326       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14327              TSK != TSK_ImplicitInstantiation &&
14328              "Instantiations don't have key functions");
14329       (void)TSK;
14330     } else if (!KeyFunction) {
14331       // If we have a class with no key function that is the subject
14332       // of an explicit instantiation declaration, suppress the
14333       // vtable; it will live with the explicit instantiation
14334       // definition.
14335       bool IsExplicitInstantiationDeclaration =
14336           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14337       for (auto R : Class->redecls()) {
14338         TemplateSpecializationKind TSK
14339           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14340         if (TSK == TSK_ExplicitInstantiationDeclaration)
14341           IsExplicitInstantiationDeclaration = true;
14342         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14343           IsExplicitInstantiationDeclaration = false;
14344           break;
14345         }
14346       }
14347 
14348       if (IsExplicitInstantiationDeclaration)
14349         DefineVTable = false;
14350     }
14351 
14352     // The exception specifications for all virtual members may be needed even
14353     // if we are not providing an authoritative form of the vtable in this TU.
14354     // We may choose to emit it available_externally anyway.
14355     if (!DefineVTable) {
14356       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14357       continue;
14358     }
14359 
14360     // Mark all of the virtual members of this class as referenced, so
14361     // that we can build a vtable. Then, tell the AST consumer that a
14362     // vtable for this class is required.
14363     DefinedAnything = true;
14364     MarkVirtualMembersReferenced(Loc, Class);
14365     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14366     if (VTablesUsed[Canonical])
14367       Consumer.HandleVTable(Class);
14368 
14369     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14370     // no key function or the key function is inlined. Don't warn in C++ ABIs
14371     // that lack key functions, since the user won't be able to make one.
14372     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14373         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14374       const FunctionDecl *KeyFunctionDef = nullptr;
14375       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14376                            KeyFunctionDef->isInlined())) {
14377         Diag(Class->getLocation(),
14378              ClassTSK == TSK_ExplicitInstantiationDefinition
14379                  ? diag::warn_weak_template_vtable
14380                  : diag::warn_weak_vtable)
14381             << Class;
14382       }
14383     }
14384   }
14385   VTableUses.clear();
14386 
14387   return DefinedAnything;
14388 }
14389 
14390 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14391                                                  const CXXRecordDecl *RD) {
14392   for (const auto *I : RD->methods())
14393     if (I->isVirtual() && !I->isPure())
14394       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14395 }
14396 
14397 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14398                                         const CXXRecordDecl *RD) {
14399   // Mark all functions which will appear in RD's vtable as used.
14400   CXXFinalOverriderMap FinalOverriders;
14401   RD->getFinalOverriders(FinalOverriders);
14402   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14403                                             E = FinalOverriders.end();
14404        I != E; ++I) {
14405     for (OverridingMethods::const_iterator OI = I->second.begin(),
14406                                            OE = I->second.end();
14407          OI != OE; ++OI) {
14408       assert(OI->second.size() > 0 && "no final overrider");
14409       CXXMethodDecl *Overrider = OI->second.front().Method;
14410 
14411       // C++ [basic.def.odr]p2:
14412       //   [...] A virtual member function is used if it is not pure. [...]
14413       if (!Overrider->isPure())
14414         MarkFunctionReferenced(Loc, Overrider);
14415     }
14416   }
14417 
14418   // Only classes that have virtual bases need a VTT.
14419   if (RD->getNumVBases() == 0)
14420     return;
14421 
14422   for (const auto &I : RD->bases()) {
14423     const CXXRecordDecl *Base =
14424         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14425     if (Base->getNumVBases() == 0)
14426       continue;
14427     MarkVirtualMembersReferenced(Loc, Base);
14428   }
14429 }
14430 
14431 /// SetIvarInitializers - This routine builds initialization ASTs for the
14432 /// Objective-C implementation whose ivars need be initialized.
14433 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14434   if (!getLangOpts().CPlusPlus)
14435     return;
14436   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14437     SmallVector<ObjCIvarDecl*, 8> ivars;
14438     CollectIvarsToConstructOrDestruct(OID, ivars);
14439     if (ivars.empty())
14440       return;
14441     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14442     for (unsigned i = 0; i < ivars.size(); i++) {
14443       FieldDecl *Field = ivars[i];
14444       if (Field->isInvalidDecl())
14445         continue;
14446 
14447       CXXCtorInitializer *Member;
14448       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14449       InitializationKind InitKind =
14450         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14451 
14452       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14453       ExprResult MemberInit =
14454         InitSeq.Perform(*this, InitEntity, InitKind, None);
14455       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14456       // Note, MemberInit could actually come back empty if no initialization
14457       // is required (e.g., because it would call a trivial default constructor)
14458       if (!MemberInit.get() || MemberInit.isInvalid())
14459         continue;
14460 
14461       Member =
14462         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14463                                          SourceLocation(),
14464                                          MemberInit.getAs<Expr>(),
14465                                          SourceLocation());
14466       AllToInit.push_back(Member);
14467 
14468       // Be sure that the destructor is accessible and is marked as referenced.
14469       if (const RecordType *RecordTy =
14470               Context.getBaseElementType(Field->getType())
14471                   ->getAs<RecordType>()) {
14472         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14473         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14474           MarkFunctionReferenced(Field->getLocation(), Destructor);
14475           CheckDestructorAccess(Field->getLocation(), Destructor,
14476                             PDiag(diag::err_access_dtor_ivar)
14477                               << Context.getBaseElementType(Field->getType()));
14478         }
14479       }
14480     }
14481     ObjCImplementation->setIvarInitializers(Context,
14482                                             AllToInit.data(), AllToInit.size());
14483   }
14484 }
14485 
14486 static
14487 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14488                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14489                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14490                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14491                            Sema &S) {
14492   if (Ctor->isInvalidDecl())
14493     return;
14494 
14495   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14496 
14497   // Target may not be determinable yet, for instance if this is a dependent
14498   // call in an uninstantiated template.
14499   if (Target) {
14500     const FunctionDecl *FNTarget = nullptr;
14501     (void)Target->hasBody(FNTarget);
14502     Target = const_cast<CXXConstructorDecl*>(
14503       cast_or_null<CXXConstructorDecl>(FNTarget));
14504   }
14505 
14506   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14507                      // Avoid dereferencing a null pointer here.
14508                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14509 
14510   if (!Current.insert(Canonical).second)
14511     return;
14512 
14513   // We know that beyond here, we aren't chaining into a cycle.
14514   if (!Target || !Target->isDelegatingConstructor() ||
14515       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14516     Valid.insert(Current.begin(), Current.end());
14517     Current.clear();
14518   // We've hit a cycle.
14519   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14520              Current.count(TCanonical)) {
14521     // If we haven't diagnosed this cycle yet, do so now.
14522     if (!Invalid.count(TCanonical)) {
14523       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14524              diag::warn_delegating_ctor_cycle)
14525         << Ctor;
14526 
14527       // Don't add a note for a function delegating directly to itself.
14528       if (TCanonical != Canonical)
14529         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14530 
14531       CXXConstructorDecl *C = Target;
14532       while (C->getCanonicalDecl() != Canonical) {
14533         const FunctionDecl *FNTarget = nullptr;
14534         (void)C->getTargetConstructor()->hasBody(FNTarget);
14535         assert(FNTarget && "Ctor cycle through bodiless function");
14536 
14537         C = const_cast<CXXConstructorDecl*>(
14538           cast<CXXConstructorDecl>(FNTarget));
14539         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14540       }
14541     }
14542 
14543     Invalid.insert(Current.begin(), Current.end());
14544     Current.clear();
14545   } else {
14546     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14547   }
14548 }
14549 
14550 
14551 void Sema::CheckDelegatingCtorCycles() {
14552   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14553 
14554   for (DelegatingCtorDeclsType::iterator
14555          I = DelegatingCtorDecls.begin(ExternalSource),
14556          E = DelegatingCtorDecls.end();
14557        I != E; ++I)
14558     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14559 
14560   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14561                                                          CE = Invalid.end();
14562        CI != CE; ++CI)
14563     (*CI)->setInvalidDecl();
14564 }
14565 
14566 namespace {
14567   /// \brief AST visitor that finds references to the 'this' expression.
14568   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14569     Sema &S;
14570 
14571   public:
14572     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14573 
14574     bool VisitCXXThisExpr(CXXThisExpr *E) {
14575       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14576         << E->isImplicit();
14577       return false;
14578     }
14579   };
14580 }
14581 
14582 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14583   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14584   if (!TSInfo)
14585     return false;
14586 
14587   TypeLoc TL = TSInfo->getTypeLoc();
14588   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14589   if (!ProtoTL)
14590     return false;
14591 
14592   // C++11 [expr.prim.general]p3:
14593   //   [The expression this] shall not appear before the optional
14594   //   cv-qualifier-seq and it shall not appear within the declaration of a
14595   //   static member function (although its type and value category are defined
14596   //   within a static member function as they are within a non-static member
14597   //   function). [ Note: this is because declaration matching does not occur
14598   //  until the complete declarator is known. - end note ]
14599   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14600   FindCXXThisExpr Finder(*this);
14601 
14602   // If the return type came after the cv-qualifier-seq, check it now.
14603   if (Proto->hasTrailingReturn() &&
14604       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14605     return true;
14606 
14607   // Check the exception specification.
14608   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14609     return true;
14610 
14611   return checkThisInStaticMemberFunctionAttributes(Method);
14612 }
14613 
14614 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14615   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14616   if (!TSInfo)
14617     return false;
14618 
14619   TypeLoc TL = TSInfo->getTypeLoc();
14620   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14621   if (!ProtoTL)
14622     return false;
14623 
14624   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14625   FindCXXThisExpr Finder(*this);
14626 
14627   switch (Proto->getExceptionSpecType()) {
14628   case EST_Unparsed:
14629   case EST_Uninstantiated:
14630   case EST_Unevaluated:
14631   case EST_BasicNoexcept:
14632   case EST_DynamicNone:
14633   case EST_MSAny:
14634   case EST_None:
14635     break;
14636 
14637   case EST_ComputedNoexcept:
14638     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14639       return true;
14640 
14641   case EST_Dynamic:
14642     for (const auto &E : Proto->exceptions()) {
14643       if (!Finder.TraverseType(E))
14644         return true;
14645     }
14646     break;
14647   }
14648 
14649   return false;
14650 }
14651 
14652 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14653   FindCXXThisExpr Finder(*this);
14654 
14655   // Check attributes.
14656   for (const auto *A : Method->attrs()) {
14657     // FIXME: This should be emitted by tblgen.
14658     Expr *Arg = nullptr;
14659     ArrayRef<Expr *> Args;
14660     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14661       Arg = G->getArg();
14662     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14663       Arg = G->getArg();
14664     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14665       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14666     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14667       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14668     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14669       Arg = ETLF->getSuccessValue();
14670       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14671     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14672       Arg = STLF->getSuccessValue();
14673       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14674     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14675       Arg = LR->getArg();
14676     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14677       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14678     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14679       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14680     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14681       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14682     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14683       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14684     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14685       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14686 
14687     if (Arg && !Finder.TraverseStmt(Arg))
14688       return true;
14689 
14690     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14691       if (!Finder.TraverseStmt(Args[I]))
14692         return true;
14693     }
14694   }
14695 
14696   return false;
14697 }
14698 
14699 void Sema::checkExceptionSpecification(
14700     bool IsTopLevel, ExceptionSpecificationType EST,
14701     ArrayRef<ParsedType> DynamicExceptions,
14702     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14703     SmallVectorImpl<QualType> &Exceptions,
14704     FunctionProtoType::ExceptionSpecInfo &ESI) {
14705   Exceptions.clear();
14706   ESI.Type = EST;
14707   if (EST == EST_Dynamic) {
14708     Exceptions.reserve(DynamicExceptions.size());
14709     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14710       // FIXME: Preserve type source info.
14711       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14712 
14713       if (IsTopLevel) {
14714         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14715         collectUnexpandedParameterPacks(ET, Unexpanded);
14716         if (!Unexpanded.empty()) {
14717           DiagnoseUnexpandedParameterPacks(
14718               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14719               Unexpanded);
14720           continue;
14721         }
14722       }
14723 
14724       // Check that the type is valid for an exception spec, and
14725       // drop it if not.
14726       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14727         Exceptions.push_back(ET);
14728     }
14729     ESI.Exceptions = Exceptions;
14730     return;
14731   }
14732 
14733   if (EST == EST_ComputedNoexcept) {
14734     // If an error occurred, there's no expression here.
14735     if (NoexceptExpr) {
14736       assert((NoexceptExpr->isTypeDependent() ||
14737               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14738               Context.BoolTy) &&
14739              "Parser should have made sure that the expression is boolean");
14740       if (IsTopLevel && NoexceptExpr &&
14741           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14742         ESI.Type = EST_BasicNoexcept;
14743         return;
14744       }
14745 
14746       if (!NoexceptExpr->isValueDependent())
14747         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14748                          diag::err_noexcept_needs_constant_expression,
14749                          /*AllowFold*/ false).get();
14750       ESI.NoexceptExpr = NoexceptExpr;
14751     }
14752     return;
14753   }
14754 }
14755 
14756 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14757              ExceptionSpecificationType EST,
14758              SourceRange SpecificationRange,
14759              ArrayRef<ParsedType> DynamicExceptions,
14760              ArrayRef<SourceRange> DynamicExceptionRanges,
14761              Expr *NoexceptExpr) {
14762   if (!MethodD)
14763     return;
14764 
14765   // Dig out the method we're referring to.
14766   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14767     MethodD = FunTmpl->getTemplatedDecl();
14768 
14769   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14770   if (!Method)
14771     return;
14772 
14773   // Check the exception specification.
14774   llvm::SmallVector<QualType, 4> Exceptions;
14775   FunctionProtoType::ExceptionSpecInfo ESI;
14776   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14777                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14778                               ESI);
14779 
14780   // Update the exception specification on the function type.
14781   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14782 
14783   if (Method->isStatic())
14784     checkThisInStaticMemberFunctionExceptionSpec(Method);
14785 
14786   if (Method->isVirtual()) {
14787     // Check overrides, which we previously had to delay.
14788     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14789                                      OEnd = Method->end_overridden_methods();
14790          O != OEnd; ++O)
14791       CheckOverridingFunctionExceptionSpec(Method, *O);
14792   }
14793 }
14794 
14795 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14796 ///
14797 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14798                                        SourceLocation DeclStart,
14799                                        Declarator &D, Expr *BitWidth,
14800                                        InClassInitStyle InitStyle,
14801                                        AccessSpecifier AS,
14802                                        AttributeList *MSPropertyAttr) {
14803   IdentifierInfo *II = D.getIdentifier();
14804   if (!II) {
14805     Diag(DeclStart, diag::err_anonymous_property);
14806     return nullptr;
14807   }
14808   SourceLocation Loc = D.getIdentifierLoc();
14809 
14810   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14811   QualType T = TInfo->getType();
14812   if (getLangOpts().CPlusPlus) {
14813     CheckExtraCXXDefaultArguments(D);
14814 
14815     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14816                                         UPPC_DataMemberType)) {
14817       D.setInvalidType();
14818       T = Context.IntTy;
14819       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14820     }
14821   }
14822 
14823   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14824 
14825   if (D.getDeclSpec().isInlineSpecified())
14826     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14827         << getLangOpts().CPlusPlus1z;
14828   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14829     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14830          diag::err_invalid_thread)
14831       << DeclSpec::getSpecifierName(TSCS);
14832 
14833   // Check to see if this name was declared as a member previously
14834   NamedDecl *PrevDecl = nullptr;
14835   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14836   LookupName(Previous, S);
14837   switch (Previous.getResultKind()) {
14838   case LookupResult::Found:
14839   case LookupResult::FoundUnresolvedValue:
14840     PrevDecl = Previous.getAsSingle<NamedDecl>();
14841     break;
14842 
14843   case LookupResult::FoundOverloaded:
14844     PrevDecl = Previous.getRepresentativeDecl();
14845     break;
14846 
14847   case LookupResult::NotFound:
14848   case LookupResult::NotFoundInCurrentInstantiation:
14849   case LookupResult::Ambiguous:
14850     break;
14851   }
14852 
14853   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14854     // Maybe we will complain about the shadowed template parameter.
14855     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14856     // Just pretend that we didn't see the previous declaration.
14857     PrevDecl = nullptr;
14858   }
14859 
14860   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14861     PrevDecl = nullptr;
14862 
14863   SourceLocation TSSL = D.getLocStart();
14864   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14865   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14866       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14867   ProcessDeclAttributes(TUScope, NewPD, D);
14868   NewPD->setAccess(AS);
14869 
14870   if (NewPD->isInvalidDecl())
14871     Record->setInvalidDecl();
14872 
14873   if (D.getDeclSpec().isModulePrivateSpecified())
14874     NewPD->setModulePrivate();
14875 
14876   if (NewPD->isInvalidDecl() && PrevDecl) {
14877     // Don't introduce NewFD into scope; there's already something
14878     // with the same name in the same scope.
14879   } else if (II) {
14880     PushOnScopeChains(NewPD, S);
14881   } else
14882     Record->addDecl(NewPD);
14883 
14884   return NewPD;
14885 }
14886