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   // FIXME: It's not clear what should happen if multiple declarations of a
651   // deduction guide have different explicitness. For now at least we simply
652   // reject any case where the explicitness changes.
653   if (New->isDeductionGuide() &&
654       New->isExplicitSpecified() != Old->isExplicitSpecified()) {
655     Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
656       << New->isExplicitSpecified();
657     Diag(Old->getLocation(), diag::note_previous_declaration);
658   }
659 
660   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
661   // argument expression, that declaration shall be a definition and shall be
662   // the only declaration of the function or function template in the
663   // translation unit.
664   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
665       functionDeclHasDefaultArgument(Old)) {
666     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
667     Diag(Old->getLocation(), diag::note_previous_declaration);
668     Invalid = true;
669   }
670 
671   return Invalid;
672 }
673 
674 NamedDecl *
675 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
676                                    MultiTemplateParamsArg TemplateParamLists) {
677   assert(D.isDecompositionDeclarator());
678   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
679 
680   // The syntax only allows a decomposition declarator as a simple-declaration
681   // or a for-range-declaration, but we parse it in more cases than that.
682   if (!D.mayHaveDecompositionDeclarator()) {
683     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
684       << Decomp.getSourceRange();
685     return nullptr;
686   }
687 
688   if (!TemplateParamLists.empty()) {
689     // FIXME: There's no rule against this, but there are also no rules that
690     // would actually make it usable, so we reject it for now.
691     Diag(TemplateParamLists.front()->getTemplateLoc(),
692          diag::err_decomp_decl_template);
693     return nullptr;
694   }
695 
696   Diag(Decomp.getLSquareLoc(), getLangOpts().CPlusPlus1z
697                                    ? diag::warn_cxx14_compat_decomp_decl
698                                    : diag::ext_decomp_decl)
699       << Decomp.getSourceRange();
700 
701   // The semantic context is always just the current context.
702   DeclContext *const DC = CurContext;
703 
704   // C++1z [dcl.dcl]/8:
705   //   The decl-specifier-seq shall contain only the type-specifier auto
706   //   and cv-qualifiers.
707   auto &DS = D.getDeclSpec();
708   {
709     SmallVector<StringRef, 8> BadSpecifiers;
710     SmallVector<SourceLocation, 8> BadSpecifierLocs;
711     if (auto SCS = DS.getStorageClassSpec()) {
712       BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
713       BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
714     }
715     if (auto TSCS = DS.getThreadStorageClassSpec()) {
716       BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
717       BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
718     }
719     if (DS.isConstexprSpecified()) {
720       BadSpecifiers.push_back("constexpr");
721       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
722     }
723     if (DS.isInlineSpecified()) {
724       BadSpecifiers.push_back("inline");
725       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
726     }
727     if (!BadSpecifiers.empty()) {
728       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
729       Err << (int)BadSpecifiers.size()
730           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
731       // Don't add FixItHints to remove the specifiers; we do still respect
732       // them when building the underlying variable.
733       for (auto Loc : BadSpecifierLocs)
734         Err << SourceRange(Loc, Loc);
735     }
736     // We can't recover from it being declared as a typedef.
737     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
738       return nullptr;
739   }
740 
741   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
742   QualType R = TInfo->getType();
743 
744   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
745                                       UPPC_DeclarationType))
746     D.setInvalidType();
747 
748   // The syntax only allows a single ref-qualifier prior to the decomposition
749   // declarator. No other declarator chunks are permitted. Also check the type
750   // specifier here.
751   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
752       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
753       (D.getNumTypeObjects() == 1 &&
754        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
755     Diag(Decomp.getLSquareLoc(),
756          (D.hasGroupingParens() ||
757           (D.getNumTypeObjects() &&
758            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
759              ? diag::err_decomp_decl_parens
760              : diag::err_decomp_decl_type)
761         << R;
762 
763     // In most cases, there's no actual problem with an explicitly-specified
764     // type, but a function type won't work here, and ActOnVariableDeclarator
765     // shouldn't be called for such a type.
766     if (R->isFunctionType())
767       D.setInvalidType();
768   }
769 
770   // Build the BindingDecls.
771   SmallVector<BindingDecl*, 8> Bindings;
772 
773   // Build the BindingDecls.
774   for (auto &B : D.getDecompositionDeclarator().bindings()) {
775     // Check for name conflicts.
776     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
777     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
778                           ForRedeclaration);
779     LookupName(Previous, S,
780                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
781 
782     // It's not permitted to shadow a template parameter name.
783     if (Previous.isSingleResult() &&
784         Previous.getFoundDecl()->isTemplateParameter()) {
785       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
786                                       Previous.getFoundDecl());
787       Previous.clear();
788     }
789 
790     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
791                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
792     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
793                          /*AllowInlineNamespace*/false);
794     if (!Previous.empty()) {
795       auto *Old = Previous.getRepresentativeDecl();
796       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
797       Diag(Old->getLocation(), diag::note_previous_definition);
798     }
799 
800     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
801     PushOnScopeChains(BD, S, true);
802     Bindings.push_back(BD);
803     ParsingInitForAutoVars.insert(BD);
804   }
805 
806   // There are no prior lookup results for the variable itself, because it
807   // is unnamed.
808   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
809                                Decomp.getLSquareLoc());
810   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
811 
812   // Build the variable that holds the non-decomposed object.
813   bool AddToScope = true;
814   NamedDecl *New =
815       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
816                               MultiTemplateParamsArg(), AddToScope, Bindings);
817   CurContext->addHiddenDecl(New);
818 
819   if (isInOpenMPDeclareTargetContext())
820     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
821 
822   return New;
823 }
824 
825 static bool checkSimpleDecomposition(
826     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
827     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
828     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
829   if ((int64_t)Bindings.size() != NumElems) {
830     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
831         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
832         << (NumElems < Bindings.size());
833     return true;
834   }
835 
836   unsigned I = 0;
837   for (auto *B : Bindings) {
838     SourceLocation Loc = B->getLocation();
839     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
840     if (E.isInvalid())
841       return true;
842     E = GetInit(Loc, E.get(), I++);
843     if (E.isInvalid())
844       return true;
845     B->setBinding(ElemType, E.get());
846   }
847 
848   return false;
849 }
850 
851 static bool checkArrayLikeDecomposition(Sema &S,
852                                         ArrayRef<BindingDecl *> Bindings,
853                                         ValueDecl *Src, QualType DecompType,
854                                         const llvm::APSInt &NumElems,
855                                         QualType ElemType) {
856   return checkSimpleDecomposition(
857       S, Bindings, Src, DecompType, NumElems, ElemType,
858       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
859         ExprResult E = S.ActOnIntegerConstant(Loc, I);
860         if (E.isInvalid())
861           return ExprError();
862         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
863       });
864 }
865 
866 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
867                                     ValueDecl *Src, QualType DecompType,
868                                     const ConstantArrayType *CAT) {
869   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
870                                      llvm::APSInt(CAT->getSize()),
871                                      CAT->getElementType());
872 }
873 
874 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
875                                      ValueDecl *Src, QualType DecompType,
876                                      const VectorType *VT) {
877   return checkArrayLikeDecomposition(
878       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
879       S.Context.getQualifiedType(VT->getElementType(),
880                                  DecompType.getQualifiers()));
881 }
882 
883 static bool checkComplexDecomposition(Sema &S,
884                                       ArrayRef<BindingDecl *> Bindings,
885                                       ValueDecl *Src, QualType DecompType,
886                                       const ComplexType *CT) {
887   return checkSimpleDecomposition(
888       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
889       S.Context.getQualifiedType(CT->getElementType(),
890                                  DecompType.getQualifiers()),
891       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
892         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
893       });
894 }
895 
896 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
897                                      TemplateArgumentListInfo &Args) {
898   SmallString<128> SS;
899   llvm::raw_svector_ostream OS(SS);
900   bool First = true;
901   for (auto &Arg : Args.arguments()) {
902     if (!First)
903       OS << ", ";
904     Arg.getArgument().print(PrintingPolicy, OS);
905     First = false;
906   }
907   return OS.str();
908 }
909 
910 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
911                                      SourceLocation Loc, StringRef Trait,
912                                      TemplateArgumentListInfo &Args,
913                                      unsigned DiagID) {
914   auto DiagnoseMissing = [&] {
915     if (DiagID)
916       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
917                                                Args);
918     return true;
919   };
920 
921   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
922   NamespaceDecl *Std = S.getStdNamespace();
923   if (!Std)
924     return DiagnoseMissing();
925 
926   // Look up the trait itself, within namespace std. We can diagnose various
927   // problems with this lookup even if we've been asked to not diagnose a
928   // missing specialization, because this can only fail if the user has been
929   // declaring their own names in namespace std or we don't support the
930   // standard library implementation in use.
931   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
932                       Loc, Sema::LookupOrdinaryName);
933   if (!S.LookupQualifiedName(Result, Std))
934     return DiagnoseMissing();
935   if (Result.isAmbiguous())
936     return true;
937 
938   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
939   if (!TraitTD) {
940     Result.suppressDiagnostics();
941     NamedDecl *Found = *Result.begin();
942     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
943     S.Diag(Found->getLocation(), diag::note_declared_at);
944     return true;
945   }
946 
947   // Build the template-id.
948   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
949   if (TraitTy.isNull())
950     return true;
951   if (!S.isCompleteType(Loc, TraitTy)) {
952     if (DiagID)
953       S.RequireCompleteType(
954           Loc, TraitTy, DiagID,
955           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
956     return true;
957   }
958 
959   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
960   assert(RD && "specialization of class template is not a class?");
961 
962   // Look up the member of the trait type.
963   S.LookupQualifiedName(TraitMemberLookup, RD);
964   return TraitMemberLookup.isAmbiguous();
965 }
966 
967 static TemplateArgumentLoc
968 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
969                                    uint64_t I) {
970   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
971   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
972 }
973 
974 static TemplateArgumentLoc
975 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
976   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
977 }
978 
979 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
980 
981 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
982                                llvm::APSInt &Size) {
983   EnterExpressionEvaluationContext ContextRAII(S, Sema::ConstantEvaluated);
984 
985   DeclarationName Value = S.PP.getIdentifierInfo("value");
986   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
987 
988   // Form template argument list for tuple_size<T>.
989   TemplateArgumentListInfo Args(Loc, Loc);
990   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
991 
992   // If there's no tuple_size specialization, it's not tuple-like.
993   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
994     return IsTupleLike::NotTupleLike;
995 
996   // If we get this far, we've committed to the tuple interpretation, but
997   // we can still fail if there actually isn't a usable ::value.
998 
999   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1000     LookupResult &R;
1001     TemplateArgumentListInfo &Args;
1002     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1003         : R(R), Args(Args) {}
1004     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1005       S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1006           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1007     }
1008   } Diagnoser(R, Args);
1009 
1010   if (R.empty()) {
1011     Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1012     return IsTupleLike::Error;
1013   }
1014 
1015   ExprResult E =
1016       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1017   if (E.isInvalid())
1018     return IsTupleLike::Error;
1019 
1020   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1021   if (E.isInvalid())
1022     return IsTupleLike::Error;
1023 
1024   return IsTupleLike::TupleLike;
1025 }
1026 
1027 /// \return std::tuple_element<I, T>::type.
1028 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1029                                         unsigned I, QualType T) {
1030   // Form template argument list for tuple_element<I, T>.
1031   TemplateArgumentListInfo Args(Loc, Loc);
1032   Args.addArgument(
1033       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1034   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1035 
1036   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1037   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1038   if (lookupStdTypeTraitMember(
1039           S, R, Loc, "tuple_element", Args,
1040           diag::err_decomp_decl_std_tuple_element_not_specialized))
1041     return QualType();
1042 
1043   auto *TD = R.getAsSingle<TypeDecl>();
1044   if (!TD) {
1045     R.suppressDiagnostics();
1046     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1047       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1048     if (!R.empty())
1049       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1050     return QualType();
1051   }
1052 
1053   return S.Context.getTypeDeclType(TD);
1054 }
1055 
1056 namespace {
1057 struct BindingDiagnosticTrap {
1058   Sema &S;
1059   DiagnosticErrorTrap Trap;
1060   BindingDecl *BD;
1061 
1062   BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1063       : S(S), Trap(S.Diags), BD(BD) {}
1064   ~BindingDiagnosticTrap() {
1065     if (Trap.hasErrorOccurred())
1066       S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1067   }
1068 };
1069 }
1070 
1071 static bool checkTupleLikeDecomposition(Sema &S,
1072                                         ArrayRef<BindingDecl *> Bindings,
1073                                         VarDecl *Src, QualType DecompType,
1074                                         const llvm::APSInt &TupleSize) {
1075   if ((int64_t)Bindings.size() != TupleSize) {
1076     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1077         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1078         << (TupleSize < Bindings.size());
1079     return true;
1080   }
1081 
1082   if (Bindings.empty())
1083     return false;
1084 
1085   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1086 
1087   // [dcl.decomp]p3:
1088   //   The unqualified-id get is looked up in the scope of E by class member
1089   //   access lookup
1090   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1091   bool UseMemberGet = false;
1092   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1093     if (auto *RD = DecompType->getAsCXXRecordDecl())
1094       S.LookupQualifiedName(MemberGet, RD);
1095     if (MemberGet.isAmbiguous())
1096       return true;
1097     UseMemberGet = !MemberGet.empty();
1098     S.FilterAcceptableTemplateNames(MemberGet);
1099   }
1100 
1101   unsigned I = 0;
1102   for (auto *B : Bindings) {
1103     BindingDiagnosticTrap Trap(S, B);
1104     SourceLocation Loc = B->getLocation();
1105 
1106     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1107     if (E.isInvalid())
1108       return true;
1109 
1110     //   e is an lvalue if the type of the entity is an lvalue reference and
1111     //   an xvalue otherwise
1112     if (!Src->getType()->isLValueReferenceType())
1113       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1114                                    E.get(), nullptr, VK_XValue);
1115 
1116     TemplateArgumentListInfo Args(Loc, Loc);
1117     Args.addArgument(
1118         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1119 
1120     if (UseMemberGet) {
1121       //   if [lookup of member get] finds at least one declaration, the
1122       //   initializer is e.get<i-1>().
1123       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1124                                      CXXScopeSpec(), SourceLocation(), nullptr,
1125                                      MemberGet, &Args, nullptr);
1126       if (E.isInvalid())
1127         return true;
1128 
1129       E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1130     } else {
1131       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1132       //   in the associated namespaces.
1133       Expr *Get = UnresolvedLookupExpr::Create(
1134           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1135           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1136           UnresolvedSetIterator(), UnresolvedSetIterator());
1137 
1138       Expr *Arg = E.get();
1139       E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1140     }
1141     if (E.isInvalid())
1142       return true;
1143     Expr *Init = E.get();
1144 
1145     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1146     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1147     if (T.isNull())
1148       return true;
1149 
1150     //   each vi is a variable of type "reference to T" initialized with the
1151     //   initializer, where the reference is an lvalue reference if the
1152     //   initializer is an lvalue and an rvalue reference otherwise
1153     QualType RefType =
1154         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1155     if (RefType.isNull())
1156       return true;
1157     auto *RefVD = VarDecl::Create(
1158         S.Context, Src->getDeclContext(), Loc, Loc,
1159         B->getDeclName().getAsIdentifierInfo(), RefType,
1160         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1161     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1162     RefVD->setTSCSpec(Src->getTSCSpec());
1163     RefVD->setImplicit();
1164     if (Src->isInlineSpecified())
1165       RefVD->setInlineSpecified();
1166     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1167 
1168     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1169     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1170     InitializationSequence Seq(S, Entity, Kind, Init);
1171     E = Seq.Perform(S, Entity, Kind, Init);
1172     if (E.isInvalid())
1173       return true;
1174     E = S.ActOnFinishFullExpr(E.get(), Loc);
1175     if (E.isInvalid())
1176       return true;
1177     RefVD->setInit(E.get());
1178     RefVD->checkInitIsICE();
1179 
1180     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1181                                    DeclarationNameInfo(B->getDeclName(), Loc),
1182                                    RefVD);
1183     if (E.isInvalid())
1184       return true;
1185 
1186     B->setBinding(T, E.get());
1187     I++;
1188   }
1189 
1190   return false;
1191 }
1192 
1193 /// Find the base class to decompose in a built-in decomposition of a class type.
1194 /// This base class search is, unfortunately, not quite like any other that we
1195 /// perform anywhere else in C++.
1196 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1197                                                       SourceLocation Loc,
1198                                                       const CXXRecordDecl *RD,
1199                                                       CXXCastPath &BasePath) {
1200   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1201                           CXXBasePath &Path) {
1202     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1203   };
1204 
1205   const CXXRecordDecl *ClassWithFields = nullptr;
1206   if (RD->hasDirectFields())
1207     // [dcl.decomp]p4:
1208     //   Otherwise, all of E's non-static data members shall be public direct
1209     //   members of E ...
1210     ClassWithFields = RD;
1211   else {
1212     //   ... or of ...
1213     CXXBasePaths Paths;
1214     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1215     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1216       // If no classes have fields, just decompose RD itself. (This will work
1217       // if and only if zero bindings were provided.)
1218       return RD;
1219     }
1220 
1221     CXXBasePath *BestPath = nullptr;
1222     for (auto &P : Paths) {
1223       if (!BestPath)
1224         BestPath = &P;
1225       else if (!S.Context.hasSameType(P.back().Base->getType(),
1226                                       BestPath->back().Base->getType())) {
1227         //   ... the same ...
1228         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1229           << false << RD << BestPath->back().Base->getType()
1230           << P.back().Base->getType();
1231         return nullptr;
1232       } else if (P.Access < BestPath->Access) {
1233         BestPath = &P;
1234       }
1235     }
1236 
1237     //   ... unambiguous ...
1238     QualType BaseType = BestPath->back().Base->getType();
1239     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1240       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1241         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1242       return nullptr;
1243     }
1244 
1245     //   ... public base class of E.
1246     if (BestPath->Access != AS_public) {
1247       S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1248         << RD << BaseType;
1249       for (auto &BS : *BestPath) {
1250         if (BS.Base->getAccessSpecifier() != AS_public) {
1251           S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1252             << (BS.Base->getAccessSpecifier() == AS_protected)
1253             << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1254           break;
1255         }
1256       }
1257       return nullptr;
1258     }
1259 
1260     ClassWithFields = BaseType->getAsCXXRecordDecl();
1261     S.BuildBasePathArray(Paths, BasePath);
1262   }
1263 
1264   // The above search did not check whether the selected class itself has base
1265   // classes with fields, so check that now.
1266   CXXBasePaths Paths;
1267   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1268     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1269       << (ClassWithFields == RD) << RD << ClassWithFields
1270       << Paths.front().back().Base->getType();
1271     return nullptr;
1272   }
1273 
1274   return ClassWithFields;
1275 }
1276 
1277 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1278                                      ValueDecl *Src, QualType DecompType,
1279                                      const CXXRecordDecl *RD) {
1280   CXXCastPath BasePath;
1281   RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1282   if (!RD)
1283     return true;
1284   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1285                                                  DecompType.getQualifiers());
1286 
1287   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1288     unsigned NumFields =
1289         std::count_if(RD->field_begin(), RD->field_end(),
1290                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1291     assert(Bindings.size() != NumFields);
1292     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1293         << DecompType << (unsigned)Bindings.size() << NumFields
1294         << (NumFields < Bindings.size());
1295     return true;
1296   };
1297 
1298   //   all of E's non-static data members shall be public [...] members,
1299   //   E shall not have an anonymous union member, ...
1300   unsigned I = 0;
1301   for (auto *FD : RD->fields()) {
1302     if (FD->isUnnamedBitfield())
1303       continue;
1304 
1305     if (FD->isAnonymousStructOrUnion()) {
1306       S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1307         << DecompType << FD->getType()->isUnionType();
1308       S.Diag(FD->getLocation(), diag::note_declared_at);
1309       return true;
1310     }
1311 
1312     // We have a real field to bind.
1313     if (I >= Bindings.size())
1314       return DiagnoseBadNumberOfBindings();
1315     auto *B = Bindings[I++];
1316 
1317     SourceLocation Loc = B->getLocation();
1318     if (FD->getAccess() != AS_public) {
1319       S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1320 
1321       // Determine whether the access specifier was explicit.
1322       bool Implicit = true;
1323       for (const auto *D : RD->decls()) {
1324         if (declaresSameEntity(D, FD))
1325           break;
1326         if (isa<AccessSpecDecl>(D)) {
1327           Implicit = false;
1328           break;
1329         }
1330       }
1331 
1332       S.Diag(FD->getLocation(), diag::note_access_natural)
1333         << (FD->getAccess() == AS_protected) << Implicit;
1334       return true;
1335     }
1336 
1337     // Initialize the binding to Src.FD.
1338     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1339     if (E.isInvalid())
1340       return true;
1341     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1342                             VK_LValue, &BasePath);
1343     if (E.isInvalid())
1344       return true;
1345     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1346                                   CXXScopeSpec(), FD,
1347                                   DeclAccessPair::make(FD, FD->getAccess()),
1348                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1349     if (E.isInvalid())
1350       return true;
1351 
1352     // If the type of the member is T, the referenced type is cv T, where cv is
1353     // the cv-qualification of the decomposition expression.
1354     //
1355     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1356     // 'const' to the type of the field.
1357     Qualifiers Q = DecompType.getQualifiers();
1358     if (FD->isMutable())
1359       Q.removeConst();
1360     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1361   }
1362 
1363   if (I != Bindings.size())
1364     return DiagnoseBadNumberOfBindings();
1365 
1366   return false;
1367 }
1368 
1369 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1370   QualType DecompType = DD->getType();
1371 
1372   // If the type of the decomposition is dependent, then so is the type of
1373   // each binding.
1374   if (DecompType->isDependentType()) {
1375     for (auto *B : DD->bindings())
1376       B->setType(Context.DependentTy);
1377     return;
1378   }
1379 
1380   DecompType = DecompType.getNonReferenceType();
1381   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1382 
1383   // C++1z [dcl.decomp]/2:
1384   //   If E is an array type [...]
1385   // As an extension, we also support decomposition of built-in complex and
1386   // vector types.
1387   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1388     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1389       DD->setInvalidDecl();
1390     return;
1391   }
1392   if (auto *VT = DecompType->getAs<VectorType>()) {
1393     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1394       DD->setInvalidDecl();
1395     return;
1396   }
1397   if (auto *CT = DecompType->getAs<ComplexType>()) {
1398     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1399       DD->setInvalidDecl();
1400     return;
1401   }
1402 
1403   // C++1z [dcl.decomp]/3:
1404   //   if the expression std::tuple_size<E>::value is a well-formed integral
1405   //   constant expression, [...]
1406   llvm::APSInt TupleSize(32);
1407   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1408   case IsTupleLike::Error:
1409     DD->setInvalidDecl();
1410     return;
1411 
1412   case IsTupleLike::TupleLike:
1413     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1414       DD->setInvalidDecl();
1415     return;
1416 
1417   case IsTupleLike::NotTupleLike:
1418     break;
1419   }
1420 
1421   // C++1z [dcl.dcl]/8:
1422   //   [E shall be of array or non-union class type]
1423   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1424   if (!RD || RD->isUnion()) {
1425     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1426         << DD << !RD << DecompType;
1427     DD->setInvalidDecl();
1428     return;
1429   }
1430 
1431   // C++1z [dcl.decomp]/4:
1432   //   all of E's non-static data members shall be [...] direct members of
1433   //   E or of the same unambiguous public base class of E, ...
1434   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1435     DD->setInvalidDecl();
1436 }
1437 
1438 /// \brief Merge the exception specifications of two variable declarations.
1439 ///
1440 /// This is called when there's a redeclaration of a VarDecl. The function
1441 /// checks if the redeclaration might have an exception specification and
1442 /// validates compatibility and merges the specs if necessary.
1443 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1444   // Shortcut if exceptions are disabled.
1445   if (!getLangOpts().CXXExceptions)
1446     return;
1447 
1448   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1449          "Should only be called if types are otherwise the same.");
1450 
1451   QualType NewType = New->getType();
1452   QualType OldType = Old->getType();
1453 
1454   // We're only interested in pointers and references to functions, as well
1455   // as pointers to member functions.
1456   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1457     NewType = R->getPointeeType();
1458     OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1459   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1460     NewType = P->getPointeeType();
1461     OldType = OldType->getAs<PointerType>()->getPointeeType();
1462   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1463     NewType = M->getPointeeType();
1464     OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1465   }
1466 
1467   if (!NewType->isFunctionProtoType())
1468     return;
1469 
1470   // There's lots of special cases for functions. For function pointers, system
1471   // libraries are hopefully not as broken so that we don't need these
1472   // workarounds.
1473   if (CheckEquivalentExceptionSpec(
1474         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1475         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1476     New->setInvalidDecl();
1477   }
1478 }
1479 
1480 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1481 /// function declaration are well-formed according to C++
1482 /// [dcl.fct.default].
1483 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1484   unsigned NumParams = FD->getNumParams();
1485   unsigned p;
1486 
1487   // Find first parameter with a default argument
1488   for (p = 0; p < NumParams; ++p) {
1489     ParmVarDecl *Param = FD->getParamDecl(p);
1490     if (Param->hasDefaultArg())
1491       break;
1492   }
1493 
1494   // C++11 [dcl.fct.default]p4:
1495   //   In a given function declaration, each parameter subsequent to a parameter
1496   //   with a default argument shall have a default argument supplied in this or
1497   //   a previous declaration or shall be a function parameter pack. A default
1498   //   argument shall not be redefined by a later declaration (not even to the
1499   //   same value).
1500   unsigned LastMissingDefaultArg = 0;
1501   for (; p < NumParams; ++p) {
1502     ParmVarDecl *Param = FD->getParamDecl(p);
1503     if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1504       if (Param->isInvalidDecl())
1505         /* We already complained about this parameter. */;
1506       else if (Param->getIdentifier())
1507         Diag(Param->getLocation(),
1508              diag::err_param_default_argument_missing_name)
1509           << Param->getIdentifier();
1510       else
1511         Diag(Param->getLocation(),
1512              diag::err_param_default_argument_missing);
1513 
1514       LastMissingDefaultArg = p;
1515     }
1516   }
1517 
1518   if (LastMissingDefaultArg > 0) {
1519     // Some default arguments were missing. Clear out all of the
1520     // default arguments up to (and including) the last missing
1521     // default argument, so that we leave the function parameters
1522     // in a semantically valid state.
1523     for (p = 0; p <= LastMissingDefaultArg; ++p) {
1524       ParmVarDecl *Param = FD->getParamDecl(p);
1525       if (Param->hasDefaultArg()) {
1526         Param->setDefaultArg(nullptr);
1527       }
1528     }
1529   }
1530 }
1531 
1532 // CheckConstexprParameterTypes - Check whether a function's parameter types
1533 // are all literal types. If so, return true. If not, produce a suitable
1534 // diagnostic and return false.
1535 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1536                                          const FunctionDecl *FD) {
1537   unsigned ArgIndex = 0;
1538   const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1539   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1540                                               e = FT->param_type_end();
1541        i != e; ++i, ++ArgIndex) {
1542     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1543     SourceLocation ParamLoc = PD->getLocation();
1544     if (!(*i)->isDependentType() &&
1545         SemaRef.RequireLiteralType(ParamLoc, *i,
1546                                    diag::err_constexpr_non_literal_param,
1547                                    ArgIndex+1, PD->getSourceRange(),
1548                                    isa<CXXConstructorDecl>(FD)))
1549       return false;
1550   }
1551   return true;
1552 }
1553 
1554 /// \brief Get diagnostic %select index for tag kind for
1555 /// record diagnostic message.
1556 /// WARNING: Indexes apply to particular diagnostics only!
1557 ///
1558 /// \returns diagnostic %select index.
1559 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1560   switch (Tag) {
1561   case TTK_Struct: return 0;
1562   case TTK_Interface: return 1;
1563   case TTK_Class:  return 2;
1564   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1565   }
1566 }
1567 
1568 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1569 // the requirements of a constexpr function definition or a constexpr
1570 // constructor definition. If so, return true. If not, produce appropriate
1571 // diagnostics and return false.
1572 //
1573 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1574 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1575   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1576   if (MD && MD->isInstance()) {
1577     // C++11 [dcl.constexpr]p4:
1578     //  The definition of a constexpr constructor shall satisfy the following
1579     //  constraints:
1580     //  - the class shall not have any virtual base classes;
1581     const CXXRecordDecl *RD = MD->getParent();
1582     if (RD->getNumVBases()) {
1583       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1584         << isa<CXXConstructorDecl>(NewFD)
1585         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1586       for (const auto &I : RD->vbases())
1587         Diag(I.getLocStart(),
1588              diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1589       return false;
1590     }
1591   }
1592 
1593   if (!isa<CXXConstructorDecl>(NewFD)) {
1594     // C++11 [dcl.constexpr]p3:
1595     //  The definition of a constexpr function shall satisfy the following
1596     //  constraints:
1597     // - it shall not be virtual;
1598     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1599     if (Method && Method->isVirtual()) {
1600       Method = Method->getCanonicalDecl();
1601       Diag(Method->getLocation(), diag::err_constexpr_virtual);
1602 
1603       // If it's not obvious why this function is virtual, find an overridden
1604       // function which uses the 'virtual' keyword.
1605       const CXXMethodDecl *WrittenVirtual = Method;
1606       while (!WrittenVirtual->isVirtualAsWritten())
1607         WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1608       if (WrittenVirtual != Method)
1609         Diag(WrittenVirtual->getLocation(),
1610              diag::note_overridden_virtual_function);
1611       return false;
1612     }
1613 
1614     // - its return type shall be a literal type;
1615     QualType RT = NewFD->getReturnType();
1616     if (!RT->isDependentType() &&
1617         RequireLiteralType(NewFD->getLocation(), RT,
1618                            diag::err_constexpr_non_literal_return))
1619       return false;
1620   }
1621 
1622   // - each of its parameter types shall be a literal type;
1623   if (!CheckConstexprParameterTypes(*this, NewFD))
1624     return false;
1625 
1626   return true;
1627 }
1628 
1629 /// Check the given declaration statement is legal within a constexpr function
1630 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1631 ///
1632 /// \return true if the body is OK (maybe only as an extension), false if we
1633 ///         have diagnosed a problem.
1634 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1635                                    DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1636   // C++11 [dcl.constexpr]p3 and p4:
1637   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1638   //  contain only
1639   for (const auto *DclIt : DS->decls()) {
1640     switch (DclIt->getKind()) {
1641     case Decl::StaticAssert:
1642     case Decl::Using:
1643     case Decl::UsingShadow:
1644     case Decl::UsingDirective:
1645     case Decl::UnresolvedUsingTypename:
1646     case Decl::UnresolvedUsingValue:
1647       //   - static_assert-declarations
1648       //   - using-declarations,
1649       //   - using-directives,
1650       continue;
1651 
1652     case Decl::Typedef:
1653     case Decl::TypeAlias: {
1654       //   - typedef declarations and alias-declarations that do not define
1655       //     classes or enumerations,
1656       const auto *TN = cast<TypedefNameDecl>(DclIt);
1657       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1658         // Don't allow variably-modified types in constexpr functions.
1659         TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1660         SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1661           << TL.getSourceRange() << TL.getType()
1662           << isa<CXXConstructorDecl>(Dcl);
1663         return false;
1664       }
1665       continue;
1666     }
1667 
1668     case Decl::Enum:
1669     case Decl::CXXRecord:
1670       // C++1y allows types to be defined, not just declared.
1671       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1672         SemaRef.Diag(DS->getLocStart(),
1673                      SemaRef.getLangOpts().CPlusPlus14
1674                        ? diag::warn_cxx11_compat_constexpr_type_definition
1675                        : diag::ext_constexpr_type_definition)
1676           << isa<CXXConstructorDecl>(Dcl);
1677       continue;
1678 
1679     case Decl::EnumConstant:
1680     case Decl::IndirectField:
1681     case Decl::ParmVar:
1682       // These can only appear with other declarations which are banned in
1683       // C++11 and permitted in C++1y, so ignore them.
1684       continue;
1685 
1686     case Decl::Var:
1687     case Decl::Decomposition: {
1688       // C++1y [dcl.constexpr]p3 allows anything except:
1689       //   a definition of a variable of non-literal type or of static or
1690       //   thread storage duration or for which no initialization is performed.
1691       const auto *VD = cast<VarDecl>(DclIt);
1692       if (VD->isThisDeclarationADefinition()) {
1693         if (VD->isStaticLocal()) {
1694           SemaRef.Diag(VD->getLocation(),
1695                        diag::err_constexpr_local_var_static)
1696             << isa<CXXConstructorDecl>(Dcl)
1697             << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1698           return false;
1699         }
1700         if (!VD->getType()->isDependentType() &&
1701             SemaRef.RequireLiteralType(
1702               VD->getLocation(), VD->getType(),
1703               diag::err_constexpr_local_var_non_literal_type,
1704               isa<CXXConstructorDecl>(Dcl)))
1705           return false;
1706         if (!VD->getType()->isDependentType() &&
1707             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1708           SemaRef.Diag(VD->getLocation(),
1709                        diag::err_constexpr_local_var_no_init)
1710             << isa<CXXConstructorDecl>(Dcl);
1711           return false;
1712         }
1713       }
1714       SemaRef.Diag(VD->getLocation(),
1715                    SemaRef.getLangOpts().CPlusPlus14
1716                     ? diag::warn_cxx11_compat_constexpr_local_var
1717                     : diag::ext_constexpr_local_var)
1718         << isa<CXXConstructorDecl>(Dcl);
1719       continue;
1720     }
1721 
1722     case Decl::NamespaceAlias:
1723     case Decl::Function:
1724       // These are disallowed in C++11 and permitted in C++1y. Allow them
1725       // everywhere as an extension.
1726       if (!Cxx1yLoc.isValid())
1727         Cxx1yLoc = DS->getLocStart();
1728       continue;
1729 
1730     default:
1731       SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1732         << isa<CXXConstructorDecl>(Dcl);
1733       return false;
1734     }
1735   }
1736 
1737   return true;
1738 }
1739 
1740 /// Check that the given field is initialized within a constexpr constructor.
1741 ///
1742 /// \param Dcl The constexpr constructor being checked.
1743 /// \param Field The field being checked. This may be a member of an anonymous
1744 ///        struct or union nested within the class being checked.
1745 /// \param Inits All declarations, including anonymous struct/union members and
1746 ///        indirect members, for which any initialization was provided.
1747 /// \param Diagnosed Set to true if an error is produced.
1748 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1749                                           const FunctionDecl *Dcl,
1750                                           FieldDecl *Field,
1751                                           llvm::SmallSet<Decl*, 16> &Inits,
1752                                           bool &Diagnosed) {
1753   if (Field->isInvalidDecl())
1754     return;
1755 
1756   if (Field->isUnnamedBitfield())
1757     return;
1758 
1759   // Anonymous unions with no variant members and empty anonymous structs do not
1760   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1761   // indirect fields don't need initializing.
1762   if (Field->isAnonymousStructOrUnion() &&
1763       (Field->getType()->isUnionType()
1764            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1765            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1766     return;
1767 
1768   if (!Inits.count(Field)) {
1769     if (!Diagnosed) {
1770       SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1771       Diagnosed = true;
1772     }
1773     SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1774   } else if (Field->isAnonymousStructOrUnion()) {
1775     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1776     for (auto *I : RD->fields())
1777       // If an anonymous union contains an anonymous struct of which any member
1778       // is initialized, all members must be initialized.
1779       if (!RD->isUnion() || Inits.count(I))
1780         CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1781   }
1782 }
1783 
1784 /// Check the provided statement is allowed in a constexpr function
1785 /// definition.
1786 static bool
1787 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1788                            SmallVectorImpl<SourceLocation> &ReturnStmts,
1789                            SourceLocation &Cxx1yLoc) {
1790   // - its function-body shall be [...] a compound-statement that contains only
1791   switch (S->getStmtClass()) {
1792   case Stmt::NullStmtClass:
1793     //   - null statements,
1794     return true;
1795 
1796   case Stmt::DeclStmtClass:
1797     //   - static_assert-declarations
1798     //   - using-declarations,
1799     //   - using-directives,
1800     //   - typedef declarations and alias-declarations that do not define
1801     //     classes or enumerations,
1802     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1803       return false;
1804     return true;
1805 
1806   case Stmt::ReturnStmtClass:
1807     //   - and exactly one return statement;
1808     if (isa<CXXConstructorDecl>(Dcl)) {
1809       // C++1y allows return statements in constexpr constructors.
1810       if (!Cxx1yLoc.isValid())
1811         Cxx1yLoc = S->getLocStart();
1812       return true;
1813     }
1814 
1815     ReturnStmts.push_back(S->getLocStart());
1816     return true;
1817 
1818   case Stmt::CompoundStmtClass: {
1819     // C++1y allows compound-statements.
1820     if (!Cxx1yLoc.isValid())
1821       Cxx1yLoc = S->getLocStart();
1822 
1823     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1824     for (auto *BodyIt : CompStmt->body()) {
1825       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1826                                       Cxx1yLoc))
1827         return false;
1828     }
1829     return true;
1830   }
1831 
1832   case Stmt::AttributedStmtClass:
1833     if (!Cxx1yLoc.isValid())
1834       Cxx1yLoc = S->getLocStart();
1835     return true;
1836 
1837   case Stmt::IfStmtClass: {
1838     // C++1y allows if-statements.
1839     if (!Cxx1yLoc.isValid())
1840       Cxx1yLoc = S->getLocStart();
1841 
1842     IfStmt *If = cast<IfStmt>(S);
1843     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1844                                     Cxx1yLoc))
1845       return false;
1846     if (If->getElse() &&
1847         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1848                                     Cxx1yLoc))
1849       return false;
1850     return true;
1851   }
1852 
1853   case Stmt::WhileStmtClass:
1854   case Stmt::DoStmtClass:
1855   case Stmt::ForStmtClass:
1856   case Stmt::CXXForRangeStmtClass:
1857   case Stmt::ContinueStmtClass:
1858     // C++1y allows all of these. We don't allow them as extensions in C++11,
1859     // because they don't make sense without variable mutation.
1860     if (!SemaRef.getLangOpts().CPlusPlus14)
1861       break;
1862     if (!Cxx1yLoc.isValid())
1863       Cxx1yLoc = S->getLocStart();
1864     for (Stmt *SubStmt : S->children())
1865       if (SubStmt &&
1866           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1867                                       Cxx1yLoc))
1868         return false;
1869     return true;
1870 
1871   case Stmt::SwitchStmtClass:
1872   case Stmt::CaseStmtClass:
1873   case Stmt::DefaultStmtClass:
1874   case Stmt::BreakStmtClass:
1875     // C++1y allows switch-statements, and since they don't need variable
1876     // mutation, we can reasonably allow them in C++11 as an extension.
1877     if (!Cxx1yLoc.isValid())
1878       Cxx1yLoc = S->getLocStart();
1879     for (Stmt *SubStmt : S->children())
1880       if (SubStmt &&
1881           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1882                                       Cxx1yLoc))
1883         return false;
1884     return true;
1885 
1886   default:
1887     if (!isa<Expr>(S))
1888       break;
1889 
1890     // C++1y allows expression-statements.
1891     if (!Cxx1yLoc.isValid())
1892       Cxx1yLoc = S->getLocStart();
1893     return true;
1894   }
1895 
1896   SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1897     << isa<CXXConstructorDecl>(Dcl);
1898   return false;
1899 }
1900 
1901 /// Check the body for the given constexpr function declaration only contains
1902 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1903 ///
1904 /// \return true if the body is OK, false if we have diagnosed a problem.
1905 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1906   if (isa<CXXTryStmt>(Body)) {
1907     // C++11 [dcl.constexpr]p3:
1908     //  The definition of a constexpr function shall satisfy the following
1909     //  constraints: [...]
1910     // - its function-body shall be = delete, = default, or a
1911     //   compound-statement
1912     //
1913     // C++11 [dcl.constexpr]p4:
1914     //  In the definition of a constexpr constructor, [...]
1915     // - its function-body shall not be a function-try-block;
1916     Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1917       << isa<CXXConstructorDecl>(Dcl);
1918     return false;
1919   }
1920 
1921   SmallVector<SourceLocation, 4> ReturnStmts;
1922 
1923   // - its function-body shall be [...] a compound-statement that contains only
1924   //   [... list of cases ...]
1925   CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1926   SourceLocation Cxx1yLoc;
1927   for (auto *BodyIt : CompBody->body()) {
1928     if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1929       return false;
1930   }
1931 
1932   if (Cxx1yLoc.isValid())
1933     Diag(Cxx1yLoc,
1934          getLangOpts().CPlusPlus14
1935            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1936            : diag::ext_constexpr_body_invalid_stmt)
1937       << isa<CXXConstructorDecl>(Dcl);
1938 
1939   if (const CXXConstructorDecl *Constructor
1940         = dyn_cast<CXXConstructorDecl>(Dcl)) {
1941     const CXXRecordDecl *RD = Constructor->getParent();
1942     // DR1359:
1943     // - every non-variant non-static data member and base class sub-object
1944     //   shall be initialized;
1945     // DR1460:
1946     // - if the class is a union having variant members, exactly one of them
1947     //   shall be initialized;
1948     if (RD->isUnion()) {
1949       if (Constructor->getNumCtorInitializers() == 0 &&
1950           RD->hasVariantMembers()) {
1951         Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1952         return false;
1953       }
1954     } else if (!Constructor->isDependentContext() &&
1955                !Constructor->isDelegatingConstructor()) {
1956       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1957 
1958       // Skip detailed checking if we have enough initializers, and we would
1959       // allow at most one initializer per member.
1960       bool AnyAnonStructUnionMembers = false;
1961       unsigned Fields = 0;
1962       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1963            E = RD->field_end(); I != E; ++I, ++Fields) {
1964         if (I->isAnonymousStructOrUnion()) {
1965           AnyAnonStructUnionMembers = true;
1966           break;
1967         }
1968       }
1969       // DR1460:
1970       // - if the class is a union-like class, but is not a union, for each of
1971       //   its anonymous union members having variant members, exactly one of
1972       //   them shall be initialized;
1973       if (AnyAnonStructUnionMembers ||
1974           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1975         // Check initialization of non-static data members. Base classes are
1976         // always initialized so do not need to be checked. Dependent bases
1977         // might not have initializers in the member initializer list.
1978         llvm::SmallSet<Decl*, 16> Inits;
1979         for (const auto *I: Constructor->inits()) {
1980           if (FieldDecl *FD = I->getMember())
1981             Inits.insert(FD);
1982           else if (IndirectFieldDecl *ID = I->getIndirectMember())
1983             Inits.insert(ID->chain_begin(), ID->chain_end());
1984         }
1985 
1986         bool Diagnosed = false;
1987         for (auto *I : RD->fields())
1988           CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
1989         if (Diagnosed)
1990           return false;
1991       }
1992     }
1993   } else {
1994     if (ReturnStmts.empty()) {
1995       // C++1y doesn't require constexpr functions to contain a 'return'
1996       // statement. We still do, unless the return type might be void, because
1997       // otherwise if there's no return statement, the function cannot
1998       // be used in a core constant expression.
1999       bool OK = getLangOpts().CPlusPlus14 &&
2000                 (Dcl->getReturnType()->isVoidType() ||
2001                  Dcl->getReturnType()->isDependentType());
2002       Diag(Dcl->getLocation(),
2003            OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2004               : diag::err_constexpr_body_no_return);
2005       if (!OK)
2006         return false;
2007     } else if (ReturnStmts.size() > 1) {
2008       Diag(ReturnStmts.back(),
2009            getLangOpts().CPlusPlus14
2010              ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2011              : diag::ext_constexpr_body_multiple_return);
2012       for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2013         Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2014     }
2015   }
2016 
2017   // C++11 [dcl.constexpr]p5:
2018   //   if no function argument values exist such that the function invocation
2019   //   substitution would produce a constant expression, the program is
2020   //   ill-formed; no diagnostic required.
2021   // C++11 [dcl.constexpr]p3:
2022   //   - every constructor call and implicit conversion used in initializing the
2023   //     return value shall be one of those allowed in a constant expression.
2024   // C++11 [dcl.constexpr]p4:
2025   //   - every constructor involved in initializing non-static data members and
2026   //     base class sub-objects shall be a constexpr constructor.
2027   SmallVector<PartialDiagnosticAt, 8> Diags;
2028   if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2029     Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2030       << isa<CXXConstructorDecl>(Dcl);
2031     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2032       Diag(Diags[I].first, Diags[I].second);
2033     // Don't return false here: we allow this for compatibility in
2034     // system headers.
2035   }
2036 
2037   return true;
2038 }
2039 
2040 /// isCurrentClassName - Determine whether the identifier II is the
2041 /// name of the class type currently being defined. In the case of
2042 /// nested classes, this will only return true if II is the name of
2043 /// the innermost class.
2044 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2045                               const CXXScopeSpec *SS) {
2046   assert(getLangOpts().CPlusPlus && "No class names in C!");
2047 
2048   CXXRecordDecl *CurDecl;
2049   if (SS && SS->isSet() && !SS->isInvalid()) {
2050     DeclContext *DC = computeDeclContext(*SS, true);
2051     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2052   } else
2053     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2054 
2055   if (CurDecl && CurDecl->getIdentifier())
2056     return &II == CurDecl->getIdentifier();
2057   return false;
2058 }
2059 
2060 /// \brief Determine whether the identifier II is a typo for the name of
2061 /// the class type currently being defined. If so, update it to the identifier
2062 /// that should have been used.
2063 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2064   assert(getLangOpts().CPlusPlus && "No class names in C!");
2065 
2066   if (!getLangOpts().SpellChecking)
2067     return false;
2068 
2069   CXXRecordDecl *CurDecl;
2070   if (SS && SS->isSet() && !SS->isInvalid()) {
2071     DeclContext *DC = computeDeclContext(*SS, true);
2072     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2073   } else
2074     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2075 
2076   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2077       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2078           < II->getLength()) {
2079     II = CurDecl->getIdentifier();
2080     return true;
2081   }
2082 
2083   return false;
2084 }
2085 
2086 /// \brief Determine whether the given class is a base class of the given
2087 /// class, including looking at dependent bases.
2088 static bool findCircularInheritance(const CXXRecordDecl *Class,
2089                                     const CXXRecordDecl *Current) {
2090   SmallVector<const CXXRecordDecl*, 8> Queue;
2091 
2092   Class = Class->getCanonicalDecl();
2093   while (true) {
2094     for (const auto &I : Current->bases()) {
2095       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2096       if (!Base)
2097         continue;
2098 
2099       Base = Base->getDefinition();
2100       if (!Base)
2101         continue;
2102 
2103       if (Base->getCanonicalDecl() == Class)
2104         return true;
2105 
2106       Queue.push_back(Base);
2107     }
2108 
2109     if (Queue.empty())
2110       return false;
2111 
2112     Current = Queue.pop_back_val();
2113   }
2114 
2115   return false;
2116 }
2117 
2118 /// \brief Check the validity of a C++ base class specifier.
2119 ///
2120 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2121 /// and returns NULL otherwise.
2122 CXXBaseSpecifier *
2123 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2124                          SourceRange SpecifierRange,
2125                          bool Virtual, AccessSpecifier Access,
2126                          TypeSourceInfo *TInfo,
2127                          SourceLocation EllipsisLoc) {
2128   QualType BaseType = TInfo->getType();
2129 
2130   // C++ [class.union]p1:
2131   //   A union shall not have base classes.
2132   if (Class->isUnion()) {
2133     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2134       << SpecifierRange;
2135     return nullptr;
2136   }
2137 
2138   if (EllipsisLoc.isValid() &&
2139       !TInfo->getType()->containsUnexpandedParameterPack()) {
2140     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2141       << TInfo->getTypeLoc().getSourceRange();
2142     EllipsisLoc = SourceLocation();
2143   }
2144 
2145   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2146 
2147   if (BaseType->isDependentType()) {
2148     // Make sure that we don't have circular inheritance among our dependent
2149     // bases. For non-dependent bases, the check for completeness below handles
2150     // this.
2151     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2152       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2153           ((BaseDecl = BaseDecl->getDefinition()) &&
2154            findCircularInheritance(Class, BaseDecl))) {
2155         Diag(BaseLoc, diag::err_circular_inheritance)
2156           << BaseType << Context.getTypeDeclType(Class);
2157 
2158         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2159           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2160             << BaseType;
2161 
2162         return nullptr;
2163       }
2164     }
2165 
2166     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2167                                           Class->getTagKind() == TTK_Class,
2168                                           Access, TInfo, EllipsisLoc);
2169   }
2170 
2171   // Base specifiers must be record types.
2172   if (!BaseType->isRecordType()) {
2173     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2174     return nullptr;
2175   }
2176 
2177   // C++ [class.union]p1:
2178   //   A union shall not be used as a base class.
2179   if (BaseType->isUnionType()) {
2180     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2181     return nullptr;
2182   }
2183 
2184   // For the MS ABI, propagate DLL attributes to base class templates.
2185   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2186     if (Attr *ClassAttr = getDLLAttr(Class)) {
2187       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2188               BaseType->getAsCXXRecordDecl())) {
2189         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2190                                             BaseLoc);
2191       }
2192     }
2193   }
2194 
2195   // C++ [class.derived]p2:
2196   //   The class-name in a base-specifier shall not be an incompletely
2197   //   defined class.
2198   if (RequireCompleteType(BaseLoc, BaseType,
2199                           diag::err_incomplete_base_class, SpecifierRange)) {
2200     Class->setInvalidDecl();
2201     return nullptr;
2202   }
2203 
2204   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2205   RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2206   assert(BaseDecl && "Record type has no declaration");
2207   BaseDecl = BaseDecl->getDefinition();
2208   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2209   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2210   assert(CXXBaseDecl && "Base type is not a C++ type");
2211 
2212   // A class which contains a flexible array member is not suitable for use as a
2213   // base class:
2214   //   - If the layout determines that a base comes before another base,
2215   //     the flexible array member would index into the subsequent base.
2216   //   - If the layout determines that base comes before the derived class,
2217   //     the flexible array member would index into the derived class.
2218   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2219     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2220       << CXXBaseDecl->getDeclName();
2221     return nullptr;
2222   }
2223 
2224   // C++ [class]p3:
2225   //   If a class is marked final and it appears as a base-type-specifier in
2226   //   base-clause, the program is ill-formed.
2227   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2228     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2229       << CXXBaseDecl->getDeclName()
2230       << FA->isSpelledAsSealed();
2231     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2232         << CXXBaseDecl->getDeclName() << FA->getRange();
2233     return nullptr;
2234   }
2235 
2236   if (BaseDecl->isInvalidDecl())
2237     Class->setInvalidDecl();
2238 
2239   // Create the base specifier.
2240   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2241                                         Class->getTagKind() == TTK_Class,
2242                                         Access, TInfo, EllipsisLoc);
2243 }
2244 
2245 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2246 /// one entry in the base class list of a class specifier, for
2247 /// example:
2248 ///    class foo : public bar, virtual private baz {
2249 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2250 BaseResult
2251 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2252                          ParsedAttributes &Attributes,
2253                          bool Virtual, AccessSpecifier Access,
2254                          ParsedType basetype, SourceLocation BaseLoc,
2255                          SourceLocation EllipsisLoc) {
2256   if (!classdecl)
2257     return true;
2258 
2259   AdjustDeclIfTemplate(classdecl);
2260   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2261   if (!Class)
2262     return true;
2263 
2264   // We haven't yet attached the base specifiers.
2265   Class->setIsParsingBaseSpecifiers();
2266 
2267   // We do not support any C++11 attributes on base-specifiers yet.
2268   // Diagnose any attributes we see.
2269   if (!Attributes.empty()) {
2270     for (AttributeList *Attr = Attributes.getList(); Attr;
2271          Attr = Attr->getNext()) {
2272       if (Attr->isInvalid() ||
2273           Attr->getKind() == AttributeList::IgnoredAttribute)
2274         continue;
2275       Diag(Attr->getLoc(),
2276            Attr->getKind() == AttributeList::UnknownAttribute
2277              ? diag::warn_unknown_attribute_ignored
2278              : diag::err_base_specifier_attribute)
2279         << Attr->getName();
2280     }
2281   }
2282 
2283   TypeSourceInfo *TInfo = nullptr;
2284   GetTypeFromParser(basetype, &TInfo);
2285 
2286   if (EllipsisLoc.isInvalid() &&
2287       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2288                                       UPPC_BaseType))
2289     return true;
2290 
2291   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2292                                                       Virtual, Access, TInfo,
2293                                                       EllipsisLoc))
2294     return BaseSpec;
2295   else
2296     Class->setInvalidDecl();
2297 
2298   return true;
2299 }
2300 
2301 /// Use small set to collect indirect bases.  As this is only used
2302 /// locally, there's no need to abstract the small size parameter.
2303 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2304 
2305 /// \brief Recursively add the bases of Type.  Don't add Type itself.
2306 static void
2307 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2308                   const QualType &Type)
2309 {
2310   // Even though the incoming type is a base, it might not be
2311   // a class -- it could be a template parm, for instance.
2312   if (auto Rec = Type->getAs<RecordType>()) {
2313     auto Decl = Rec->getAsCXXRecordDecl();
2314 
2315     // Iterate over its bases.
2316     for (const auto &BaseSpec : Decl->bases()) {
2317       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2318         .getUnqualifiedType();
2319       if (Set.insert(Base).second)
2320         // If we've not already seen it, recurse.
2321         NoteIndirectBases(Context, Set, Base);
2322     }
2323   }
2324 }
2325 
2326 /// \brief Performs the actual work of attaching the given base class
2327 /// specifiers to a C++ class.
2328 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2329                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2330  if (Bases.empty())
2331     return false;
2332 
2333   // Used to keep track of which base types we have already seen, so
2334   // that we can properly diagnose redundant direct base types. Note
2335   // that the key is always the unqualified canonical type of the base
2336   // class.
2337   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2338 
2339   // Used to track indirect bases so we can see if a direct base is
2340   // ambiguous.
2341   IndirectBaseSet IndirectBaseTypes;
2342 
2343   // Copy non-redundant base specifiers into permanent storage.
2344   unsigned NumGoodBases = 0;
2345   bool Invalid = false;
2346   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2347     QualType NewBaseType
2348       = Context.getCanonicalType(Bases[idx]->getType());
2349     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2350 
2351     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2352     if (KnownBase) {
2353       // C++ [class.mi]p3:
2354       //   A class shall not be specified as a direct base class of a
2355       //   derived class more than once.
2356       Diag(Bases[idx]->getLocStart(),
2357            diag::err_duplicate_base_class)
2358         << KnownBase->getType()
2359         << Bases[idx]->getSourceRange();
2360 
2361       // Delete the duplicate base class specifier; we're going to
2362       // overwrite its pointer later.
2363       Context.Deallocate(Bases[idx]);
2364 
2365       Invalid = true;
2366     } else {
2367       // Okay, add this new base class.
2368       KnownBase = Bases[idx];
2369       Bases[NumGoodBases++] = Bases[idx];
2370 
2371       // Note this base's direct & indirect bases, if there could be ambiguity.
2372       if (Bases.size() > 1)
2373         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2374 
2375       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2376         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2377         if (Class->isInterface() &&
2378               (!RD->isInterface() ||
2379                KnownBase->getAccessSpecifier() != AS_public)) {
2380           // The Microsoft extension __interface does not permit bases that
2381           // are not themselves public interfaces.
2382           Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2383             << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2384             << RD->getSourceRange();
2385           Invalid = true;
2386         }
2387         if (RD->hasAttr<WeakAttr>())
2388           Class->addAttr(WeakAttr::CreateImplicit(Context));
2389       }
2390     }
2391   }
2392 
2393   // Attach the remaining base class specifiers to the derived class.
2394   Class->setBases(Bases.data(), NumGoodBases);
2395 
2396   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2397     // Check whether this direct base is inaccessible due to ambiguity.
2398     QualType BaseType = Bases[idx]->getType();
2399     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2400       .getUnqualifiedType();
2401 
2402     if (IndirectBaseTypes.count(CanonicalBase)) {
2403       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2404                          /*DetectVirtual=*/true);
2405       bool found
2406         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2407       assert(found);
2408       (void)found;
2409 
2410       if (Paths.isAmbiguous(CanonicalBase))
2411         Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2412           << BaseType << getAmbiguousPathsDisplayString(Paths)
2413           << Bases[idx]->getSourceRange();
2414       else
2415         assert(Bases[idx]->isVirtual());
2416     }
2417 
2418     // Delete the base class specifier, since its data has been copied
2419     // into the CXXRecordDecl.
2420     Context.Deallocate(Bases[idx]);
2421   }
2422 
2423   return Invalid;
2424 }
2425 
2426 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2427 /// class, after checking whether there are any duplicate base
2428 /// classes.
2429 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2430                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2431   if (!ClassDecl || Bases.empty())
2432     return;
2433 
2434   AdjustDeclIfTemplate(ClassDecl);
2435   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2436 }
2437 
2438 /// \brief Determine whether the type \p Derived is a C++ class that is
2439 /// derived from the type \p Base.
2440 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2441   if (!getLangOpts().CPlusPlus)
2442     return false;
2443 
2444   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2445   if (!DerivedRD)
2446     return false;
2447 
2448   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2449   if (!BaseRD)
2450     return false;
2451 
2452   // If either the base or the derived type is invalid, don't try to
2453   // check whether one is derived from the other.
2454   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2455     return false;
2456 
2457   // FIXME: In a modules build, do we need the entire path to be visible for us
2458   // to be able to use the inheritance relationship?
2459   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2460     return false;
2461 
2462   return DerivedRD->isDerivedFrom(BaseRD);
2463 }
2464 
2465 /// \brief Determine whether the type \p Derived is a C++ class that is
2466 /// derived from the type \p Base.
2467 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2468                          CXXBasePaths &Paths) {
2469   if (!getLangOpts().CPlusPlus)
2470     return false;
2471 
2472   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2473   if (!DerivedRD)
2474     return false;
2475 
2476   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2477   if (!BaseRD)
2478     return false;
2479 
2480   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2481     return false;
2482 
2483   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2484 }
2485 
2486 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2487                               CXXCastPath &BasePathArray) {
2488   assert(BasePathArray.empty() && "Base path array must be empty!");
2489   assert(Paths.isRecordingPaths() && "Must record paths!");
2490 
2491   const CXXBasePath &Path = Paths.front();
2492 
2493   // We first go backward and check if we have a virtual base.
2494   // FIXME: It would be better if CXXBasePath had the base specifier for
2495   // the nearest virtual base.
2496   unsigned Start = 0;
2497   for (unsigned I = Path.size(); I != 0; --I) {
2498     if (Path[I - 1].Base->isVirtual()) {
2499       Start = I - 1;
2500       break;
2501     }
2502   }
2503 
2504   // Now add all bases.
2505   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2506     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2507 }
2508 
2509 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2510 /// conversion (where Derived and Base are class types) is
2511 /// well-formed, meaning that the conversion is unambiguous (and
2512 /// that all of the base classes are accessible). Returns true
2513 /// and emits a diagnostic if the code is ill-formed, returns false
2514 /// otherwise. Loc is the location where this routine should point to
2515 /// if there is an error, and Range is the source range to highlight
2516 /// if there is an error.
2517 ///
2518 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2519 /// diagnostic for the respective type of error will be suppressed, but the
2520 /// check for ill-formed code will still be performed.
2521 bool
2522 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2523                                    unsigned InaccessibleBaseID,
2524                                    unsigned AmbigiousBaseConvID,
2525                                    SourceLocation Loc, SourceRange Range,
2526                                    DeclarationName Name,
2527                                    CXXCastPath *BasePath,
2528                                    bool IgnoreAccess) {
2529   // First, determine whether the path from Derived to Base is
2530   // ambiguous. This is slightly more expensive than checking whether
2531   // the Derived to Base conversion exists, because here we need to
2532   // explore multiple paths to determine if there is an ambiguity.
2533   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2534                      /*DetectVirtual=*/false);
2535   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2536   assert(DerivationOkay &&
2537          "Can only be used with a derived-to-base conversion");
2538   (void)DerivationOkay;
2539 
2540   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2541     if (!IgnoreAccess) {
2542       // Check that the base class can be accessed.
2543       switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2544                                    InaccessibleBaseID)) {
2545         case AR_inaccessible:
2546           return true;
2547         case AR_accessible:
2548         case AR_dependent:
2549         case AR_delayed:
2550           break;
2551       }
2552     }
2553 
2554     // Build a base path if necessary.
2555     if (BasePath)
2556       BuildBasePathArray(Paths, *BasePath);
2557     return false;
2558   }
2559 
2560   if (AmbigiousBaseConvID) {
2561     // We know that the derived-to-base conversion is ambiguous, and
2562     // we're going to produce a diagnostic. Perform the derived-to-base
2563     // search just one more time to compute all of the possible paths so
2564     // that we can print them out. This is more expensive than any of
2565     // the previous derived-to-base checks we've done, but at this point
2566     // performance isn't as much of an issue.
2567     Paths.clear();
2568     Paths.setRecordingPaths(true);
2569     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2570     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2571     (void)StillOkay;
2572 
2573     // Build up a textual representation of the ambiguous paths, e.g.,
2574     // D -> B -> A, that will be used to illustrate the ambiguous
2575     // conversions in the diagnostic. We only print one of the paths
2576     // to each base class subobject.
2577     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2578 
2579     Diag(Loc, AmbigiousBaseConvID)
2580     << Derived << Base << PathDisplayStr << Range << Name;
2581   }
2582   return true;
2583 }
2584 
2585 bool
2586 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2587                                    SourceLocation Loc, SourceRange Range,
2588                                    CXXCastPath *BasePath,
2589                                    bool IgnoreAccess) {
2590   return CheckDerivedToBaseConversion(
2591       Derived, Base, diag::err_upcast_to_inaccessible_base,
2592       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2593       BasePath, IgnoreAccess);
2594 }
2595 
2596 
2597 /// @brief Builds a string representing ambiguous paths from a
2598 /// specific derived class to different subobjects of the same base
2599 /// class.
2600 ///
2601 /// This function builds a string that can be used in error messages
2602 /// to show the different paths that one can take through the
2603 /// inheritance hierarchy to go from the derived class to different
2604 /// subobjects of a base class. The result looks something like this:
2605 /// @code
2606 /// struct D -> struct B -> struct A
2607 /// struct D -> struct C -> struct A
2608 /// @endcode
2609 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2610   std::string PathDisplayStr;
2611   std::set<unsigned> DisplayedPaths;
2612   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2613        Path != Paths.end(); ++Path) {
2614     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2615       // We haven't displayed a path to this particular base
2616       // class subobject yet.
2617       PathDisplayStr += "\n    ";
2618       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2619       for (CXXBasePath::const_iterator Element = Path->begin();
2620            Element != Path->end(); ++Element)
2621         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2622     }
2623   }
2624 
2625   return PathDisplayStr;
2626 }
2627 
2628 //===----------------------------------------------------------------------===//
2629 // C++ class member Handling
2630 //===----------------------------------------------------------------------===//
2631 
2632 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2633 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2634                                 SourceLocation ASLoc,
2635                                 SourceLocation ColonLoc,
2636                                 AttributeList *Attrs) {
2637   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2638   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2639                                                   ASLoc, ColonLoc);
2640   CurContext->addHiddenDecl(ASDecl);
2641   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2642 }
2643 
2644 /// CheckOverrideControl - Check C++11 override control semantics.
2645 void Sema::CheckOverrideControl(NamedDecl *D) {
2646   if (D->isInvalidDecl())
2647     return;
2648 
2649   // We only care about "override" and "final" declarations.
2650   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2651     return;
2652 
2653   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2654 
2655   // We can't check dependent instance methods.
2656   if (MD && MD->isInstance() &&
2657       (MD->getParent()->hasAnyDependentBases() ||
2658        MD->getType()->isDependentType()))
2659     return;
2660 
2661   if (MD && !MD->isVirtual()) {
2662     // If we have a non-virtual method, check if if hides a virtual method.
2663     // (In that case, it's most likely the method has the wrong type.)
2664     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2665     FindHiddenVirtualMethods(MD, OverloadedMethods);
2666 
2667     if (!OverloadedMethods.empty()) {
2668       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2669         Diag(OA->getLocation(),
2670              diag::override_keyword_hides_virtual_member_function)
2671           << "override" << (OverloadedMethods.size() > 1);
2672       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2673         Diag(FA->getLocation(),
2674              diag::override_keyword_hides_virtual_member_function)
2675           << (FA->isSpelledAsSealed() ? "sealed" : "final")
2676           << (OverloadedMethods.size() > 1);
2677       }
2678       NoteHiddenVirtualMethods(MD, OverloadedMethods);
2679       MD->setInvalidDecl();
2680       return;
2681     }
2682     // Fall through into the general case diagnostic.
2683     // FIXME: We might want to attempt typo correction here.
2684   }
2685 
2686   if (!MD || !MD->isVirtual()) {
2687     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2688       Diag(OA->getLocation(),
2689            diag::override_keyword_only_allowed_on_virtual_member_functions)
2690         << "override" << FixItHint::CreateRemoval(OA->getLocation());
2691       D->dropAttr<OverrideAttr>();
2692     }
2693     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2694       Diag(FA->getLocation(),
2695            diag::override_keyword_only_allowed_on_virtual_member_functions)
2696         << (FA->isSpelledAsSealed() ? "sealed" : "final")
2697         << FixItHint::CreateRemoval(FA->getLocation());
2698       D->dropAttr<FinalAttr>();
2699     }
2700     return;
2701   }
2702 
2703   // C++11 [class.virtual]p5:
2704   //   If a function is marked with the virt-specifier override and
2705   //   does not override a member function of a base class, the program is
2706   //   ill-formed.
2707   bool HasOverriddenMethods =
2708     MD->begin_overridden_methods() != MD->end_overridden_methods();
2709   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2710     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2711       << MD->getDeclName();
2712 }
2713 
2714 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2715   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2716     return;
2717   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2718   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
2719       isa<CXXDestructorDecl>(MD))
2720     return;
2721 
2722   SourceLocation Loc = MD->getLocation();
2723   SourceLocation SpellingLoc = Loc;
2724   if (getSourceManager().isMacroArgExpansion(Loc))
2725     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2726   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2727   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2728       return;
2729 
2730   if (MD->size_overridden_methods() > 0) {
2731     Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
2732       << MD->getDeclName();
2733     const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2734     Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2735   }
2736 }
2737 
2738 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2739 /// function overrides a virtual member function marked 'final', according to
2740 /// C++11 [class.virtual]p4.
2741 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2742                                                   const CXXMethodDecl *Old) {
2743   FinalAttr *FA = Old->getAttr<FinalAttr>();
2744   if (!FA)
2745     return false;
2746 
2747   Diag(New->getLocation(), diag::err_final_function_overridden)
2748     << New->getDeclName()
2749     << FA->isSpelledAsSealed();
2750   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2751   return true;
2752 }
2753 
2754 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2755   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2756   // FIXME: Destruction of ObjC lifetime types has side-effects.
2757   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2758     return !RD->isCompleteDefinition() ||
2759            !RD->hasTrivialDefaultConstructor() ||
2760            !RD->hasTrivialDestructor();
2761   return false;
2762 }
2763 
2764 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2765   for (AttributeList *it = list; it != nullptr; it = it->getNext())
2766     if (it->isDeclspecPropertyAttribute())
2767       return it;
2768   return nullptr;
2769 }
2770 
2771 // Check if there is a field shadowing.
2772 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2773                                       DeclarationName FieldName,
2774                                       const CXXRecordDecl *RD) {
2775   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2776     return;
2777 
2778   // To record a shadowed field in a base
2779   std::map<CXXRecordDecl*, NamedDecl*> Bases;
2780   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2781                            CXXBasePath &Path) {
2782     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2783     // Record an ambiguous path directly
2784     if (Bases.find(Base) != Bases.end())
2785       return true;
2786     for (const auto Field : Base->lookup(FieldName)) {
2787       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2788           Field->getAccess() != AS_private) {
2789         assert(Field->getAccess() != AS_none);
2790         assert(Bases.find(Base) == Bases.end());
2791         Bases[Base] = Field;
2792         return true;
2793       }
2794     }
2795     return false;
2796   };
2797 
2798   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2799                      /*DetectVirtual=*/true);
2800   if (!RD->lookupInBases(FieldShadowed, Paths))
2801     return;
2802 
2803   for (const auto &P : Paths) {
2804     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2805     auto It = Bases.find(Base);
2806     // Skip duplicated bases
2807     if (It == Bases.end())
2808       continue;
2809     auto BaseField = It->second;
2810     assert(BaseField->getAccess() != AS_private);
2811     if (AS_none !=
2812         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2813       Diag(Loc, diag::warn_shadow_field)
2814         << FieldName.getAsString() << RD->getName() << Base->getName();
2815       Diag(BaseField->getLocation(), diag::note_shadow_field);
2816       Bases.erase(It);
2817     }
2818   }
2819 }
2820 
2821 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2822 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2823 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2824 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2825 /// present (but parsing it has been deferred).
2826 NamedDecl *
2827 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2828                                MultiTemplateParamsArg TemplateParameterLists,
2829                                Expr *BW, const VirtSpecifiers &VS,
2830                                InClassInitStyle InitStyle) {
2831   const DeclSpec &DS = D.getDeclSpec();
2832   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2833   DeclarationName Name = NameInfo.getName();
2834   SourceLocation Loc = NameInfo.getLoc();
2835 
2836   // For anonymous bitfields, the location should point to the type.
2837   if (Loc.isInvalid())
2838     Loc = D.getLocStart();
2839 
2840   Expr *BitWidth = static_cast<Expr*>(BW);
2841 
2842   assert(isa<CXXRecordDecl>(CurContext));
2843   assert(!DS.isFriendSpecified());
2844 
2845   bool isFunc = D.isDeclarationOfFunction();
2846 
2847   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2848     // The Microsoft extension __interface only permits public member functions
2849     // and prohibits constructors, destructors, operators, non-public member
2850     // functions, static methods and data members.
2851     unsigned InvalidDecl;
2852     bool ShowDeclName = true;
2853     if (!isFunc)
2854       InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2855     else if (AS != AS_public)
2856       InvalidDecl = 2;
2857     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2858       InvalidDecl = 3;
2859     else switch (Name.getNameKind()) {
2860       case DeclarationName::CXXConstructorName:
2861         InvalidDecl = 4;
2862         ShowDeclName = false;
2863         break;
2864 
2865       case DeclarationName::CXXDestructorName:
2866         InvalidDecl = 5;
2867         ShowDeclName = false;
2868         break;
2869 
2870       case DeclarationName::CXXOperatorName:
2871       case DeclarationName::CXXConversionFunctionName:
2872         InvalidDecl = 6;
2873         break;
2874 
2875       default:
2876         InvalidDecl = 0;
2877         break;
2878     }
2879 
2880     if (InvalidDecl) {
2881       if (ShowDeclName)
2882         Diag(Loc, diag::err_invalid_member_in_interface)
2883           << (InvalidDecl-1) << Name;
2884       else
2885         Diag(Loc, diag::err_invalid_member_in_interface)
2886           << (InvalidDecl-1) << "";
2887       return nullptr;
2888     }
2889   }
2890 
2891   // C++ 9.2p6: A member shall not be declared to have automatic storage
2892   // duration (auto, register) or with the extern storage-class-specifier.
2893   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2894   // data members and cannot be applied to names declared const or static,
2895   // and cannot be applied to reference members.
2896   switch (DS.getStorageClassSpec()) {
2897   case DeclSpec::SCS_unspecified:
2898   case DeclSpec::SCS_typedef:
2899   case DeclSpec::SCS_static:
2900     break;
2901   case DeclSpec::SCS_mutable:
2902     if (isFunc) {
2903       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2904 
2905       // FIXME: It would be nicer if the keyword was ignored only for this
2906       // declarator. Otherwise we could get follow-up errors.
2907       D.getMutableDeclSpec().ClearStorageClassSpecs();
2908     }
2909     break;
2910   default:
2911     Diag(DS.getStorageClassSpecLoc(),
2912          diag::err_storageclass_invalid_for_member);
2913     D.getMutableDeclSpec().ClearStorageClassSpecs();
2914     break;
2915   }
2916 
2917   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2918                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2919                       !isFunc);
2920 
2921   if (DS.isConstexprSpecified() && isInstField) {
2922     SemaDiagnosticBuilder B =
2923         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2924     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2925     if (InitStyle == ICIS_NoInit) {
2926       B << 0 << 0;
2927       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2928         B << FixItHint::CreateRemoval(ConstexprLoc);
2929       else {
2930         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2931         D.getMutableDeclSpec().ClearConstexprSpec();
2932         const char *PrevSpec;
2933         unsigned DiagID;
2934         bool Failed = D.getMutableDeclSpec().SetTypeQual(
2935             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2936         (void)Failed;
2937         assert(!Failed && "Making a constexpr member const shouldn't fail");
2938       }
2939     } else {
2940       B << 1;
2941       const char *PrevSpec;
2942       unsigned DiagID;
2943       if (D.getMutableDeclSpec().SetStorageClassSpec(
2944           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2945           Context.getPrintingPolicy())) {
2946         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2947                "This is the only DeclSpec that should fail to be applied");
2948         B << 1;
2949       } else {
2950         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2951         isInstField = false;
2952       }
2953     }
2954   }
2955 
2956   NamedDecl *Member;
2957   if (isInstField) {
2958     CXXScopeSpec &SS = D.getCXXScopeSpec();
2959 
2960     // Data members must have identifiers for names.
2961     if (!Name.isIdentifier()) {
2962       Diag(Loc, diag::err_bad_variable_name)
2963         << Name;
2964       return nullptr;
2965     }
2966 
2967     IdentifierInfo *II = Name.getAsIdentifierInfo();
2968 
2969     // Member field could not be with "template" keyword.
2970     // So TemplateParameterLists should be empty in this case.
2971     if (TemplateParameterLists.size()) {
2972       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2973       if (TemplateParams->size()) {
2974         // There is no such thing as a member field template.
2975         Diag(D.getIdentifierLoc(), diag::err_template_member)
2976             << II
2977             << SourceRange(TemplateParams->getTemplateLoc(),
2978                 TemplateParams->getRAngleLoc());
2979       } else {
2980         // There is an extraneous 'template<>' for this member.
2981         Diag(TemplateParams->getTemplateLoc(),
2982             diag::err_template_member_noparams)
2983             << II
2984             << SourceRange(TemplateParams->getTemplateLoc(),
2985                 TemplateParams->getRAngleLoc());
2986       }
2987       return nullptr;
2988     }
2989 
2990     if (SS.isSet() && !SS.isInvalid()) {
2991       // The user provided a superfluous scope specifier inside a class
2992       // definition:
2993       //
2994       // class X {
2995       //   int X::member;
2996       // };
2997       if (DeclContext *DC = computeDeclContext(SS, false))
2998         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2999       else
3000         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3001           << Name << SS.getRange();
3002 
3003       SS.clear();
3004     }
3005 
3006     AttributeList *MSPropertyAttr =
3007       getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
3008     if (MSPropertyAttr) {
3009       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3010                                 BitWidth, InitStyle, AS, MSPropertyAttr);
3011       if (!Member)
3012         return nullptr;
3013       isInstField = false;
3014     } else {
3015       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3016                                 BitWidth, InitStyle, AS);
3017       if (!Member)
3018         return nullptr;
3019     }
3020 
3021     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3022   } else {
3023     Member = HandleDeclarator(S, D, TemplateParameterLists);
3024     if (!Member)
3025       return nullptr;
3026 
3027     // Non-instance-fields can't have a bitfield.
3028     if (BitWidth) {
3029       if (Member->isInvalidDecl()) {
3030         // don't emit another diagnostic.
3031       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3032         // C++ 9.6p3: A bit-field shall not be a static member.
3033         // "static member 'A' cannot be a bit-field"
3034         Diag(Loc, diag::err_static_not_bitfield)
3035           << Name << BitWidth->getSourceRange();
3036       } else if (isa<TypedefDecl>(Member)) {
3037         // "typedef member 'x' cannot be a bit-field"
3038         Diag(Loc, diag::err_typedef_not_bitfield)
3039           << Name << BitWidth->getSourceRange();
3040       } else {
3041         // A function typedef ("typedef int f(); f a;").
3042         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3043         Diag(Loc, diag::err_not_integral_type_bitfield)
3044           << Name << cast<ValueDecl>(Member)->getType()
3045           << BitWidth->getSourceRange();
3046       }
3047 
3048       BitWidth = nullptr;
3049       Member->setInvalidDecl();
3050     }
3051 
3052     Member->setAccess(AS);
3053 
3054     // If we have declared a member function template or static data member
3055     // template, set the access of the templated declaration as well.
3056     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3057       FunTmpl->getTemplatedDecl()->setAccess(AS);
3058     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3059       VarTmpl->getTemplatedDecl()->setAccess(AS);
3060   }
3061 
3062   if (VS.isOverrideSpecified())
3063     Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3064   if (VS.isFinalSpecified())
3065     Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3066                                             VS.isFinalSpelledSealed()));
3067 
3068   if (VS.getLastLocation().isValid()) {
3069     // Update the end location of a method that has a virt-specifiers.
3070     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3071       MD->setRangeEnd(VS.getLastLocation());
3072   }
3073 
3074   CheckOverrideControl(Member);
3075 
3076   assert((Name || isInstField) && "No identifier for non-field ?");
3077 
3078   if (isInstField) {
3079     FieldDecl *FD = cast<FieldDecl>(Member);
3080     FieldCollector->Add(FD);
3081 
3082     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3083       // Remember all explicit private FieldDecls that have a name, no side
3084       // effects and are not part of a dependent type declaration.
3085       if (!FD->isImplicit() && FD->getDeclName() &&
3086           FD->getAccess() == AS_private &&
3087           !FD->hasAttr<UnusedAttr>() &&
3088           !FD->getParent()->isDependentContext() &&
3089           !InitializationHasSideEffects(*FD))
3090         UnusedPrivateFields.insert(FD);
3091     }
3092   }
3093 
3094   return Member;
3095 }
3096 
3097 namespace {
3098   class UninitializedFieldVisitor
3099       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3100     Sema &S;
3101     // List of Decls to generate a warning on.  Also remove Decls that become
3102     // initialized.
3103     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3104     // List of base classes of the record.  Classes are removed after their
3105     // initializers.
3106     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3107     // Vector of decls to be removed from the Decl set prior to visiting the
3108     // nodes.  These Decls may have been initialized in the prior initializer.
3109     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3110     // If non-null, add a note to the warning pointing back to the constructor.
3111     const CXXConstructorDecl *Constructor;
3112     // Variables to hold state when processing an initializer list.  When
3113     // InitList is true, special case initialization of FieldDecls matching
3114     // InitListFieldDecl.
3115     bool InitList;
3116     FieldDecl *InitListFieldDecl;
3117     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3118 
3119   public:
3120     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3121     UninitializedFieldVisitor(Sema &S,
3122                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3123                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3124       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3125         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3126 
3127     // Returns true if the use of ME is not an uninitialized use.
3128     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3129                                          bool CheckReferenceOnly) {
3130       llvm::SmallVector<FieldDecl*, 4> Fields;
3131       bool ReferenceField = false;
3132       while (ME) {
3133         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3134         if (!FD)
3135           return false;
3136         Fields.push_back(FD);
3137         if (FD->getType()->isReferenceType())
3138           ReferenceField = true;
3139         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3140       }
3141 
3142       // Binding a reference to an unintialized field is not an
3143       // uninitialized use.
3144       if (CheckReferenceOnly && !ReferenceField)
3145         return true;
3146 
3147       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3148       // Discard the first field since it is the field decl that is being
3149       // initialized.
3150       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3151         UsedFieldIndex.push_back((*I)->getFieldIndex());
3152       }
3153 
3154       for (auto UsedIter = UsedFieldIndex.begin(),
3155                 UsedEnd = UsedFieldIndex.end(),
3156                 OrigIter = InitFieldIndex.begin(),
3157                 OrigEnd = InitFieldIndex.end();
3158            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3159         if (*UsedIter < *OrigIter)
3160           return true;
3161         if (*UsedIter > *OrigIter)
3162           break;
3163       }
3164 
3165       return false;
3166     }
3167 
3168     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3169                           bool AddressOf) {
3170       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3171         return;
3172 
3173       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3174       // or union.
3175       MemberExpr *FieldME = ME;
3176 
3177       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3178 
3179       Expr *Base = ME;
3180       while (MemberExpr *SubME =
3181                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3182 
3183         if (isa<VarDecl>(SubME->getMemberDecl()))
3184           return;
3185 
3186         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3187           if (!FD->isAnonymousStructOrUnion())
3188             FieldME = SubME;
3189 
3190         if (!FieldME->getType().isPODType(S.Context))
3191           AllPODFields = false;
3192 
3193         Base = SubME->getBase();
3194       }
3195 
3196       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3197         return;
3198 
3199       if (AddressOf && AllPODFields)
3200         return;
3201 
3202       ValueDecl* FoundVD = FieldME->getMemberDecl();
3203 
3204       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3205         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3206           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3207         }
3208 
3209         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3210           QualType T = BaseCast->getType();
3211           if (T->isPointerType() &&
3212               BaseClasses.count(T->getPointeeType())) {
3213             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3214                 << T->getPointeeType() << FoundVD;
3215           }
3216         }
3217       }
3218 
3219       if (!Decls.count(FoundVD))
3220         return;
3221 
3222       const bool IsReference = FoundVD->getType()->isReferenceType();
3223 
3224       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3225         // Special checking for initializer lists.
3226         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3227           return;
3228         }
3229       } else {
3230         // Prevent double warnings on use of unbounded references.
3231         if (CheckReferenceOnly && !IsReference)
3232           return;
3233       }
3234 
3235       unsigned diag = IsReference
3236           ? diag::warn_reference_field_is_uninit
3237           : diag::warn_field_is_uninit;
3238       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3239       if (Constructor)
3240         S.Diag(Constructor->getLocation(),
3241                diag::note_uninit_in_this_constructor)
3242           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3243 
3244     }
3245 
3246     void HandleValue(Expr *E, bool AddressOf) {
3247       E = E->IgnoreParens();
3248 
3249       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3250         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3251                          AddressOf /*AddressOf*/);
3252         return;
3253       }
3254 
3255       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3256         Visit(CO->getCond());
3257         HandleValue(CO->getTrueExpr(), AddressOf);
3258         HandleValue(CO->getFalseExpr(), AddressOf);
3259         return;
3260       }
3261 
3262       if (BinaryConditionalOperator *BCO =
3263               dyn_cast<BinaryConditionalOperator>(E)) {
3264         Visit(BCO->getCond());
3265         HandleValue(BCO->getFalseExpr(), AddressOf);
3266         return;
3267       }
3268 
3269       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3270         HandleValue(OVE->getSourceExpr(), AddressOf);
3271         return;
3272       }
3273 
3274       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3275         switch (BO->getOpcode()) {
3276         default:
3277           break;
3278         case(BO_PtrMemD):
3279         case(BO_PtrMemI):
3280           HandleValue(BO->getLHS(), AddressOf);
3281           Visit(BO->getRHS());
3282           return;
3283         case(BO_Comma):
3284           Visit(BO->getLHS());
3285           HandleValue(BO->getRHS(), AddressOf);
3286           return;
3287         }
3288       }
3289 
3290       Visit(E);
3291     }
3292 
3293     void CheckInitListExpr(InitListExpr *ILE) {
3294       InitFieldIndex.push_back(0);
3295       for (auto Child : ILE->children()) {
3296         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3297           CheckInitListExpr(SubList);
3298         } else {
3299           Visit(Child);
3300         }
3301         ++InitFieldIndex.back();
3302       }
3303       InitFieldIndex.pop_back();
3304     }
3305 
3306     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3307                           FieldDecl *Field, const Type *BaseClass) {
3308       // Remove Decls that may have been initialized in the previous
3309       // initializer.
3310       for (ValueDecl* VD : DeclsToRemove)
3311         Decls.erase(VD);
3312       DeclsToRemove.clear();
3313 
3314       Constructor = FieldConstructor;
3315       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3316 
3317       if (ILE && Field) {
3318         InitList = true;
3319         InitListFieldDecl = Field;
3320         InitFieldIndex.clear();
3321         CheckInitListExpr(ILE);
3322       } else {
3323         InitList = false;
3324         Visit(E);
3325       }
3326 
3327       if (Field)
3328         Decls.erase(Field);
3329       if (BaseClass)
3330         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3331     }
3332 
3333     void VisitMemberExpr(MemberExpr *ME) {
3334       // All uses of unbounded reference fields will warn.
3335       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3336     }
3337 
3338     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3339       if (E->getCastKind() == CK_LValueToRValue) {
3340         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3341         return;
3342       }
3343 
3344       Inherited::VisitImplicitCastExpr(E);
3345     }
3346 
3347     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3348       if (E->getConstructor()->isCopyConstructor()) {
3349         Expr *ArgExpr = E->getArg(0);
3350         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3351           if (ILE->getNumInits() == 1)
3352             ArgExpr = ILE->getInit(0);
3353         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3354           if (ICE->getCastKind() == CK_NoOp)
3355             ArgExpr = ICE->getSubExpr();
3356         HandleValue(ArgExpr, false /*AddressOf*/);
3357         return;
3358       }
3359       Inherited::VisitCXXConstructExpr(E);
3360     }
3361 
3362     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3363       Expr *Callee = E->getCallee();
3364       if (isa<MemberExpr>(Callee)) {
3365         HandleValue(Callee, false /*AddressOf*/);
3366         for (auto Arg : E->arguments())
3367           Visit(Arg);
3368         return;
3369       }
3370 
3371       Inherited::VisitCXXMemberCallExpr(E);
3372     }
3373 
3374     void VisitCallExpr(CallExpr *E) {
3375       // Treat std::move as a use.
3376       if (E->getNumArgs() == 1) {
3377         if (FunctionDecl *FD = E->getDirectCallee()) {
3378           if (FD->isInStdNamespace() && FD->getIdentifier() &&
3379               FD->getIdentifier()->isStr("move")) {
3380             HandleValue(E->getArg(0), false /*AddressOf*/);
3381             return;
3382           }
3383         }
3384       }
3385 
3386       Inherited::VisitCallExpr(E);
3387     }
3388 
3389     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3390       Expr *Callee = E->getCallee();
3391 
3392       if (isa<UnresolvedLookupExpr>(Callee))
3393         return Inherited::VisitCXXOperatorCallExpr(E);
3394 
3395       Visit(Callee);
3396       for (auto Arg : E->arguments())
3397         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3398     }
3399 
3400     void VisitBinaryOperator(BinaryOperator *E) {
3401       // If a field assignment is detected, remove the field from the
3402       // uninitiailized field set.
3403       if (E->getOpcode() == BO_Assign)
3404         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3405           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3406             if (!FD->getType()->isReferenceType())
3407               DeclsToRemove.push_back(FD);
3408 
3409       if (E->isCompoundAssignmentOp()) {
3410         HandleValue(E->getLHS(), false /*AddressOf*/);
3411         Visit(E->getRHS());
3412         return;
3413       }
3414 
3415       Inherited::VisitBinaryOperator(E);
3416     }
3417 
3418     void VisitUnaryOperator(UnaryOperator *E) {
3419       if (E->isIncrementDecrementOp()) {
3420         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3421         return;
3422       }
3423       if (E->getOpcode() == UO_AddrOf) {
3424         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3425           HandleValue(ME->getBase(), true /*AddressOf*/);
3426           return;
3427         }
3428       }
3429 
3430       Inherited::VisitUnaryOperator(E);
3431     }
3432   };
3433 
3434   // Diagnose value-uses of fields to initialize themselves, e.g.
3435   //   foo(foo)
3436   // where foo is not also a parameter to the constructor.
3437   // Also diagnose across field uninitialized use such as
3438   //   x(y), y(x)
3439   // TODO: implement -Wuninitialized and fold this into that framework.
3440   static void DiagnoseUninitializedFields(
3441       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3442 
3443     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3444                                            Constructor->getLocation())) {
3445       return;
3446     }
3447 
3448     if (Constructor->isInvalidDecl())
3449       return;
3450 
3451     const CXXRecordDecl *RD = Constructor->getParent();
3452 
3453     if (RD->getDescribedClassTemplate())
3454       return;
3455 
3456     // Holds fields that are uninitialized.
3457     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3458 
3459     // At the beginning, all fields are uninitialized.
3460     for (auto *I : RD->decls()) {
3461       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3462         UninitializedFields.insert(FD);
3463       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3464         UninitializedFields.insert(IFD->getAnonField());
3465       }
3466     }
3467 
3468     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3469     for (auto I : RD->bases())
3470       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3471 
3472     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3473       return;
3474 
3475     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3476                                                    UninitializedFields,
3477                                                    UninitializedBaseClasses);
3478 
3479     for (const auto *FieldInit : Constructor->inits()) {
3480       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3481         break;
3482 
3483       Expr *InitExpr = FieldInit->getInit();
3484       if (!InitExpr)
3485         continue;
3486 
3487       if (CXXDefaultInitExpr *Default =
3488               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3489         InitExpr = Default->getExpr();
3490         if (!InitExpr)
3491           continue;
3492         // In class initializers will point to the constructor.
3493         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3494                                               FieldInit->getAnyMember(),
3495                                               FieldInit->getBaseClass());
3496       } else {
3497         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3498                                               FieldInit->getAnyMember(),
3499                                               FieldInit->getBaseClass());
3500       }
3501     }
3502   }
3503 } // namespace
3504 
3505 /// \brief Enter a new C++ default initializer scope. After calling this, the
3506 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3507 /// parsing or instantiating the initializer failed.
3508 void Sema::ActOnStartCXXInClassMemberInitializer() {
3509   // Create a synthetic function scope to represent the call to the constructor
3510   // that notionally surrounds a use of this initializer.
3511   PushFunctionScope();
3512 }
3513 
3514 /// \brief This is invoked after parsing an in-class initializer for a
3515 /// non-static C++ class member, and after instantiating an in-class initializer
3516 /// in a class template. Such actions are deferred until the class is complete.
3517 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3518                                                   SourceLocation InitLoc,
3519                                                   Expr *InitExpr) {
3520   // Pop the notional constructor scope we created earlier.
3521   PopFunctionScopeInfo(nullptr, D);
3522 
3523   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3524   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3525          "must set init style when field is created");
3526 
3527   if (!InitExpr) {
3528     D->setInvalidDecl();
3529     if (FD)
3530       FD->removeInClassInitializer();
3531     return;
3532   }
3533 
3534   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3535     FD->setInvalidDecl();
3536     FD->removeInClassInitializer();
3537     return;
3538   }
3539 
3540   ExprResult Init = InitExpr;
3541   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3542     InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3543     InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3544         ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3545         : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3546     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3547     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3548     if (Init.isInvalid()) {
3549       FD->setInvalidDecl();
3550       return;
3551     }
3552   }
3553 
3554   // C++11 [class.base.init]p7:
3555   //   The initialization of each base and member constitutes a
3556   //   full-expression.
3557   Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3558   if (Init.isInvalid()) {
3559     FD->setInvalidDecl();
3560     return;
3561   }
3562 
3563   InitExpr = Init.get();
3564 
3565   FD->setInClassInitializer(InitExpr);
3566 }
3567 
3568 /// \brief Find the direct and/or virtual base specifiers that
3569 /// correspond to the given base type, for use in base initialization
3570 /// within a constructor.
3571 static bool FindBaseInitializer(Sema &SemaRef,
3572                                 CXXRecordDecl *ClassDecl,
3573                                 QualType BaseType,
3574                                 const CXXBaseSpecifier *&DirectBaseSpec,
3575                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
3576   // First, check for a direct base class.
3577   DirectBaseSpec = nullptr;
3578   for (const auto &Base : ClassDecl->bases()) {
3579     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3580       // We found a direct base of this type. That's what we're
3581       // initializing.
3582       DirectBaseSpec = &Base;
3583       break;
3584     }
3585   }
3586 
3587   // Check for a virtual base class.
3588   // FIXME: We might be able to short-circuit this if we know in advance that
3589   // there are no virtual bases.
3590   VirtualBaseSpec = nullptr;
3591   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3592     // We haven't found a base yet; search the class hierarchy for a
3593     // virtual base class.
3594     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3595                        /*DetectVirtual=*/false);
3596     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3597                               SemaRef.Context.getTypeDeclType(ClassDecl),
3598                               BaseType, Paths)) {
3599       for (CXXBasePaths::paths_iterator Path = Paths.begin();
3600            Path != Paths.end(); ++Path) {
3601         if (Path->back().Base->isVirtual()) {
3602           VirtualBaseSpec = Path->back().Base;
3603           break;
3604         }
3605       }
3606     }
3607   }
3608 
3609   return DirectBaseSpec || VirtualBaseSpec;
3610 }
3611 
3612 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3613 MemInitResult
3614 Sema::ActOnMemInitializer(Decl *ConstructorD,
3615                           Scope *S,
3616                           CXXScopeSpec &SS,
3617                           IdentifierInfo *MemberOrBase,
3618                           ParsedType TemplateTypeTy,
3619                           const DeclSpec &DS,
3620                           SourceLocation IdLoc,
3621                           Expr *InitList,
3622                           SourceLocation EllipsisLoc) {
3623   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3624                              DS, IdLoc, InitList,
3625                              EllipsisLoc);
3626 }
3627 
3628 /// \brief Handle a C++ member initializer using parentheses syntax.
3629 MemInitResult
3630 Sema::ActOnMemInitializer(Decl *ConstructorD,
3631                           Scope *S,
3632                           CXXScopeSpec &SS,
3633                           IdentifierInfo *MemberOrBase,
3634                           ParsedType TemplateTypeTy,
3635                           const DeclSpec &DS,
3636                           SourceLocation IdLoc,
3637                           SourceLocation LParenLoc,
3638                           ArrayRef<Expr *> Args,
3639                           SourceLocation RParenLoc,
3640                           SourceLocation EllipsisLoc) {
3641   Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3642                                            Args, RParenLoc);
3643   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3644                              DS, IdLoc, List, EllipsisLoc);
3645 }
3646 
3647 namespace {
3648 
3649 // Callback to only accept typo corrections that can be a valid C++ member
3650 // intializer: either a non-static field member or a base class.
3651 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3652 public:
3653   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3654       : ClassDecl(ClassDecl) {}
3655 
3656   bool ValidateCandidate(const TypoCorrection &candidate) override {
3657     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3658       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3659         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3660       return isa<TypeDecl>(ND);
3661     }
3662     return false;
3663   }
3664 
3665 private:
3666   CXXRecordDecl *ClassDecl;
3667 };
3668 
3669 }
3670 
3671 /// \brief Handle a C++ member initializer.
3672 MemInitResult
3673 Sema::BuildMemInitializer(Decl *ConstructorD,
3674                           Scope *S,
3675                           CXXScopeSpec &SS,
3676                           IdentifierInfo *MemberOrBase,
3677                           ParsedType TemplateTypeTy,
3678                           const DeclSpec &DS,
3679                           SourceLocation IdLoc,
3680                           Expr *Init,
3681                           SourceLocation EllipsisLoc) {
3682   ExprResult Res = CorrectDelayedTyposInExpr(Init);
3683   if (!Res.isUsable())
3684     return true;
3685   Init = Res.get();
3686 
3687   if (!ConstructorD)
3688     return true;
3689 
3690   AdjustDeclIfTemplate(ConstructorD);
3691 
3692   CXXConstructorDecl *Constructor
3693     = dyn_cast<CXXConstructorDecl>(ConstructorD);
3694   if (!Constructor) {
3695     // The user wrote a constructor initializer on a function that is
3696     // not a C++ constructor. Ignore the error for now, because we may
3697     // have more member initializers coming; we'll diagnose it just
3698     // once in ActOnMemInitializers.
3699     return true;
3700   }
3701 
3702   CXXRecordDecl *ClassDecl = Constructor->getParent();
3703 
3704   // C++ [class.base.init]p2:
3705   //   Names in a mem-initializer-id are looked up in the scope of the
3706   //   constructor's class and, if not found in that scope, are looked
3707   //   up in the scope containing the constructor's definition.
3708   //   [Note: if the constructor's class contains a member with the
3709   //   same name as a direct or virtual base class of the class, a
3710   //   mem-initializer-id naming the member or base class and composed
3711   //   of a single identifier refers to the class member. A
3712   //   mem-initializer-id for the hidden base class may be specified
3713   //   using a qualified name. ]
3714   if (!SS.getScopeRep() && !TemplateTypeTy) {
3715     // Look for a member, first.
3716     DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3717     if (!Result.empty()) {
3718       ValueDecl *Member;
3719       if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3720           (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3721         if (EllipsisLoc.isValid())
3722           Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3723             << MemberOrBase
3724             << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3725 
3726         return BuildMemberInitializer(Member, Init, IdLoc);
3727       }
3728     }
3729   }
3730   // It didn't name a member, so see if it names a class.
3731   QualType BaseType;
3732   TypeSourceInfo *TInfo = nullptr;
3733 
3734   if (TemplateTypeTy) {
3735     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3736   } else if (DS.getTypeSpecType() == TST_decltype) {
3737     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3738   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3739     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3740     return true;
3741   } else {
3742     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3743     LookupParsedName(R, S, &SS);
3744 
3745     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3746     if (!TyD) {
3747       if (R.isAmbiguous()) return true;
3748 
3749       // We don't want access-control diagnostics here.
3750       R.suppressDiagnostics();
3751 
3752       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3753         bool NotUnknownSpecialization = false;
3754         DeclContext *DC = computeDeclContext(SS, false);
3755         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3756           NotUnknownSpecialization = !Record->hasAnyDependentBases();
3757 
3758         if (!NotUnknownSpecialization) {
3759           // When the scope specifier can refer to a member of an unknown
3760           // specialization, we take it as a type name.
3761           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3762                                        SS.getWithLocInContext(Context),
3763                                        *MemberOrBase, IdLoc);
3764           if (BaseType.isNull())
3765             return true;
3766 
3767           R.clear();
3768           R.setLookupName(MemberOrBase);
3769         }
3770       }
3771 
3772       // If no results were found, try to correct typos.
3773       TypoCorrection Corr;
3774       if (R.empty() && BaseType.isNull() &&
3775           (Corr = CorrectTypo(
3776                R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3777                llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3778                CTK_ErrorRecovery, ClassDecl))) {
3779         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3780           // We have found a non-static data member with a similar
3781           // name to what was typed; complain and initialize that
3782           // member.
3783           diagnoseTypo(Corr,
3784                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
3785                          << MemberOrBase << true);
3786           return BuildMemberInitializer(Member, Init, IdLoc);
3787         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3788           const CXXBaseSpecifier *DirectBaseSpec;
3789           const CXXBaseSpecifier *VirtualBaseSpec;
3790           if (FindBaseInitializer(*this, ClassDecl,
3791                                   Context.getTypeDeclType(Type),
3792                                   DirectBaseSpec, VirtualBaseSpec)) {
3793             // We have found a direct or virtual base class with a
3794             // similar name to what was typed; complain and initialize
3795             // that base class.
3796             diagnoseTypo(Corr,
3797                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
3798                            << MemberOrBase << false,
3799                          PDiag() /*Suppress note, we provide our own.*/);
3800 
3801             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3802                                                               : VirtualBaseSpec;
3803             Diag(BaseSpec->getLocStart(),
3804                  diag::note_base_class_specified_here)
3805               << BaseSpec->getType()
3806               << BaseSpec->getSourceRange();
3807 
3808             TyD = Type;
3809           }
3810         }
3811       }
3812 
3813       if (!TyD && BaseType.isNull()) {
3814         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3815           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3816         return true;
3817       }
3818     }
3819 
3820     if (BaseType.isNull()) {
3821       BaseType = Context.getTypeDeclType(TyD);
3822       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3823       if (SS.isSet()) {
3824         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3825                                              BaseType);
3826         TInfo = Context.CreateTypeSourceInfo(BaseType);
3827         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3828         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3829         TL.setElaboratedKeywordLoc(SourceLocation());
3830         TL.setQualifierLoc(SS.getWithLocInContext(Context));
3831       }
3832     }
3833   }
3834 
3835   if (!TInfo)
3836     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3837 
3838   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3839 }
3840 
3841 /// Checks a member initializer expression for cases where reference (or
3842 /// pointer) members are bound to by-value parameters (or their addresses).
3843 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3844                                                Expr *Init,
3845                                                SourceLocation IdLoc) {
3846   QualType MemberTy = Member->getType();
3847 
3848   // We only handle pointers and references currently.
3849   // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3850   if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3851     return;
3852 
3853   const bool IsPointer = MemberTy->isPointerType();
3854   if (IsPointer) {
3855     if (const UnaryOperator *Op
3856           = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3857       // The only case we're worried about with pointers requires taking the
3858       // address.
3859       if (Op->getOpcode() != UO_AddrOf)
3860         return;
3861 
3862       Init = Op->getSubExpr();
3863     } else {
3864       // We only handle address-of expression initializers for pointers.
3865       return;
3866     }
3867   }
3868 
3869   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3870     // We only warn when referring to a non-reference parameter declaration.
3871     const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3872     if (!Parameter || Parameter->getType()->isReferenceType())
3873       return;
3874 
3875     S.Diag(Init->getExprLoc(),
3876            IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3877                      : diag::warn_bind_ref_member_to_parameter)
3878       << Member << Parameter << Init->getSourceRange();
3879   } else {
3880     // Other initializers are fine.
3881     return;
3882   }
3883 
3884   S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3885     << (unsigned)IsPointer;
3886 }
3887 
3888 MemInitResult
3889 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3890                              SourceLocation IdLoc) {
3891   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3892   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3893   assert((DirectMember || IndirectMember) &&
3894          "Member must be a FieldDecl or IndirectFieldDecl");
3895 
3896   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3897     return true;
3898 
3899   if (Member->isInvalidDecl())
3900     return true;
3901 
3902   MultiExprArg Args;
3903   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3904     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3905   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3906     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3907   } else {
3908     // Template instantiation doesn't reconstruct ParenListExprs for us.
3909     Args = Init;
3910   }
3911 
3912   SourceRange InitRange = Init->getSourceRange();
3913 
3914   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3915     // Can't check initialization for a member of dependent type or when
3916     // any of the arguments are type-dependent expressions.
3917     DiscardCleanupsInEvaluationContext();
3918   } else {
3919     bool InitList = false;
3920     if (isa<InitListExpr>(Init)) {
3921       InitList = true;
3922       Args = Init;
3923     }
3924 
3925     // Initialize the member.
3926     InitializedEntity MemberEntity =
3927       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3928                    : InitializedEntity::InitializeMember(IndirectMember,
3929                                                          nullptr);
3930     InitializationKind Kind =
3931       InitList ? InitializationKind::CreateDirectList(IdLoc)
3932                : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3933                                                   InitRange.getEnd());
3934 
3935     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3936     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3937                                             nullptr);
3938     if (MemberInit.isInvalid())
3939       return true;
3940 
3941     CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3942 
3943     // C++11 [class.base.init]p7:
3944     //   The initialization of each base and member constitutes a
3945     //   full-expression.
3946     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3947     if (MemberInit.isInvalid())
3948       return true;
3949 
3950     Init = MemberInit.get();
3951   }
3952 
3953   if (DirectMember) {
3954     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3955                                             InitRange.getBegin(), Init,
3956                                             InitRange.getEnd());
3957   } else {
3958     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3959                                             InitRange.getBegin(), Init,
3960                                             InitRange.getEnd());
3961   }
3962 }
3963 
3964 MemInitResult
3965 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3966                                  CXXRecordDecl *ClassDecl) {
3967   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3968   if (!LangOpts.CPlusPlus11)
3969     return Diag(NameLoc, diag::err_delegating_ctor)
3970       << TInfo->getTypeLoc().getLocalSourceRange();
3971   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3972 
3973   bool InitList = true;
3974   MultiExprArg Args = Init;
3975   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3976     InitList = false;
3977     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3978   }
3979 
3980   SourceRange InitRange = Init->getSourceRange();
3981   // Initialize the object.
3982   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3983                                      QualType(ClassDecl->getTypeForDecl(), 0));
3984   InitializationKind Kind =
3985     InitList ? InitializationKind::CreateDirectList(NameLoc)
3986              : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3987                                                 InitRange.getEnd());
3988   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
3989   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
3990                                               Args, nullptr);
3991   if (DelegationInit.isInvalid())
3992     return true;
3993 
3994   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3995          "Delegating constructor with no target?");
3996 
3997   // C++11 [class.base.init]p7:
3998   //   The initialization of each base and member constitutes a
3999   //   full-expression.
4000   DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4001                                        InitRange.getBegin());
4002   if (DelegationInit.isInvalid())
4003     return true;
4004 
4005   // If we are in a dependent context, template instantiation will
4006   // perform this type-checking again. Just save the arguments that we
4007   // received in a ParenListExpr.
4008   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4009   // of the information that we have about the base
4010   // initializer. However, deconstructing the ASTs is a dicey process,
4011   // and this approach is far more likely to get the corner cases right.
4012   if (CurContext->isDependentContext())
4013     DelegationInit = Init;
4014 
4015   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4016                                           DelegationInit.getAs<Expr>(),
4017                                           InitRange.getEnd());
4018 }
4019 
4020 MemInitResult
4021 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4022                            Expr *Init, CXXRecordDecl *ClassDecl,
4023                            SourceLocation EllipsisLoc) {
4024   SourceLocation BaseLoc
4025     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4026 
4027   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4028     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4029              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4030 
4031   // C++ [class.base.init]p2:
4032   //   [...] Unless the mem-initializer-id names a nonstatic data
4033   //   member of the constructor's class or a direct or virtual base
4034   //   of that class, the mem-initializer is ill-formed. A
4035   //   mem-initializer-list can initialize a base class using any
4036   //   name that denotes that base class type.
4037   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4038 
4039   SourceRange InitRange = Init->getSourceRange();
4040   if (EllipsisLoc.isValid()) {
4041     // This is a pack expansion.
4042     if (!BaseType->containsUnexpandedParameterPack())  {
4043       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4044         << SourceRange(BaseLoc, InitRange.getEnd());
4045 
4046       EllipsisLoc = SourceLocation();
4047     }
4048   } else {
4049     // Check for any unexpanded parameter packs.
4050     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4051       return true;
4052 
4053     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4054       return true;
4055   }
4056 
4057   // Check for direct and virtual base classes.
4058   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4059   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4060   if (!Dependent) {
4061     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4062                                        BaseType))
4063       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4064 
4065     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4066                         VirtualBaseSpec);
4067 
4068     // C++ [base.class.init]p2:
4069     // Unless the mem-initializer-id names a nonstatic data member of the
4070     // constructor's class or a direct or virtual base of that class, the
4071     // mem-initializer is ill-formed.
4072     if (!DirectBaseSpec && !VirtualBaseSpec) {
4073       // If the class has any dependent bases, then it's possible that
4074       // one of those types will resolve to the same type as
4075       // BaseType. Therefore, just treat this as a dependent base
4076       // class initialization.  FIXME: Should we try to check the
4077       // initialization anyway? It seems odd.
4078       if (ClassDecl->hasAnyDependentBases())
4079         Dependent = true;
4080       else
4081         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4082           << BaseType << Context.getTypeDeclType(ClassDecl)
4083           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4084     }
4085   }
4086 
4087   if (Dependent) {
4088     DiscardCleanupsInEvaluationContext();
4089 
4090     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4091                                             /*IsVirtual=*/false,
4092                                             InitRange.getBegin(), Init,
4093                                             InitRange.getEnd(), EllipsisLoc);
4094   }
4095 
4096   // C++ [base.class.init]p2:
4097   //   If a mem-initializer-id is ambiguous because it designates both
4098   //   a direct non-virtual base class and an inherited virtual base
4099   //   class, the mem-initializer is ill-formed.
4100   if (DirectBaseSpec && VirtualBaseSpec)
4101     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4102       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4103 
4104   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4105   if (!BaseSpec)
4106     BaseSpec = VirtualBaseSpec;
4107 
4108   // Initialize the base.
4109   bool InitList = true;
4110   MultiExprArg Args = Init;
4111   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4112     InitList = false;
4113     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4114   }
4115 
4116   InitializedEntity BaseEntity =
4117     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4118   InitializationKind Kind =
4119     InitList ? InitializationKind::CreateDirectList(BaseLoc)
4120              : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4121                                                 InitRange.getEnd());
4122   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4123   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4124   if (BaseInit.isInvalid())
4125     return true;
4126 
4127   // C++11 [class.base.init]p7:
4128   //   The initialization of each base and member constitutes a
4129   //   full-expression.
4130   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4131   if (BaseInit.isInvalid())
4132     return true;
4133 
4134   // If we are in a dependent context, template instantiation will
4135   // perform this type-checking again. Just save the arguments that we
4136   // received in a ParenListExpr.
4137   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4138   // of the information that we have about the base
4139   // initializer. However, deconstructing the ASTs is a dicey process,
4140   // and this approach is far more likely to get the corner cases right.
4141   if (CurContext->isDependentContext())
4142     BaseInit = Init;
4143 
4144   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4145                                           BaseSpec->isVirtual(),
4146                                           InitRange.getBegin(),
4147                                           BaseInit.getAs<Expr>(),
4148                                           InitRange.getEnd(), EllipsisLoc);
4149 }
4150 
4151 // Create a static_cast\<T&&>(expr).
4152 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4153   if (T.isNull()) T = E->getType();
4154   QualType TargetType = SemaRef.BuildReferenceType(
4155       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4156   SourceLocation ExprLoc = E->getLocStart();
4157   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4158       TargetType, ExprLoc);
4159 
4160   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4161                                    SourceRange(ExprLoc, ExprLoc),
4162                                    E->getSourceRange()).get();
4163 }
4164 
4165 /// ImplicitInitializerKind - How an implicit base or member initializer should
4166 /// initialize its base or member.
4167 enum ImplicitInitializerKind {
4168   IIK_Default,
4169   IIK_Copy,
4170   IIK_Move,
4171   IIK_Inherit
4172 };
4173 
4174 static bool
4175 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4176                              ImplicitInitializerKind ImplicitInitKind,
4177                              CXXBaseSpecifier *BaseSpec,
4178                              bool IsInheritedVirtualBase,
4179                              CXXCtorInitializer *&CXXBaseInit) {
4180   InitializedEntity InitEntity
4181     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4182                                         IsInheritedVirtualBase);
4183 
4184   ExprResult BaseInit;
4185 
4186   switch (ImplicitInitKind) {
4187   case IIK_Inherit:
4188   case IIK_Default: {
4189     InitializationKind InitKind
4190       = InitializationKind::CreateDefault(Constructor->getLocation());
4191     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4192     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4193     break;
4194   }
4195 
4196   case IIK_Move:
4197   case IIK_Copy: {
4198     bool Moving = ImplicitInitKind == IIK_Move;
4199     ParmVarDecl *Param = Constructor->getParamDecl(0);
4200     QualType ParamType = Param->getType().getNonReferenceType();
4201 
4202     Expr *CopyCtorArg =
4203       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4204                           SourceLocation(), Param, false,
4205                           Constructor->getLocation(), ParamType,
4206                           VK_LValue, nullptr);
4207 
4208     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4209 
4210     // Cast to the base class to avoid ambiguities.
4211     QualType ArgTy =
4212       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4213                                        ParamType.getQualifiers());
4214 
4215     if (Moving) {
4216       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4217     }
4218 
4219     CXXCastPath BasePath;
4220     BasePath.push_back(BaseSpec);
4221     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4222                                             CK_UncheckedDerivedToBase,
4223                                             Moving ? VK_XValue : VK_LValue,
4224                                             &BasePath).get();
4225 
4226     InitializationKind InitKind
4227       = InitializationKind::CreateDirect(Constructor->getLocation(),
4228                                          SourceLocation(), SourceLocation());
4229     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4230     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4231     break;
4232   }
4233   }
4234 
4235   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4236   if (BaseInit.isInvalid())
4237     return true;
4238 
4239   CXXBaseInit =
4240     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4241                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4242                                                         SourceLocation()),
4243                                              BaseSpec->isVirtual(),
4244                                              SourceLocation(),
4245                                              BaseInit.getAs<Expr>(),
4246                                              SourceLocation(),
4247                                              SourceLocation());
4248 
4249   return false;
4250 }
4251 
4252 static bool RefersToRValueRef(Expr *MemRef) {
4253   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4254   return Referenced->getType()->isRValueReferenceType();
4255 }
4256 
4257 static bool
4258 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4259                                ImplicitInitializerKind ImplicitInitKind,
4260                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4261                                CXXCtorInitializer *&CXXMemberInit) {
4262   if (Field->isInvalidDecl())
4263     return true;
4264 
4265   SourceLocation Loc = Constructor->getLocation();
4266 
4267   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4268     bool Moving = ImplicitInitKind == IIK_Move;
4269     ParmVarDecl *Param = Constructor->getParamDecl(0);
4270     QualType ParamType = Param->getType().getNonReferenceType();
4271 
4272     // Suppress copying zero-width bitfields.
4273     if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4274       return false;
4275 
4276     Expr *MemberExprBase =
4277       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4278                           SourceLocation(), Param, false,
4279                           Loc, ParamType, VK_LValue, nullptr);
4280 
4281     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4282 
4283     if (Moving) {
4284       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4285     }
4286 
4287     // Build a reference to this field within the parameter.
4288     CXXScopeSpec SS;
4289     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4290                               Sema::LookupMemberName);
4291     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4292                                   : cast<ValueDecl>(Field), AS_public);
4293     MemberLookup.resolveKind();
4294     ExprResult CtorArg
4295       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4296                                          ParamType, Loc,
4297                                          /*IsArrow=*/false,
4298                                          SS,
4299                                          /*TemplateKWLoc=*/SourceLocation(),
4300                                          /*FirstQualifierInScope=*/nullptr,
4301                                          MemberLookup,
4302                                          /*TemplateArgs=*/nullptr,
4303                                          /*S*/nullptr);
4304     if (CtorArg.isInvalid())
4305       return true;
4306 
4307     // C++11 [class.copy]p15:
4308     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4309     //     with static_cast<T&&>(x.m);
4310     if (RefersToRValueRef(CtorArg.get())) {
4311       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4312     }
4313 
4314     InitializedEntity Entity =
4315         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4316                                                        /*Implicit*/ true)
4317                  : InitializedEntity::InitializeMember(Field, nullptr,
4318                                                        /*Implicit*/ true);
4319 
4320     // Direct-initialize to use the copy constructor.
4321     InitializationKind InitKind =
4322       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4323 
4324     Expr *CtorArgE = CtorArg.getAs<Expr>();
4325     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4326     ExprResult MemberInit =
4327         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4328     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4329     if (MemberInit.isInvalid())
4330       return true;
4331 
4332     if (Indirect)
4333       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4334           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4335     else
4336       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4337           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4338     return false;
4339   }
4340 
4341   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4342          "Unhandled implicit init kind!");
4343 
4344   QualType FieldBaseElementType =
4345     SemaRef.Context.getBaseElementType(Field->getType());
4346 
4347   if (FieldBaseElementType->isRecordType()) {
4348     InitializedEntity InitEntity =
4349         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4350                                                        /*Implicit*/ true)
4351                  : InitializedEntity::InitializeMember(Field, nullptr,
4352                                                        /*Implicit*/ true);
4353     InitializationKind InitKind =
4354       InitializationKind::CreateDefault(Loc);
4355 
4356     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4357     ExprResult MemberInit =
4358       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4359 
4360     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4361     if (MemberInit.isInvalid())
4362       return true;
4363 
4364     if (Indirect)
4365       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4366                                                                Indirect, Loc,
4367                                                                Loc,
4368                                                                MemberInit.get(),
4369                                                                Loc);
4370     else
4371       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4372                                                                Field, Loc, Loc,
4373                                                                MemberInit.get(),
4374                                                                Loc);
4375     return false;
4376   }
4377 
4378   if (!Field->getParent()->isUnion()) {
4379     if (FieldBaseElementType->isReferenceType()) {
4380       SemaRef.Diag(Constructor->getLocation(),
4381                    diag::err_uninitialized_member_in_ctor)
4382       << (int)Constructor->isImplicit()
4383       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4384       << 0 << Field->getDeclName();
4385       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4386       return true;
4387     }
4388 
4389     if (FieldBaseElementType.isConstQualified()) {
4390       SemaRef.Diag(Constructor->getLocation(),
4391                    diag::err_uninitialized_member_in_ctor)
4392       << (int)Constructor->isImplicit()
4393       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4394       << 1 << Field->getDeclName();
4395       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4396       return true;
4397     }
4398   }
4399 
4400   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
4401       FieldBaseElementType->isObjCRetainableType() &&
4402       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
4403       FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
4404     // ARC:
4405     //   Default-initialize Objective-C pointers to NULL.
4406     CXXMemberInit
4407       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4408                                                  Loc, Loc,
4409                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4410                                                  Loc);
4411     return false;
4412   }
4413 
4414   // Nothing to initialize.
4415   CXXMemberInit = nullptr;
4416   return false;
4417 }
4418 
4419 namespace {
4420 struct BaseAndFieldInfo {
4421   Sema &S;
4422   CXXConstructorDecl *Ctor;
4423   bool AnyErrorsInInits;
4424   ImplicitInitializerKind IIK;
4425   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4426   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4427   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4428 
4429   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4430     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4431     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4432     if (Ctor->getInheritedConstructor())
4433       IIK = IIK_Inherit;
4434     else if (Generated && Ctor->isCopyConstructor())
4435       IIK = IIK_Copy;
4436     else if (Generated && Ctor->isMoveConstructor())
4437       IIK = IIK_Move;
4438     else
4439       IIK = IIK_Default;
4440   }
4441 
4442   bool isImplicitCopyOrMove() const {
4443     switch (IIK) {
4444     case IIK_Copy:
4445     case IIK_Move:
4446       return true;
4447 
4448     case IIK_Default:
4449     case IIK_Inherit:
4450       return false;
4451     }
4452 
4453     llvm_unreachable("Invalid ImplicitInitializerKind!");
4454   }
4455 
4456   bool addFieldInitializer(CXXCtorInitializer *Init) {
4457     AllToInit.push_back(Init);
4458 
4459     // Check whether this initializer makes the field "used".
4460     if (Init->getInit()->HasSideEffects(S.Context))
4461       S.UnusedPrivateFields.remove(Init->getAnyMember());
4462 
4463     return false;
4464   }
4465 
4466   bool isInactiveUnionMember(FieldDecl *Field) {
4467     RecordDecl *Record = Field->getParent();
4468     if (!Record->isUnion())
4469       return false;
4470 
4471     if (FieldDecl *Active =
4472             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4473       return Active != Field->getCanonicalDecl();
4474 
4475     // In an implicit copy or move constructor, ignore any in-class initializer.
4476     if (isImplicitCopyOrMove())
4477       return true;
4478 
4479     // If there's no explicit initialization, the field is active only if it
4480     // has an in-class initializer...
4481     if (Field->hasInClassInitializer())
4482       return false;
4483     // ... or it's an anonymous struct or union whose class has an in-class
4484     // initializer.
4485     if (!Field->isAnonymousStructOrUnion())
4486       return true;
4487     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4488     return !FieldRD->hasInClassInitializer();
4489   }
4490 
4491   /// \brief Determine whether the given field is, or is within, a union member
4492   /// that is inactive (because there was an initializer given for a different
4493   /// member of the union, or because the union was not initialized at all).
4494   bool isWithinInactiveUnionMember(FieldDecl *Field,
4495                                    IndirectFieldDecl *Indirect) {
4496     if (!Indirect)
4497       return isInactiveUnionMember(Field);
4498 
4499     for (auto *C : Indirect->chain()) {
4500       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4501       if (Field && isInactiveUnionMember(Field))
4502         return true;
4503     }
4504     return false;
4505   }
4506 };
4507 }
4508 
4509 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4510 /// array type.
4511 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4512   if (T->isIncompleteArrayType())
4513     return true;
4514 
4515   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4516     if (!ArrayT->getSize())
4517       return true;
4518 
4519     T = ArrayT->getElementType();
4520   }
4521 
4522   return false;
4523 }
4524 
4525 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4526                                     FieldDecl *Field,
4527                                     IndirectFieldDecl *Indirect = nullptr) {
4528   if (Field->isInvalidDecl())
4529     return false;
4530 
4531   // Overwhelmingly common case: we have a direct initializer for this field.
4532   if (CXXCtorInitializer *Init =
4533           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4534     return Info.addFieldInitializer(Init);
4535 
4536   // C++11 [class.base.init]p8:
4537   //   if the entity is a non-static data member that has a
4538   //   brace-or-equal-initializer and either
4539   //   -- the constructor's class is a union and no other variant member of that
4540   //      union is designated by a mem-initializer-id or
4541   //   -- the constructor's class is not a union, and, if the entity is a member
4542   //      of an anonymous union, no other member of that union is designated by
4543   //      a mem-initializer-id,
4544   //   the entity is initialized as specified in [dcl.init].
4545   //
4546   // We also apply the same rules to handle anonymous structs within anonymous
4547   // unions.
4548   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4549     return false;
4550 
4551   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4552     ExprResult DIE =
4553         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4554     if (DIE.isInvalid())
4555       return true;
4556     CXXCtorInitializer *Init;
4557     if (Indirect)
4558       Init = new (SemaRef.Context)
4559           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4560                              SourceLocation(), DIE.get(), SourceLocation());
4561     else
4562       Init = new (SemaRef.Context)
4563           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4564                              SourceLocation(), DIE.get(), SourceLocation());
4565     return Info.addFieldInitializer(Init);
4566   }
4567 
4568   // Don't initialize incomplete or zero-length arrays.
4569   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4570     return false;
4571 
4572   // Don't try to build an implicit initializer if there were semantic
4573   // errors in any of the initializers (and therefore we might be
4574   // missing some that the user actually wrote).
4575   if (Info.AnyErrorsInInits)
4576     return false;
4577 
4578   CXXCtorInitializer *Init = nullptr;
4579   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4580                                      Indirect, Init))
4581     return true;
4582 
4583   if (!Init)
4584     return false;
4585 
4586   return Info.addFieldInitializer(Init);
4587 }
4588 
4589 bool
4590 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4591                                CXXCtorInitializer *Initializer) {
4592   assert(Initializer->isDelegatingInitializer());
4593   Constructor->setNumCtorInitializers(1);
4594   CXXCtorInitializer **initializer =
4595     new (Context) CXXCtorInitializer*[1];
4596   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4597   Constructor->setCtorInitializers(initializer);
4598 
4599   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4600     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4601     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4602   }
4603 
4604   DelegatingCtorDecls.push_back(Constructor);
4605 
4606   DiagnoseUninitializedFields(*this, Constructor);
4607 
4608   return false;
4609 }
4610 
4611 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4612                                ArrayRef<CXXCtorInitializer *> Initializers) {
4613   if (Constructor->isDependentContext()) {
4614     // Just store the initializers as written, they will be checked during
4615     // instantiation.
4616     if (!Initializers.empty()) {
4617       Constructor->setNumCtorInitializers(Initializers.size());
4618       CXXCtorInitializer **baseOrMemberInitializers =
4619         new (Context) CXXCtorInitializer*[Initializers.size()];
4620       memcpy(baseOrMemberInitializers, Initializers.data(),
4621              Initializers.size() * sizeof(CXXCtorInitializer*));
4622       Constructor->setCtorInitializers(baseOrMemberInitializers);
4623     }
4624 
4625     // Let template instantiation know whether we had errors.
4626     if (AnyErrors)
4627       Constructor->setInvalidDecl();
4628 
4629     return false;
4630   }
4631 
4632   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4633 
4634   // We need to build the initializer AST according to order of construction
4635   // and not what user specified in the Initializers list.
4636   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4637   if (!ClassDecl)
4638     return true;
4639 
4640   bool HadError = false;
4641 
4642   for (unsigned i = 0; i < Initializers.size(); i++) {
4643     CXXCtorInitializer *Member = Initializers[i];
4644 
4645     if (Member->isBaseInitializer())
4646       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4647     else {
4648       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4649 
4650       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4651         for (auto *C : F->chain()) {
4652           FieldDecl *FD = dyn_cast<FieldDecl>(C);
4653           if (FD && FD->getParent()->isUnion())
4654             Info.ActiveUnionMember.insert(std::make_pair(
4655                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4656         }
4657       } else if (FieldDecl *FD = Member->getMember()) {
4658         if (FD->getParent()->isUnion())
4659           Info.ActiveUnionMember.insert(std::make_pair(
4660               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4661       }
4662     }
4663   }
4664 
4665   // Keep track of the direct virtual bases.
4666   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4667   for (auto &I : ClassDecl->bases()) {
4668     if (I.isVirtual())
4669       DirectVBases.insert(&I);
4670   }
4671 
4672   // Push virtual bases before others.
4673   for (auto &VBase : ClassDecl->vbases()) {
4674     if (CXXCtorInitializer *Value
4675         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4676       // [class.base.init]p7, per DR257:
4677       //   A mem-initializer where the mem-initializer-id names a virtual base
4678       //   class is ignored during execution of a constructor of any class that
4679       //   is not the most derived class.
4680       if (ClassDecl->isAbstract()) {
4681         // FIXME: Provide a fixit to remove the base specifier. This requires
4682         // tracking the location of the associated comma for a base specifier.
4683         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4684           << VBase.getType() << ClassDecl;
4685         DiagnoseAbstractType(ClassDecl);
4686       }
4687 
4688       Info.AllToInit.push_back(Value);
4689     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4690       // [class.base.init]p8, per DR257:
4691       //   If a given [...] base class is not named by a mem-initializer-id
4692       //   [...] and the entity is not a virtual base class of an abstract
4693       //   class, then [...] the entity is default-initialized.
4694       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4695       CXXCtorInitializer *CXXBaseInit;
4696       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4697                                        &VBase, IsInheritedVirtualBase,
4698                                        CXXBaseInit)) {
4699         HadError = true;
4700         continue;
4701       }
4702 
4703       Info.AllToInit.push_back(CXXBaseInit);
4704     }
4705   }
4706 
4707   // Non-virtual bases.
4708   for (auto &Base : ClassDecl->bases()) {
4709     // Virtuals are in the virtual base list and already constructed.
4710     if (Base.isVirtual())
4711       continue;
4712 
4713     if (CXXCtorInitializer *Value
4714           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4715       Info.AllToInit.push_back(Value);
4716     } else if (!AnyErrors) {
4717       CXXCtorInitializer *CXXBaseInit;
4718       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4719                                        &Base, /*IsInheritedVirtualBase=*/false,
4720                                        CXXBaseInit)) {
4721         HadError = true;
4722         continue;
4723       }
4724 
4725       Info.AllToInit.push_back(CXXBaseInit);
4726     }
4727   }
4728 
4729   // Fields.
4730   for (auto *Mem : ClassDecl->decls()) {
4731     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4732       // C++ [class.bit]p2:
4733       //   A declaration for a bit-field that omits the identifier declares an
4734       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
4735       //   initialized.
4736       if (F->isUnnamedBitfield())
4737         continue;
4738 
4739       // If we're not generating the implicit copy/move constructor, then we'll
4740       // handle anonymous struct/union fields based on their individual
4741       // indirect fields.
4742       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4743         continue;
4744 
4745       if (CollectFieldInitializer(*this, Info, F))
4746         HadError = true;
4747       continue;
4748     }
4749 
4750     // Beyond this point, we only consider default initialization.
4751     if (Info.isImplicitCopyOrMove())
4752       continue;
4753 
4754     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4755       if (F->getType()->isIncompleteArrayType()) {
4756         assert(ClassDecl->hasFlexibleArrayMember() &&
4757                "Incomplete array type is not valid");
4758         continue;
4759       }
4760 
4761       // Initialize each field of an anonymous struct individually.
4762       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4763         HadError = true;
4764 
4765       continue;
4766     }
4767   }
4768 
4769   unsigned NumInitializers = Info.AllToInit.size();
4770   if (NumInitializers > 0) {
4771     Constructor->setNumCtorInitializers(NumInitializers);
4772     CXXCtorInitializer **baseOrMemberInitializers =
4773       new (Context) CXXCtorInitializer*[NumInitializers];
4774     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4775            NumInitializers * sizeof(CXXCtorInitializer*));
4776     Constructor->setCtorInitializers(baseOrMemberInitializers);
4777 
4778     // Constructors implicitly reference the base and member
4779     // destructors.
4780     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4781                                            Constructor->getParent());
4782   }
4783 
4784   return HadError;
4785 }
4786 
4787 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4788   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4789     const RecordDecl *RD = RT->getDecl();
4790     if (RD->isAnonymousStructOrUnion()) {
4791       for (auto *Field : RD->fields())
4792         PopulateKeysForFields(Field, IdealInits);
4793       return;
4794     }
4795   }
4796   IdealInits.push_back(Field->getCanonicalDecl());
4797 }
4798 
4799 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4800   return Context.getCanonicalType(BaseType).getTypePtr();
4801 }
4802 
4803 static const void *GetKeyForMember(ASTContext &Context,
4804                                    CXXCtorInitializer *Member) {
4805   if (!Member->isAnyMemberInitializer())
4806     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4807 
4808   return Member->getAnyMember()->getCanonicalDecl();
4809 }
4810 
4811 static void DiagnoseBaseOrMemInitializerOrder(
4812     Sema &SemaRef, const CXXConstructorDecl *Constructor,
4813     ArrayRef<CXXCtorInitializer *> Inits) {
4814   if (Constructor->getDeclContext()->isDependentContext())
4815     return;
4816 
4817   // Don't check initializers order unless the warning is enabled at the
4818   // location of at least one initializer.
4819   bool ShouldCheckOrder = false;
4820   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4821     CXXCtorInitializer *Init = Inits[InitIndex];
4822     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4823                                  Init->getSourceLocation())) {
4824       ShouldCheckOrder = true;
4825       break;
4826     }
4827   }
4828   if (!ShouldCheckOrder)
4829     return;
4830 
4831   // Build the list of bases and members in the order that they'll
4832   // actually be initialized.  The explicit initializers should be in
4833   // this same order but may be missing things.
4834   SmallVector<const void*, 32> IdealInitKeys;
4835 
4836   const CXXRecordDecl *ClassDecl = Constructor->getParent();
4837 
4838   // 1. Virtual bases.
4839   for (const auto &VBase : ClassDecl->vbases())
4840     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4841 
4842   // 2. Non-virtual bases.
4843   for (const auto &Base : ClassDecl->bases()) {
4844     if (Base.isVirtual())
4845       continue;
4846     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4847   }
4848 
4849   // 3. Direct fields.
4850   for (auto *Field : ClassDecl->fields()) {
4851     if (Field->isUnnamedBitfield())
4852       continue;
4853 
4854     PopulateKeysForFields(Field, IdealInitKeys);
4855   }
4856 
4857   unsigned NumIdealInits = IdealInitKeys.size();
4858   unsigned IdealIndex = 0;
4859 
4860   CXXCtorInitializer *PrevInit = nullptr;
4861   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4862     CXXCtorInitializer *Init = Inits[InitIndex];
4863     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4864 
4865     // Scan forward to try to find this initializer in the idealized
4866     // initializers list.
4867     for (; IdealIndex != NumIdealInits; ++IdealIndex)
4868       if (InitKey == IdealInitKeys[IdealIndex])
4869         break;
4870 
4871     // If we didn't find this initializer, it must be because we
4872     // scanned past it on a previous iteration.  That can only
4873     // happen if we're out of order;  emit a warning.
4874     if (IdealIndex == NumIdealInits && PrevInit) {
4875       Sema::SemaDiagnosticBuilder D =
4876         SemaRef.Diag(PrevInit->getSourceLocation(),
4877                      diag::warn_initializer_out_of_order);
4878 
4879       if (PrevInit->isAnyMemberInitializer())
4880         D << 0 << PrevInit->getAnyMember()->getDeclName();
4881       else
4882         D << 1 << PrevInit->getTypeSourceInfo()->getType();
4883 
4884       if (Init->isAnyMemberInitializer())
4885         D << 0 << Init->getAnyMember()->getDeclName();
4886       else
4887         D << 1 << Init->getTypeSourceInfo()->getType();
4888 
4889       // Move back to the initializer's location in the ideal list.
4890       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4891         if (InitKey == IdealInitKeys[IdealIndex])
4892           break;
4893 
4894       assert(IdealIndex < NumIdealInits &&
4895              "initializer not found in initializer list");
4896     }
4897 
4898     PrevInit = Init;
4899   }
4900 }
4901 
4902 namespace {
4903 bool CheckRedundantInit(Sema &S,
4904                         CXXCtorInitializer *Init,
4905                         CXXCtorInitializer *&PrevInit) {
4906   if (!PrevInit) {
4907     PrevInit = Init;
4908     return false;
4909   }
4910 
4911   if (FieldDecl *Field = Init->getAnyMember())
4912     S.Diag(Init->getSourceLocation(),
4913            diag::err_multiple_mem_initialization)
4914       << Field->getDeclName()
4915       << Init->getSourceRange();
4916   else {
4917     const Type *BaseClass = Init->getBaseClass();
4918     assert(BaseClass && "neither field nor base");
4919     S.Diag(Init->getSourceLocation(),
4920            diag::err_multiple_base_initialization)
4921       << QualType(BaseClass, 0)
4922       << Init->getSourceRange();
4923   }
4924   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4925     << 0 << PrevInit->getSourceRange();
4926 
4927   return true;
4928 }
4929 
4930 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4931 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4932 
4933 bool CheckRedundantUnionInit(Sema &S,
4934                              CXXCtorInitializer *Init,
4935                              RedundantUnionMap &Unions) {
4936   FieldDecl *Field = Init->getAnyMember();
4937   RecordDecl *Parent = Field->getParent();
4938   NamedDecl *Child = Field;
4939 
4940   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4941     if (Parent->isUnion()) {
4942       UnionEntry &En = Unions[Parent];
4943       if (En.first && En.first != Child) {
4944         S.Diag(Init->getSourceLocation(),
4945                diag::err_multiple_mem_union_initialization)
4946           << Field->getDeclName()
4947           << Init->getSourceRange();
4948         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4949           << 0 << En.second->getSourceRange();
4950         return true;
4951       }
4952       if (!En.first) {
4953         En.first = Child;
4954         En.second = Init;
4955       }
4956       if (!Parent->isAnonymousStructOrUnion())
4957         return false;
4958     }
4959 
4960     Child = Parent;
4961     Parent = cast<RecordDecl>(Parent->getDeclContext());
4962   }
4963 
4964   return false;
4965 }
4966 }
4967 
4968 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4969 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4970                                 SourceLocation ColonLoc,
4971                                 ArrayRef<CXXCtorInitializer*> MemInits,
4972                                 bool AnyErrors) {
4973   if (!ConstructorDecl)
4974     return;
4975 
4976   AdjustDeclIfTemplate(ConstructorDecl);
4977 
4978   CXXConstructorDecl *Constructor
4979     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4980 
4981   if (!Constructor) {
4982     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4983     return;
4984   }
4985 
4986   // Mapping for the duplicate initializers check.
4987   // For member initializers, this is keyed with a FieldDecl*.
4988   // For base initializers, this is keyed with a Type*.
4989   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
4990 
4991   // Mapping for the inconsistent anonymous-union initializers check.
4992   RedundantUnionMap MemberUnions;
4993 
4994   bool HadError = false;
4995   for (unsigned i = 0; i < MemInits.size(); i++) {
4996     CXXCtorInitializer *Init = MemInits[i];
4997 
4998     // Set the source order index.
4999     Init->setSourceOrder(i);
5000 
5001     if (Init->isAnyMemberInitializer()) {
5002       const void *Key = GetKeyForMember(Context, Init);
5003       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5004           CheckRedundantUnionInit(*this, Init, MemberUnions))
5005         HadError = true;
5006     } else if (Init->isBaseInitializer()) {
5007       const void *Key = GetKeyForMember(Context, Init);
5008       if (CheckRedundantInit(*this, Init, Members[Key]))
5009         HadError = true;
5010     } else {
5011       assert(Init->isDelegatingInitializer());
5012       // This must be the only initializer
5013       if (MemInits.size() != 1) {
5014         Diag(Init->getSourceLocation(),
5015              diag::err_delegating_initializer_alone)
5016           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5017         // We will treat this as being the only initializer.
5018       }
5019       SetDelegatingInitializer(Constructor, MemInits[i]);
5020       // Return immediately as the initializer is set.
5021       return;
5022     }
5023   }
5024 
5025   if (HadError)
5026     return;
5027 
5028   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5029 
5030   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5031 
5032   DiagnoseUninitializedFields(*this, Constructor);
5033 }
5034 
5035 void
5036 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5037                                              CXXRecordDecl *ClassDecl) {
5038   // Ignore dependent contexts. Also ignore unions, since their members never
5039   // have destructors implicitly called.
5040   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5041     return;
5042 
5043   // FIXME: all the access-control diagnostics are positioned on the
5044   // field/base declaration.  That's probably good; that said, the
5045   // user might reasonably want to know why the destructor is being
5046   // emitted, and we currently don't say.
5047 
5048   // Non-static data members.
5049   for (auto *Field : ClassDecl->fields()) {
5050     if (Field->isInvalidDecl())
5051       continue;
5052 
5053     // Don't destroy incomplete or zero-length arrays.
5054     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5055       continue;
5056 
5057     QualType FieldType = Context.getBaseElementType(Field->getType());
5058 
5059     const RecordType* RT = FieldType->getAs<RecordType>();
5060     if (!RT)
5061       continue;
5062 
5063     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5064     if (FieldClassDecl->isInvalidDecl())
5065       continue;
5066     if (FieldClassDecl->hasIrrelevantDestructor())
5067       continue;
5068     // The destructor for an implicit anonymous union member is never invoked.
5069     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5070       continue;
5071 
5072     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5073     assert(Dtor && "No dtor found for FieldClassDecl!");
5074     CheckDestructorAccess(Field->getLocation(), Dtor,
5075                           PDiag(diag::err_access_dtor_field)
5076                             << Field->getDeclName()
5077                             << FieldType);
5078 
5079     MarkFunctionReferenced(Location, Dtor);
5080     DiagnoseUseOfDecl(Dtor, Location);
5081   }
5082 
5083   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5084 
5085   // Bases.
5086   for (const auto &Base : ClassDecl->bases()) {
5087     // Bases are always records in a well-formed non-dependent class.
5088     const RecordType *RT = Base.getType()->getAs<RecordType>();
5089 
5090     // Remember direct virtual bases.
5091     if (Base.isVirtual())
5092       DirectVirtualBases.insert(RT);
5093 
5094     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5095     // If our base class is invalid, we probably can't get its dtor anyway.
5096     if (BaseClassDecl->isInvalidDecl())
5097       continue;
5098     if (BaseClassDecl->hasIrrelevantDestructor())
5099       continue;
5100 
5101     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5102     assert(Dtor && "No dtor found for BaseClassDecl!");
5103 
5104     // FIXME: caret should be on the start of the class name
5105     CheckDestructorAccess(Base.getLocStart(), Dtor,
5106                           PDiag(diag::err_access_dtor_base)
5107                             << Base.getType()
5108                             << Base.getSourceRange(),
5109                           Context.getTypeDeclType(ClassDecl));
5110 
5111     MarkFunctionReferenced(Location, Dtor);
5112     DiagnoseUseOfDecl(Dtor, Location);
5113   }
5114 
5115   // Virtual bases.
5116   for (const auto &VBase : ClassDecl->vbases()) {
5117     // Bases are always records in a well-formed non-dependent class.
5118     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5119 
5120     // Ignore direct virtual bases.
5121     if (DirectVirtualBases.count(RT))
5122       continue;
5123 
5124     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5125     // If our base class is invalid, we probably can't get its dtor anyway.
5126     if (BaseClassDecl->isInvalidDecl())
5127       continue;
5128     if (BaseClassDecl->hasIrrelevantDestructor())
5129       continue;
5130 
5131     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5132     assert(Dtor && "No dtor found for BaseClassDecl!");
5133     if (CheckDestructorAccess(
5134             ClassDecl->getLocation(), Dtor,
5135             PDiag(diag::err_access_dtor_vbase)
5136                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5137             Context.getTypeDeclType(ClassDecl)) ==
5138         AR_accessible) {
5139       CheckDerivedToBaseConversion(
5140           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5141           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5142           SourceRange(), DeclarationName(), nullptr);
5143     }
5144 
5145     MarkFunctionReferenced(Location, Dtor);
5146     DiagnoseUseOfDecl(Dtor, Location);
5147   }
5148 }
5149 
5150 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5151   if (!CDtorDecl)
5152     return;
5153 
5154   if (CXXConstructorDecl *Constructor
5155       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5156     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5157     DiagnoseUninitializedFields(*this, Constructor);
5158   }
5159 }
5160 
5161 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5162   if (!getLangOpts().CPlusPlus)
5163     return false;
5164 
5165   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5166   if (!RD)
5167     return false;
5168 
5169   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5170   // class template specialization here, but doing so breaks a lot of code.
5171 
5172   // We can't answer whether something is abstract until it has a
5173   // definition. If it's currently being defined, we'll walk back
5174   // over all the declarations when we have a full definition.
5175   const CXXRecordDecl *Def = RD->getDefinition();
5176   if (!Def || Def->isBeingDefined())
5177     return false;
5178 
5179   return RD->isAbstract();
5180 }
5181 
5182 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5183                                   TypeDiagnoser &Diagnoser) {
5184   if (!isAbstractType(Loc, T))
5185     return false;
5186 
5187   T = Context.getBaseElementType(T);
5188   Diagnoser.diagnose(*this, Loc, T);
5189   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5190   return true;
5191 }
5192 
5193 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5194   // Check if we've already emitted the list of pure virtual functions
5195   // for this class.
5196   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5197     return;
5198 
5199   // If the diagnostic is suppressed, don't emit the notes. We're only
5200   // going to emit them once, so try to attach them to a diagnostic we're
5201   // actually going to show.
5202   if (Diags.isLastDiagnosticIgnored())
5203     return;
5204 
5205   CXXFinalOverriderMap FinalOverriders;
5206   RD->getFinalOverriders(FinalOverriders);
5207 
5208   // Keep a set of seen pure methods so we won't diagnose the same method
5209   // more than once.
5210   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5211 
5212   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5213                                    MEnd = FinalOverriders.end();
5214        M != MEnd;
5215        ++M) {
5216     for (OverridingMethods::iterator SO = M->second.begin(),
5217                                   SOEnd = M->second.end();
5218          SO != SOEnd; ++SO) {
5219       // C++ [class.abstract]p4:
5220       //   A class is abstract if it contains or inherits at least one
5221       //   pure virtual function for which the final overrider is pure
5222       //   virtual.
5223 
5224       //
5225       if (SO->second.size() != 1)
5226         continue;
5227 
5228       if (!SO->second.front().Method->isPure())
5229         continue;
5230 
5231       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5232         continue;
5233 
5234       Diag(SO->second.front().Method->getLocation(),
5235            diag::note_pure_virtual_function)
5236         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5237     }
5238   }
5239 
5240   if (!PureVirtualClassDiagSet)
5241     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5242   PureVirtualClassDiagSet->insert(RD);
5243 }
5244 
5245 namespace {
5246 struct AbstractUsageInfo {
5247   Sema &S;
5248   CXXRecordDecl *Record;
5249   CanQualType AbstractType;
5250   bool Invalid;
5251 
5252   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5253     : S(S), Record(Record),
5254       AbstractType(S.Context.getCanonicalType(
5255                    S.Context.getTypeDeclType(Record))),
5256       Invalid(false) {}
5257 
5258   void DiagnoseAbstractType() {
5259     if (Invalid) return;
5260     S.DiagnoseAbstractType(Record);
5261     Invalid = true;
5262   }
5263 
5264   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5265 };
5266 
5267 struct CheckAbstractUsage {
5268   AbstractUsageInfo &Info;
5269   const NamedDecl *Ctx;
5270 
5271   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5272     : Info(Info), Ctx(Ctx) {}
5273 
5274   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5275     switch (TL.getTypeLocClass()) {
5276 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5277 #define TYPELOC(CLASS, PARENT) \
5278     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5279 #include "clang/AST/TypeLocNodes.def"
5280     }
5281   }
5282 
5283   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5284     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5285     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5286       if (!TL.getParam(I))
5287         continue;
5288 
5289       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5290       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5291     }
5292   }
5293 
5294   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5295     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5296   }
5297 
5298   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5299     // Visit the type parameters from a permissive context.
5300     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5301       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5302       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5303         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5304           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5305       // TODO: other template argument types?
5306     }
5307   }
5308 
5309   // Visit pointee types from a permissive context.
5310 #define CheckPolymorphic(Type) \
5311   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5312     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5313   }
5314   CheckPolymorphic(PointerTypeLoc)
5315   CheckPolymorphic(ReferenceTypeLoc)
5316   CheckPolymorphic(MemberPointerTypeLoc)
5317   CheckPolymorphic(BlockPointerTypeLoc)
5318   CheckPolymorphic(AtomicTypeLoc)
5319 
5320   /// Handle all the types we haven't given a more specific
5321   /// implementation for above.
5322   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5323     // Every other kind of type that we haven't called out already
5324     // that has an inner type is either (1) sugar or (2) contains that
5325     // inner type in some way as a subobject.
5326     if (TypeLoc Next = TL.getNextTypeLoc())
5327       return Visit(Next, Sel);
5328 
5329     // If there's no inner type and we're in a permissive context,
5330     // don't diagnose.
5331     if (Sel == Sema::AbstractNone) return;
5332 
5333     // Check whether the type matches the abstract type.
5334     QualType T = TL.getType();
5335     if (T->isArrayType()) {
5336       Sel = Sema::AbstractArrayType;
5337       T = Info.S.Context.getBaseElementType(T);
5338     }
5339     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5340     if (CT != Info.AbstractType) return;
5341 
5342     // It matched; do some magic.
5343     if (Sel == Sema::AbstractArrayType) {
5344       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5345         << T << TL.getSourceRange();
5346     } else {
5347       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5348         << Sel << T << TL.getSourceRange();
5349     }
5350     Info.DiagnoseAbstractType();
5351   }
5352 };
5353 
5354 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5355                                   Sema::AbstractDiagSelID Sel) {
5356   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5357 }
5358 
5359 }
5360 
5361 /// Check for invalid uses of an abstract type in a method declaration.
5362 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5363                                     CXXMethodDecl *MD) {
5364   // No need to do the check on definitions, which require that
5365   // the return/param types be complete.
5366   if (MD->doesThisDeclarationHaveABody())
5367     return;
5368 
5369   // For safety's sake, just ignore it if we don't have type source
5370   // information.  This should never happen for non-implicit methods,
5371   // but...
5372   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5373     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5374 }
5375 
5376 /// Check for invalid uses of an abstract type within a class definition.
5377 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5378                                     CXXRecordDecl *RD) {
5379   for (auto *D : RD->decls()) {
5380     if (D->isImplicit()) continue;
5381 
5382     // Methods and method templates.
5383     if (isa<CXXMethodDecl>(D)) {
5384       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5385     } else if (isa<FunctionTemplateDecl>(D)) {
5386       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5387       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5388 
5389     // Fields and static variables.
5390     } else if (isa<FieldDecl>(D)) {
5391       FieldDecl *FD = cast<FieldDecl>(D);
5392       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5393         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5394     } else if (isa<VarDecl>(D)) {
5395       VarDecl *VD = cast<VarDecl>(D);
5396       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5397         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5398 
5399     // Nested classes and class templates.
5400     } else if (isa<CXXRecordDecl>(D)) {
5401       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5402     } else if (isa<ClassTemplateDecl>(D)) {
5403       CheckAbstractClassUsage(Info,
5404                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5405     }
5406   }
5407 }
5408 
5409 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5410   Attr *ClassAttr = getDLLAttr(Class);
5411   if (!ClassAttr)
5412     return;
5413 
5414   assert(ClassAttr->getKind() == attr::DLLExport);
5415 
5416   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5417 
5418   if (TSK == TSK_ExplicitInstantiationDeclaration)
5419     // Don't go any further if this is just an explicit instantiation
5420     // declaration.
5421     return;
5422 
5423   for (Decl *Member : Class->decls()) {
5424     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5425     if (!MD)
5426       continue;
5427 
5428     if (Member->getAttr<DLLExportAttr>()) {
5429       if (MD->isUserProvided()) {
5430         // Instantiate non-default class member functions ...
5431 
5432         // .. except for certain kinds of template specializations.
5433         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5434           continue;
5435 
5436         S.MarkFunctionReferenced(Class->getLocation(), MD);
5437 
5438         // The function will be passed to the consumer when its definition is
5439         // encountered.
5440       } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5441                  MD->isCopyAssignmentOperator() ||
5442                  MD->isMoveAssignmentOperator()) {
5443         // Synthesize and instantiate non-trivial implicit methods, explicitly
5444         // defaulted methods, and the copy and move assignment operators. The
5445         // latter are exported even if they are trivial, because the address of
5446         // an operator can be taken and should compare equal accross libraries.
5447         DiagnosticErrorTrap Trap(S.Diags);
5448         S.MarkFunctionReferenced(Class->getLocation(), MD);
5449         if (Trap.hasErrorOccurred()) {
5450           S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5451               << Class->getName() << !S.getLangOpts().CPlusPlus11;
5452           break;
5453         }
5454 
5455         // There is no later point when we will see the definition of this
5456         // function, so pass it to the consumer now.
5457         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5458       }
5459     }
5460   }
5461 }
5462 
5463 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5464                                                         CXXRecordDecl *Class) {
5465   // Only the MS ABI has default constructor closures, so we don't need to do
5466   // this semantic checking anywhere else.
5467   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5468     return;
5469 
5470   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5471   for (Decl *Member : Class->decls()) {
5472     // Look for exported default constructors.
5473     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5474     if (!CD || !CD->isDefaultConstructor())
5475       continue;
5476     auto *Attr = CD->getAttr<DLLExportAttr>();
5477     if (!Attr)
5478       continue;
5479 
5480     // If the class is non-dependent, mark the default arguments as ODR-used so
5481     // that we can properly codegen the constructor closure.
5482     if (!Class->isDependentContext()) {
5483       for (ParmVarDecl *PD : CD->parameters()) {
5484         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5485         S.DiscardCleanupsInEvaluationContext();
5486       }
5487     }
5488 
5489     if (LastExportedDefaultCtor) {
5490       S.Diag(LastExportedDefaultCtor->getLocation(),
5491              diag::err_attribute_dll_ambiguous_default_ctor)
5492           << Class;
5493       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5494           << CD->getDeclName();
5495       return;
5496     }
5497     LastExportedDefaultCtor = CD;
5498   }
5499 }
5500 
5501 /// \brief Check class-level dllimport/dllexport attribute.
5502 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5503   Attr *ClassAttr = getDLLAttr(Class);
5504 
5505   // MSVC inherits DLL attributes to partial class template specializations.
5506   if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5507     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5508       if (Attr *TemplateAttr =
5509               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5510         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5511         A->setInherited(true);
5512         ClassAttr = A;
5513       }
5514     }
5515   }
5516 
5517   if (!ClassAttr)
5518     return;
5519 
5520   if (!Class->isExternallyVisible()) {
5521     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5522         << Class << ClassAttr;
5523     return;
5524   }
5525 
5526   if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5527       !ClassAttr->isInherited()) {
5528     // Diagnose dll attributes on members of class with dll attribute.
5529     for (Decl *Member : Class->decls()) {
5530       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5531         continue;
5532       InheritableAttr *MemberAttr = getDLLAttr(Member);
5533       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5534         continue;
5535 
5536       Diag(MemberAttr->getLocation(),
5537              diag::err_attribute_dll_member_of_dll_class)
5538           << MemberAttr << ClassAttr;
5539       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5540       Member->setInvalidDecl();
5541     }
5542   }
5543 
5544   if (Class->getDescribedClassTemplate())
5545     // Don't inherit dll attribute until the template is instantiated.
5546     return;
5547 
5548   // The class is either imported or exported.
5549   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5550 
5551   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5552 
5553   // Ignore explicit dllexport on explicit class template instantiation declarations.
5554   if (ClassExported && !ClassAttr->isInherited() &&
5555       TSK == TSK_ExplicitInstantiationDeclaration) {
5556     Class->dropAttr<DLLExportAttr>();
5557     return;
5558   }
5559 
5560   // Force declaration of implicit members so they can inherit the attribute.
5561   ForceDeclarationOfImplicitMembers(Class);
5562 
5563   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5564   // seem to be true in practice?
5565 
5566   for (Decl *Member : Class->decls()) {
5567     VarDecl *VD = dyn_cast<VarDecl>(Member);
5568     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5569 
5570     // Only methods and static fields inherit the attributes.
5571     if (!VD && !MD)
5572       continue;
5573 
5574     if (MD) {
5575       // Don't process deleted methods.
5576       if (MD->isDeleted())
5577         continue;
5578 
5579       if (MD->isInlined()) {
5580         // MinGW does not import or export inline methods.
5581         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5582             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5583           continue;
5584 
5585         // MSVC versions before 2015 don't export the move assignment operators
5586         // and move constructor, so don't attempt to import/export them if
5587         // we have a definition.
5588         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5589         if ((MD->isMoveAssignmentOperator() ||
5590              (Ctor && Ctor->isMoveConstructor())) &&
5591             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5592           continue;
5593 
5594         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5595         // operator is exported anyway.
5596         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5597             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5598           continue;
5599       }
5600     }
5601 
5602     if (!cast<NamedDecl>(Member)->isExternallyVisible())
5603       continue;
5604 
5605     if (!getDLLAttr(Member)) {
5606       auto *NewAttr =
5607           cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5608       NewAttr->setInherited(true);
5609       Member->addAttr(NewAttr);
5610     }
5611   }
5612 
5613   if (ClassExported)
5614     DelayedDllExportClasses.push_back(Class);
5615 }
5616 
5617 /// \brief Perform propagation of DLL attributes from a derived class to a
5618 /// templated base class for MS compatibility.
5619 void Sema::propagateDLLAttrToBaseClassTemplate(
5620     CXXRecordDecl *Class, Attr *ClassAttr,
5621     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5622   if (getDLLAttr(
5623           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5624     // If the base class template has a DLL attribute, don't try to change it.
5625     return;
5626   }
5627 
5628   auto TSK = BaseTemplateSpec->getSpecializationKind();
5629   if (!getDLLAttr(BaseTemplateSpec) &&
5630       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5631        TSK == TSK_ImplicitInstantiation)) {
5632     // The template hasn't been instantiated yet (or it has, but only as an
5633     // explicit instantiation declaration or implicit instantiation, which means
5634     // we haven't codegenned any members yet), so propagate the attribute.
5635     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5636     NewAttr->setInherited(true);
5637     BaseTemplateSpec->addAttr(NewAttr);
5638 
5639     // If the template is already instantiated, checkDLLAttributeRedeclaration()
5640     // needs to be run again to work see the new attribute. Otherwise this will
5641     // get run whenever the template is instantiated.
5642     if (TSK != TSK_Undeclared)
5643       checkClassLevelDLLAttribute(BaseTemplateSpec);
5644 
5645     return;
5646   }
5647 
5648   if (getDLLAttr(BaseTemplateSpec)) {
5649     // The template has already been specialized or instantiated with an
5650     // attribute, explicitly or through propagation. We should not try to change
5651     // it.
5652     return;
5653   }
5654 
5655   // The template was previously instantiated or explicitly specialized without
5656   // a dll attribute, It's too late for us to add an attribute, so warn that
5657   // this is unsupported.
5658   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5659       << BaseTemplateSpec->isExplicitSpecialization();
5660   Diag(ClassAttr->getLocation(), diag::note_attribute);
5661   if (BaseTemplateSpec->isExplicitSpecialization()) {
5662     Diag(BaseTemplateSpec->getLocation(),
5663            diag::note_template_class_explicit_specialization_was_here)
5664         << BaseTemplateSpec;
5665   } else {
5666     Diag(BaseTemplateSpec->getPointOfInstantiation(),
5667            diag::note_template_class_instantiation_was_here)
5668         << BaseTemplateSpec;
5669   }
5670 }
5671 
5672 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5673                                         SourceLocation DefaultLoc) {
5674   switch (S.getSpecialMember(MD)) {
5675   case Sema::CXXDefaultConstructor:
5676     S.DefineImplicitDefaultConstructor(DefaultLoc,
5677                                        cast<CXXConstructorDecl>(MD));
5678     break;
5679   case Sema::CXXCopyConstructor:
5680     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5681     break;
5682   case Sema::CXXCopyAssignment:
5683     S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5684     break;
5685   case Sema::CXXDestructor:
5686     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5687     break;
5688   case Sema::CXXMoveConstructor:
5689     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5690     break;
5691   case Sema::CXXMoveAssignment:
5692     S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5693     break;
5694   case Sema::CXXInvalid:
5695     llvm_unreachable("Invalid special member.");
5696   }
5697 }
5698 
5699 /// \brief Perform semantic checks on a class definition that has been
5700 /// completing, introducing implicitly-declared members, checking for
5701 /// abstract types, etc.
5702 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5703   if (!Record)
5704     return;
5705 
5706   if (Record->isAbstract() && !Record->isInvalidDecl()) {
5707     AbstractUsageInfo Info(*this, Record);
5708     CheckAbstractClassUsage(Info, Record);
5709   }
5710 
5711   // If this is not an aggregate type and has no user-declared constructor,
5712   // complain about any non-static data members of reference or const scalar
5713   // type, since they will never get initializers.
5714   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5715       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5716       !Record->isLambda()) {
5717     bool Complained = false;
5718     for (const auto *F : Record->fields()) {
5719       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5720         continue;
5721 
5722       if (F->getType()->isReferenceType() ||
5723           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5724         if (!Complained) {
5725           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5726             << Record->getTagKind() << Record;
5727           Complained = true;
5728         }
5729 
5730         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5731           << F->getType()->isReferenceType()
5732           << F->getDeclName();
5733       }
5734     }
5735   }
5736 
5737   if (Record->getIdentifier()) {
5738     // C++ [class.mem]p13:
5739     //   If T is the name of a class, then each of the following shall have a
5740     //   name different from T:
5741     //     - every member of every anonymous union that is a member of class T.
5742     //
5743     // C++ [class.mem]p14:
5744     //   In addition, if class T has a user-declared constructor (12.1), every
5745     //   non-static data member of class T shall have a name different from T.
5746     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5747     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5748          ++I) {
5749       NamedDecl *D = *I;
5750       if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5751           isa<IndirectFieldDecl>(D)) {
5752         Diag(D->getLocation(), diag::err_member_name_of_class)
5753           << D->getDeclName();
5754         break;
5755       }
5756     }
5757   }
5758 
5759   // Warn if the class has virtual methods but non-virtual public destructor.
5760   if (Record->isPolymorphic() && !Record->isDependentType()) {
5761     CXXDestructorDecl *dtor = Record->getDestructor();
5762     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5763         !Record->hasAttr<FinalAttr>())
5764       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5765            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5766   }
5767 
5768   if (Record->isAbstract()) {
5769     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5770       Diag(Record->getLocation(), diag::warn_abstract_final_class)
5771         << FA->isSpelledAsSealed();
5772       DiagnoseAbstractType(Record);
5773     }
5774   }
5775 
5776   bool HasMethodWithOverrideControl = false,
5777        HasOverridingMethodWithoutOverrideControl = false;
5778   if (!Record->isDependentType()) {
5779     for (auto *M : Record->methods()) {
5780       // See if a method overloads virtual methods in a base
5781       // class without overriding any.
5782       if (!M->isStatic())
5783         DiagnoseHiddenVirtualMethods(M);
5784       if (M->hasAttr<OverrideAttr>())
5785         HasMethodWithOverrideControl = true;
5786       else if (M->size_overridden_methods() > 0)
5787         HasOverridingMethodWithoutOverrideControl = true;
5788       // Check whether the explicitly-defaulted special members are valid.
5789       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5790         CheckExplicitlyDefaultedSpecialMember(M);
5791 
5792       // For an explicitly defaulted or deleted special member, we defer
5793       // determining triviality until the class is complete. That time is now!
5794       CXXSpecialMember CSM = getSpecialMember(M);
5795       if (!M->isImplicit() && !M->isUserProvided()) {
5796         if (CSM != CXXInvalid) {
5797           M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5798 
5799           // Inform the class that we've finished declaring this member.
5800           Record->finishedDefaultedOrDeletedMember(M);
5801         }
5802       }
5803 
5804       if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5805           M->hasAttr<DLLExportAttr>()) {
5806         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5807             M->isTrivial() &&
5808             (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5809              CSM == CXXDestructor))
5810           M->dropAttr<DLLExportAttr>();
5811 
5812         if (M->hasAttr<DLLExportAttr>()) {
5813           DefineImplicitSpecialMember(*this, M, M->getLocation());
5814           ActOnFinishInlineFunctionDef(M);
5815         }
5816       }
5817     }
5818   }
5819 
5820   if (HasMethodWithOverrideControl &&
5821       HasOverridingMethodWithoutOverrideControl) {
5822     // At least one method has the 'override' control declared.
5823     // Diagnose all other overridden methods which do not have 'override' specified on them.
5824     for (auto *M : Record->methods())
5825       DiagnoseAbsenceOfOverrideControl(M);
5826   }
5827 
5828   // ms_struct is a request to use the same ABI rules as MSVC.  Check
5829   // whether this class uses any C++ features that are implemented
5830   // completely differently in MSVC, and if so, emit a diagnostic.
5831   // That diagnostic defaults to an error, but we allow projects to
5832   // map it down to a warning (or ignore it).  It's a fairly common
5833   // practice among users of the ms_struct pragma to mass-annotate
5834   // headers, sweeping up a bunch of types that the project doesn't
5835   // really rely on MSVC-compatible layout for.  We must therefore
5836   // support "ms_struct except for C++ stuff" as a secondary ABI.
5837   if (Record->isMsStruct(Context) &&
5838       (Record->isPolymorphic() || Record->getNumBases())) {
5839     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5840   }
5841 
5842   checkClassLevelDLLAttribute(Record);
5843 }
5844 
5845 /// Look up the special member function that would be called by a special
5846 /// member function for a subobject of class type.
5847 ///
5848 /// \param Class The class type of the subobject.
5849 /// \param CSM The kind of special member function.
5850 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5851 /// \param ConstRHS True if this is a copy operation with a const object
5852 ///        on its RHS, that is, if the argument to the outer special member
5853 ///        function is 'const' and this is not a field marked 'mutable'.
5854 static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
5855     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5856     unsigned FieldQuals, bool ConstRHS) {
5857   unsigned LHSQuals = 0;
5858   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5859     LHSQuals = FieldQuals;
5860 
5861   unsigned RHSQuals = FieldQuals;
5862   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5863     RHSQuals = 0;
5864   else if (ConstRHS)
5865     RHSQuals |= Qualifiers::Const;
5866 
5867   return S.LookupSpecialMember(Class, CSM,
5868                                RHSQuals & Qualifiers::Const,
5869                                RHSQuals & Qualifiers::Volatile,
5870                                false,
5871                                LHSQuals & Qualifiers::Const,
5872                                LHSQuals & Qualifiers::Volatile);
5873 }
5874 
5875 class Sema::InheritedConstructorInfo {
5876   Sema &S;
5877   SourceLocation UseLoc;
5878 
5879   /// A mapping from the base classes through which the constructor was
5880   /// inherited to the using shadow declaration in that base class (or a null
5881   /// pointer if the constructor was declared in that base class).
5882   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5883       InheritedFromBases;
5884 
5885 public:
5886   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5887                            ConstructorUsingShadowDecl *Shadow)
5888       : S(S), UseLoc(UseLoc) {
5889     bool DiagnosedMultipleConstructedBases = false;
5890     CXXRecordDecl *ConstructedBase = nullptr;
5891     UsingDecl *ConstructedBaseUsing = nullptr;
5892 
5893     // Find the set of such base class subobjects and check that there's a
5894     // unique constructed subobject.
5895     for (auto *D : Shadow->redecls()) {
5896       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5897       auto *DNominatedBase = DShadow->getNominatedBaseClass();
5898       auto *DConstructedBase = DShadow->getConstructedBaseClass();
5899 
5900       InheritedFromBases.insert(
5901           std::make_pair(DNominatedBase->getCanonicalDecl(),
5902                          DShadow->getNominatedBaseClassShadowDecl()));
5903       if (DShadow->constructsVirtualBase())
5904         InheritedFromBases.insert(
5905             std::make_pair(DConstructedBase->getCanonicalDecl(),
5906                            DShadow->getConstructedBaseClassShadowDecl()));
5907       else
5908         assert(DNominatedBase == DConstructedBase);
5909 
5910       // [class.inhctor.init]p2:
5911       //   If the constructor was inherited from multiple base class subobjects
5912       //   of type B, the program is ill-formed.
5913       if (!ConstructedBase) {
5914         ConstructedBase = DConstructedBase;
5915         ConstructedBaseUsing = D->getUsingDecl();
5916       } else if (ConstructedBase != DConstructedBase &&
5917                  !Shadow->isInvalidDecl()) {
5918         if (!DiagnosedMultipleConstructedBases) {
5919           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5920               << Shadow->getTargetDecl();
5921           S.Diag(ConstructedBaseUsing->getLocation(),
5922                diag::note_ambiguous_inherited_constructor_using)
5923               << ConstructedBase;
5924           DiagnosedMultipleConstructedBases = true;
5925         }
5926         S.Diag(D->getUsingDecl()->getLocation(),
5927                diag::note_ambiguous_inherited_constructor_using)
5928             << DConstructedBase;
5929       }
5930     }
5931 
5932     if (DiagnosedMultipleConstructedBases)
5933       Shadow->setInvalidDecl();
5934   }
5935 
5936   /// Find the constructor to use for inherited construction of a base class,
5937   /// and whether that base class constructor inherits the constructor from a
5938   /// virtual base class (in which case it won't actually invoke it).
5939   std::pair<CXXConstructorDecl *, bool>
5940   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5941     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5942     if (It == InheritedFromBases.end())
5943       return std::make_pair(nullptr, false);
5944 
5945     // This is an intermediary class.
5946     if (It->second)
5947       return std::make_pair(
5948           S.findInheritingConstructor(UseLoc, Ctor, It->second),
5949           It->second->constructsVirtualBase());
5950 
5951     // This is the base class from which the constructor was inherited.
5952     return std::make_pair(Ctor, false);
5953   }
5954 };
5955 
5956 /// Is the special member function which would be selected to perform the
5957 /// specified operation on the specified class type a constexpr constructor?
5958 static bool
5959 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5960                          Sema::CXXSpecialMember CSM, unsigned Quals,
5961                          bool ConstRHS,
5962                          CXXConstructorDecl *InheritedCtor = nullptr,
5963                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
5964   // If we're inheriting a constructor, see if we need to call it for this base
5965   // class.
5966   if (InheritedCtor) {
5967     assert(CSM == Sema::CXXDefaultConstructor);
5968     auto BaseCtor =
5969         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5970     if (BaseCtor)
5971       return BaseCtor->isConstexpr();
5972   }
5973 
5974   if (CSM == Sema::CXXDefaultConstructor)
5975     return ClassDecl->hasConstexprDefaultConstructor();
5976 
5977   Sema::SpecialMemberOverloadResult *SMOR =
5978       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
5979   if (!SMOR || !SMOR->getMethod())
5980     // A constructor we wouldn't select can't be "involved in initializing"
5981     // anything.
5982     return true;
5983   return SMOR->getMethod()->isConstexpr();
5984 }
5985 
5986 /// Determine whether the specified special member function would be constexpr
5987 /// if it were implicitly defined.
5988 static bool defaultedSpecialMemberIsConstexpr(
5989     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
5990     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
5991     Sema::InheritedConstructorInfo *Inherited = nullptr) {
5992   if (!S.getLangOpts().CPlusPlus11)
5993     return false;
5994 
5995   // C++11 [dcl.constexpr]p4:
5996   // In the definition of a constexpr constructor [...]
5997   bool Ctor = true;
5998   switch (CSM) {
5999   case Sema::CXXDefaultConstructor:
6000     if (Inherited)
6001       break;
6002     // Since default constructor lookup is essentially trivial (and cannot
6003     // involve, for instance, template instantiation), we compute whether a
6004     // defaulted default constructor is constexpr directly within CXXRecordDecl.
6005     //
6006     // This is important for performance; we need to know whether the default
6007     // constructor is constexpr to determine whether the type is a literal type.
6008     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6009 
6010   case Sema::CXXCopyConstructor:
6011   case Sema::CXXMoveConstructor:
6012     // For copy or move constructors, we need to perform overload resolution.
6013     break;
6014 
6015   case Sema::CXXCopyAssignment:
6016   case Sema::CXXMoveAssignment:
6017     if (!S.getLangOpts().CPlusPlus14)
6018       return false;
6019     // In C++1y, we need to perform overload resolution.
6020     Ctor = false;
6021     break;
6022 
6023   case Sema::CXXDestructor:
6024   case Sema::CXXInvalid:
6025     return false;
6026   }
6027 
6028   //   -- if the class is a non-empty union, or for each non-empty anonymous
6029   //      union member of a non-union class, exactly one non-static data member
6030   //      shall be initialized; [DR1359]
6031   //
6032   // If we squint, this is guaranteed, since exactly one non-static data member
6033   // will be initialized (if the constructor isn't deleted), we just don't know
6034   // which one.
6035   if (Ctor && ClassDecl->isUnion())
6036     return CSM == Sema::CXXDefaultConstructor
6037                ? ClassDecl->hasInClassInitializer() ||
6038                      !ClassDecl->hasVariantMembers()
6039                : true;
6040 
6041   //   -- the class shall not have any virtual base classes;
6042   if (Ctor && ClassDecl->getNumVBases())
6043     return false;
6044 
6045   // C++1y [class.copy]p26:
6046   //   -- [the class] is a literal type, and
6047   if (!Ctor && !ClassDecl->isLiteral())
6048     return false;
6049 
6050   //   -- every constructor involved in initializing [...] base class
6051   //      sub-objects shall be a constexpr constructor;
6052   //   -- the assignment operator selected to copy/move each direct base
6053   //      class is a constexpr function, and
6054   for (const auto &B : ClassDecl->bases()) {
6055     const RecordType *BaseType = B.getType()->getAs<RecordType>();
6056     if (!BaseType) continue;
6057 
6058     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6059     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6060                                   InheritedCtor, Inherited))
6061       return false;
6062   }
6063 
6064   //   -- every constructor involved in initializing non-static data members
6065   //      [...] shall be a constexpr constructor;
6066   //   -- every non-static data member and base class sub-object shall be
6067   //      initialized
6068   //   -- for each non-static data member of X that is of class type (or array
6069   //      thereof), the assignment operator selected to copy/move that member is
6070   //      a constexpr function
6071   for (const auto *F : ClassDecl->fields()) {
6072     if (F->isInvalidDecl())
6073       continue;
6074     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6075       continue;
6076     QualType BaseType = S.Context.getBaseElementType(F->getType());
6077     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6078       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6079       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6080                                     BaseType.getCVRQualifiers(),
6081                                     ConstArg && !F->isMutable()))
6082         return false;
6083     } else if (CSM == Sema::CXXDefaultConstructor) {
6084       return false;
6085     }
6086   }
6087 
6088   // All OK, it's constexpr!
6089   return true;
6090 }
6091 
6092 static Sema::ImplicitExceptionSpecification
6093 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6094   switch (S.getSpecialMember(MD)) {
6095   case Sema::CXXDefaultConstructor:
6096     return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
6097   case Sema::CXXCopyConstructor:
6098     return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
6099   case Sema::CXXCopyAssignment:
6100     return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
6101   case Sema::CXXMoveConstructor:
6102     return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
6103   case Sema::CXXMoveAssignment:
6104     return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
6105   case Sema::CXXDestructor:
6106     return S.ComputeDefaultedDtorExceptionSpec(MD);
6107   case Sema::CXXInvalid:
6108     break;
6109   }
6110   assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
6111          "only special members have implicit exception specs");
6112   return S.ComputeInheritingCtorExceptionSpec(Loc,
6113                                               cast<CXXConstructorDecl>(MD));
6114 }
6115 
6116 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6117                                                             CXXMethodDecl *MD) {
6118   FunctionProtoType::ExtProtoInfo EPI;
6119 
6120   // Build an exception specification pointing back at this member.
6121   EPI.ExceptionSpec.Type = EST_Unevaluated;
6122   EPI.ExceptionSpec.SourceDecl = MD;
6123 
6124   // Set the calling convention to the default for C++ instance methods.
6125   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6126       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6127                                             /*IsCXXMethod=*/true));
6128   return EPI;
6129 }
6130 
6131 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6132   const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6133   if (FPT->getExceptionSpecType() != EST_Unevaluated)
6134     return;
6135 
6136   // Evaluate the exception specification.
6137   auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6138   auto ESI = IES.getExceptionSpec();
6139 
6140   // Update the type of the special member to use it.
6141   UpdateExceptionSpec(MD, ESI);
6142 
6143   // A user-provided destructor can be defined outside the class. When that
6144   // happens, be sure to update the exception specification on both
6145   // declarations.
6146   const FunctionProtoType *CanonicalFPT =
6147     MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6148   if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6149     UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6150 }
6151 
6152 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6153   CXXRecordDecl *RD = MD->getParent();
6154   CXXSpecialMember CSM = getSpecialMember(MD);
6155 
6156   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6157          "not an explicitly-defaulted special member");
6158 
6159   // Whether this was the first-declared instance of the constructor.
6160   // This affects whether we implicitly add an exception spec and constexpr.
6161   bool First = MD == MD->getCanonicalDecl();
6162 
6163   bool HadError = false;
6164 
6165   // C++11 [dcl.fct.def.default]p1:
6166   //   A function that is explicitly defaulted shall
6167   //     -- be a special member function (checked elsewhere),
6168   //     -- have the same type (except for ref-qualifiers, and except that a
6169   //        copy operation can take a non-const reference) as an implicit
6170   //        declaration, and
6171   //     -- not have default arguments.
6172   unsigned ExpectedParams = 1;
6173   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6174     ExpectedParams = 0;
6175   if (MD->getNumParams() != ExpectedParams) {
6176     // This also checks for default arguments: a copy or move constructor with a
6177     // default argument is classified as a default constructor, and assignment
6178     // operations and destructors can't have default arguments.
6179     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6180       << CSM << MD->getSourceRange();
6181     HadError = true;
6182   } else if (MD->isVariadic()) {
6183     Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6184       << CSM << MD->getSourceRange();
6185     HadError = true;
6186   }
6187 
6188   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6189 
6190   bool CanHaveConstParam = false;
6191   if (CSM == CXXCopyConstructor)
6192     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6193   else if (CSM == CXXCopyAssignment)
6194     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6195 
6196   QualType ReturnType = Context.VoidTy;
6197   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6198     // Check for return type matching.
6199     ReturnType = Type->getReturnType();
6200     QualType ExpectedReturnType =
6201         Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6202     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6203       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6204         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6205       HadError = true;
6206     }
6207 
6208     // A defaulted special member cannot have cv-qualifiers.
6209     if (Type->getTypeQuals()) {
6210       Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6211         << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6212       HadError = true;
6213     }
6214   }
6215 
6216   // Check for parameter type matching.
6217   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6218   bool HasConstParam = false;
6219   if (ExpectedParams && ArgType->isReferenceType()) {
6220     // Argument must be reference to possibly-const T.
6221     QualType ReferentType = ArgType->getPointeeType();
6222     HasConstParam = ReferentType.isConstQualified();
6223 
6224     if (ReferentType.isVolatileQualified()) {
6225       Diag(MD->getLocation(),
6226            diag::err_defaulted_special_member_volatile_param) << CSM;
6227       HadError = true;
6228     }
6229 
6230     if (HasConstParam && !CanHaveConstParam) {
6231       if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6232         Diag(MD->getLocation(),
6233              diag::err_defaulted_special_member_copy_const_param)
6234           << (CSM == CXXCopyAssignment);
6235         // FIXME: Explain why this special member can't be const.
6236       } else {
6237         Diag(MD->getLocation(),
6238              diag::err_defaulted_special_member_move_const_param)
6239           << (CSM == CXXMoveAssignment);
6240       }
6241       HadError = true;
6242     }
6243   } else if (ExpectedParams) {
6244     // A copy assignment operator can take its argument by value, but a
6245     // defaulted one cannot.
6246     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6247     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6248     HadError = true;
6249   }
6250 
6251   // C++11 [dcl.fct.def.default]p2:
6252   //   An explicitly-defaulted function may be declared constexpr only if it
6253   //   would have been implicitly declared as constexpr,
6254   // Do not apply this rule to members of class templates, since core issue 1358
6255   // makes such functions always instantiate to constexpr functions. For
6256   // functions which cannot be constexpr (for non-constructors in C++11 and for
6257   // destructors in C++1y), this is checked elsewhere.
6258   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6259                                                      HasConstParam);
6260   if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6261                                  : isa<CXXConstructorDecl>(MD)) &&
6262       MD->isConstexpr() && !Constexpr &&
6263       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6264     Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6265     // FIXME: Explain why the special member can't be constexpr.
6266     HadError = true;
6267   }
6268 
6269   //   and may have an explicit exception-specification only if it is compatible
6270   //   with the exception-specification on the implicit declaration.
6271   if (Type->hasExceptionSpec()) {
6272     // Delay the check if this is the first declaration of the special member,
6273     // since we may not have parsed some necessary in-class initializers yet.
6274     if (First) {
6275       // If the exception specification needs to be instantiated, do so now,
6276       // before we clobber it with an EST_Unevaluated specification below.
6277       if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6278         InstantiateExceptionSpec(MD->getLocStart(), MD);
6279         Type = MD->getType()->getAs<FunctionProtoType>();
6280       }
6281       DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6282     } else
6283       CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6284   }
6285 
6286   //   If a function is explicitly defaulted on its first declaration,
6287   if (First) {
6288     //  -- it is implicitly considered to be constexpr if the implicit
6289     //     definition would be,
6290     MD->setConstexpr(Constexpr);
6291 
6292     //  -- it is implicitly considered to have the same exception-specification
6293     //     as if it had been implicitly declared,
6294     FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6295     EPI.ExceptionSpec.Type = EST_Unevaluated;
6296     EPI.ExceptionSpec.SourceDecl = MD;
6297     MD->setType(Context.getFunctionType(ReturnType,
6298                                         llvm::makeArrayRef(&ArgType,
6299                                                            ExpectedParams),
6300                                         EPI));
6301   }
6302 
6303   if (ShouldDeleteSpecialMember(MD, CSM)) {
6304     if (First) {
6305       SetDeclDeleted(MD, MD->getLocation());
6306     } else {
6307       // C++11 [dcl.fct.def.default]p4:
6308       //   [For a] user-provided explicitly-defaulted function [...] if such a
6309       //   function is implicitly defined as deleted, the program is ill-formed.
6310       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6311       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6312       HadError = true;
6313     }
6314   }
6315 
6316   if (HadError)
6317     MD->setInvalidDecl();
6318 }
6319 
6320 /// Check whether the exception specification provided for an
6321 /// explicitly-defaulted special member matches the exception specification
6322 /// that would have been generated for an implicit special member, per
6323 /// C++11 [dcl.fct.def.default]p2.
6324 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6325     CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6326   // If the exception specification was explicitly specified but hadn't been
6327   // parsed when the method was defaulted, grab it now.
6328   if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6329     SpecifiedType =
6330         MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6331 
6332   // Compute the implicit exception specification.
6333   CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6334                                                        /*IsCXXMethod=*/true);
6335   FunctionProtoType::ExtProtoInfo EPI(CC);
6336   auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6337   EPI.ExceptionSpec = IES.getExceptionSpec();
6338   const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6339     Context.getFunctionType(Context.VoidTy, None, EPI));
6340 
6341   // Ensure that it matches.
6342   CheckEquivalentExceptionSpec(
6343     PDiag(diag::err_incorrect_defaulted_exception_spec)
6344       << getSpecialMember(MD), PDiag(),
6345     ImplicitType, SourceLocation(),
6346     SpecifiedType, MD->getLocation());
6347 }
6348 
6349 void Sema::CheckDelayedMemberExceptionSpecs() {
6350   decltype(DelayedExceptionSpecChecks) Checks;
6351   decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6352 
6353   std::swap(Checks, DelayedExceptionSpecChecks);
6354   std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6355 
6356   // Perform any deferred checking of exception specifications for virtual
6357   // destructors.
6358   for (auto &Check : Checks)
6359     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6360 
6361   // Check that any explicitly-defaulted methods have exception specifications
6362   // compatible with their implicit exception specifications.
6363   for (auto &Spec : Specs)
6364     CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6365 }
6366 
6367 namespace {
6368 struct SpecialMemberDeletionInfo {
6369   Sema &S;
6370   CXXMethodDecl *MD;
6371   Sema::CXXSpecialMember CSM;
6372   Sema::InheritedConstructorInfo *ICI;
6373   bool Diagnose;
6374 
6375   // Properties of the special member, computed for convenience.
6376   bool IsConstructor, IsAssignment, IsMove, ConstArg;
6377   SourceLocation Loc;
6378 
6379   bool AllFieldsAreConst;
6380 
6381   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6382                             Sema::CXXSpecialMember CSM,
6383                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6384       : S(S), MD(MD), CSM(CSM), ICI(ICI), Diagnose(Diagnose),
6385         IsConstructor(false), IsAssignment(false), IsMove(false),
6386         ConstArg(false), Loc(MD->getLocation()), AllFieldsAreConst(true) {
6387     switch (CSM) {
6388       case Sema::CXXDefaultConstructor:
6389       case Sema::CXXCopyConstructor:
6390         IsConstructor = true;
6391         break;
6392       case Sema::CXXMoveConstructor:
6393         IsConstructor = true;
6394         IsMove = true;
6395         break;
6396       case Sema::CXXCopyAssignment:
6397         IsAssignment = true;
6398         break;
6399       case Sema::CXXMoveAssignment:
6400         IsAssignment = true;
6401         IsMove = true;
6402         break;
6403       case Sema::CXXDestructor:
6404         break;
6405       case Sema::CXXInvalid:
6406         llvm_unreachable("invalid special member kind");
6407     }
6408 
6409     if (MD->getNumParams()) {
6410       if (const ReferenceType *RT =
6411               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6412         ConstArg = RT->getPointeeType().isConstQualified();
6413     }
6414   }
6415 
6416   bool inUnion() const { return MD->getParent()->isUnion(); }
6417 
6418   Sema::CXXSpecialMember getEffectiveCSM() {
6419     return ICI ? Sema::CXXInvalid : CSM;
6420   }
6421 
6422   /// Look up the corresponding special member in the given class.
6423   Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
6424                                               unsigned Quals, bool IsMutable) {
6425     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6426                                        ConstArg && !IsMutable);
6427   }
6428 
6429   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6430 
6431   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6432   bool shouldDeleteForField(FieldDecl *FD);
6433   bool shouldDeleteForAllConstMembers();
6434 
6435   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6436                                      unsigned Quals);
6437   bool shouldDeleteForSubobjectCall(Subobject Subobj,
6438                                     Sema::SpecialMemberOverloadResult *SMOR,
6439                                     bool IsDtorCallInCtor);
6440 
6441   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6442 };
6443 }
6444 
6445 /// Is the given special member inaccessible when used on the given
6446 /// sub-object.
6447 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6448                                              CXXMethodDecl *target) {
6449   /// If we're operating on a base class, the object type is the
6450   /// type of this special member.
6451   QualType objectTy;
6452   AccessSpecifier access = target->getAccess();
6453   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6454     objectTy = S.Context.getTypeDeclType(MD->getParent());
6455     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6456 
6457   // If we're operating on a field, the object type is the type of the field.
6458   } else {
6459     objectTy = S.Context.getTypeDeclType(target->getParent());
6460   }
6461 
6462   return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6463 }
6464 
6465 /// Check whether we should delete a special member due to the implicit
6466 /// definition containing a call to a special member of a subobject.
6467 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6468     Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
6469     bool IsDtorCallInCtor) {
6470   CXXMethodDecl *Decl = SMOR->getMethod();
6471   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6472 
6473   int DiagKind = -1;
6474 
6475   if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6476     DiagKind = !Decl ? 0 : 1;
6477   else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6478     DiagKind = 2;
6479   else if (!isAccessible(Subobj, Decl))
6480     DiagKind = 3;
6481   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6482            !Decl->isTrivial()) {
6483     // A member of a union must have a trivial corresponding special member.
6484     // As a weird special case, a destructor call from a union's constructor
6485     // must be accessible and non-deleted, but need not be trivial. Such a
6486     // destructor is never actually called, but is semantically checked as
6487     // if it were.
6488     DiagKind = 4;
6489   }
6490 
6491   if (DiagKind == -1)
6492     return false;
6493 
6494   if (Diagnose) {
6495     if (Field) {
6496       S.Diag(Field->getLocation(),
6497              diag::note_deleted_special_member_class_subobject)
6498         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6499         << Field << DiagKind << IsDtorCallInCtor;
6500     } else {
6501       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6502       S.Diag(Base->getLocStart(),
6503              diag::note_deleted_special_member_class_subobject)
6504         << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6505         << Base->getType() << DiagKind << IsDtorCallInCtor;
6506     }
6507 
6508     if (DiagKind == 1)
6509       S.NoteDeletedFunction(Decl);
6510     // FIXME: Explain inaccessibility if DiagKind == 3.
6511   }
6512 
6513   return true;
6514 }
6515 
6516 /// Check whether we should delete a special member function due to having a
6517 /// direct or virtual base class or non-static data member of class type M.
6518 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6519     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6520   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6521   bool IsMutable = Field && Field->isMutable();
6522 
6523   // C++11 [class.ctor]p5:
6524   // -- any direct or virtual base class, or non-static data member with no
6525   //    brace-or-equal-initializer, has class type M (or array thereof) and
6526   //    either M has no default constructor or overload resolution as applied
6527   //    to M's default constructor results in an ambiguity or in a function
6528   //    that is deleted or inaccessible
6529   // C++11 [class.copy]p11, C++11 [class.copy]p23:
6530   // -- a direct or virtual base class B that cannot be copied/moved because
6531   //    overload resolution, as applied to B's corresponding special member,
6532   //    results in an ambiguity or a function that is deleted or inaccessible
6533   //    from the defaulted special member
6534   // C++11 [class.dtor]p5:
6535   // -- any direct or virtual base class [...] has a type with a destructor
6536   //    that is deleted or inaccessible
6537   if (!(CSM == Sema::CXXDefaultConstructor &&
6538         Field && Field->hasInClassInitializer()) &&
6539       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6540                                    false))
6541     return true;
6542 
6543   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6544   // -- any direct or virtual base class or non-static data member has a
6545   //    type with a destructor that is deleted or inaccessible
6546   if (IsConstructor) {
6547     Sema::SpecialMemberOverloadResult *SMOR =
6548         S.LookupSpecialMember(Class, Sema::CXXDestructor,
6549                               false, false, false, false, false);
6550     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6551       return true;
6552   }
6553 
6554   return false;
6555 }
6556 
6557 /// Check whether we should delete a special member function due to the class
6558 /// having a particular direct or virtual base class.
6559 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6560   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6561   // If program is correct, BaseClass cannot be null, but if it is, the error
6562   // must be reported elsewhere.
6563   if (!BaseClass)
6564     return false;
6565   // If we have an inheriting constructor, check whether we're calling an
6566   // inherited constructor instead of a default constructor.
6567   if (ICI) {
6568     assert(CSM == Sema::CXXDefaultConstructor);
6569     auto *BaseCtor =
6570         ICI->findConstructorForBase(BaseClass, cast<CXXConstructorDecl>(MD)
6571                                                    ->getInheritedConstructor()
6572                                                    .getConstructor())
6573             .first;
6574     if (BaseCtor) {
6575       if (BaseCtor->isDeleted() && Diagnose) {
6576         S.Diag(Base->getLocStart(),
6577                diag::note_deleted_special_member_class_subobject)
6578           << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6579           << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6580         S.NoteDeletedFunction(BaseCtor);
6581       }
6582       return BaseCtor->isDeleted();
6583     }
6584   }
6585   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6586 }
6587 
6588 /// Check whether we should delete a special member function due to the class
6589 /// having a particular non-static data member.
6590 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6591   QualType FieldType = S.Context.getBaseElementType(FD->getType());
6592   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6593 
6594   if (CSM == Sema::CXXDefaultConstructor) {
6595     // For a default constructor, all references must be initialized in-class
6596     // and, if a union, it must have a non-const member.
6597     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6598       if (Diagnose)
6599         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6600           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6601       return true;
6602     }
6603     // C++11 [class.ctor]p5: any non-variant non-static data member of
6604     // const-qualified type (or array thereof) with no
6605     // brace-or-equal-initializer does not have a user-provided default
6606     // constructor.
6607     if (!inUnion() && FieldType.isConstQualified() &&
6608         !FD->hasInClassInitializer() &&
6609         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6610       if (Diagnose)
6611         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6612           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6613       return true;
6614     }
6615 
6616     if (inUnion() && !FieldType.isConstQualified())
6617       AllFieldsAreConst = false;
6618   } else if (CSM == Sema::CXXCopyConstructor) {
6619     // For a copy constructor, data members must not be of rvalue reference
6620     // type.
6621     if (FieldType->isRValueReferenceType()) {
6622       if (Diagnose)
6623         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6624           << MD->getParent() << FD << FieldType;
6625       return true;
6626     }
6627   } else if (IsAssignment) {
6628     // For an assignment operator, data members must not be of reference type.
6629     if (FieldType->isReferenceType()) {
6630       if (Diagnose)
6631         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6632           << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
6633       return true;
6634     }
6635     if (!FieldRecord && FieldType.isConstQualified()) {
6636       // C++11 [class.copy]p23:
6637       // -- a non-static data member of const non-class type (or array thereof)
6638       if (Diagnose)
6639         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6640           << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
6641       return true;
6642     }
6643   }
6644 
6645   if (FieldRecord) {
6646     // Some additional restrictions exist on the variant members.
6647     if (!inUnion() && FieldRecord->isUnion() &&
6648         FieldRecord->isAnonymousStructOrUnion()) {
6649       bool AllVariantFieldsAreConst = true;
6650 
6651       // FIXME: Handle anonymous unions declared within anonymous unions.
6652       for (auto *UI : FieldRecord->fields()) {
6653         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6654 
6655         if (!UnionFieldType.isConstQualified())
6656           AllVariantFieldsAreConst = false;
6657 
6658         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6659         if (UnionFieldRecord &&
6660             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6661                                           UnionFieldType.getCVRQualifiers()))
6662           return true;
6663       }
6664 
6665       // At least one member in each anonymous union must be non-const
6666       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6667           !FieldRecord->field_empty()) {
6668         if (Diagnose)
6669           S.Diag(FieldRecord->getLocation(),
6670                  diag::note_deleted_default_ctor_all_const)
6671             << !!ICI << MD->getParent() << /*anonymous union*/1;
6672         return true;
6673       }
6674 
6675       // Don't check the implicit member of the anonymous union type.
6676       // This is technically non-conformant, but sanity demands it.
6677       return false;
6678     }
6679 
6680     if (shouldDeleteForClassSubobject(FieldRecord, FD,
6681                                       FieldType.getCVRQualifiers()))
6682       return true;
6683   }
6684 
6685   return false;
6686 }
6687 
6688 /// C++11 [class.ctor] p5:
6689 ///   A defaulted default constructor for a class X is defined as deleted if
6690 /// X is a union and all of its variant members are of const-qualified type.
6691 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6692   // This is a silly definition, because it gives an empty union a deleted
6693   // default constructor. Don't do that.
6694   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6695     bool AnyFields = false;
6696     for (auto *F : MD->getParent()->fields())
6697       if ((AnyFields = !F->isUnnamedBitfield()))
6698         break;
6699     if (!AnyFields)
6700       return false;
6701     if (Diagnose)
6702       S.Diag(MD->getParent()->getLocation(),
6703              diag::note_deleted_default_ctor_all_const)
6704         << !!ICI << MD->getParent() << /*not anonymous union*/0;
6705     return true;
6706   }
6707   return false;
6708 }
6709 
6710 /// Determine whether a defaulted special member function should be defined as
6711 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6712 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6713 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6714                                      InheritedConstructorInfo *ICI,
6715                                      bool Diagnose) {
6716   if (MD->isInvalidDecl())
6717     return false;
6718   CXXRecordDecl *RD = MD->getParent();
6719   assert(!RD->isDependentType() && "do deletion after instantiation");
6720   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6721     return false;
6722 
6723   // C++11 [expr.lambda.prim]p19:
6724   //   The closure type associated with a lambda-expression has a
6725   //   deleted (8.4.3) default constructor and a deleted copy
6726   //   assignment operator.
6727   if (RD->isLambda() &&
6728       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6729     if (Diagnose)
6730       Diag(RD->getLocation(), diag::note_lambda_decl);
6731     return true;
6732   }
6733 
6734   // For an anonymous struct or union, the copy and assignment special members
6735   // will never be used, so skip the check. For an anonymous union declared at
6736   // namespace scope, the constructor and destructor are used.
6737   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6738       RD->isAnonymousStructOrUnion())
6739     return false;
6740 
6741   // C++11 [class.copy]p7, p18:
6742   //   If the class definition declares a move constructor or move assignment
6743   //   operator, an implicitly declared copy constructor or copy assignment
6744   //   operator is defined as deleted.
6745   if (MD->isImplicit() &&
6746       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6747     CXXMethodDecl *UserDeclaredMove = nullptr;
6748 
6749     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6750     // deletion of the corresponding copy operation, not both copy operations.
6751     // MSVC 2015 has adopted the standards conforming behavior.
6752     bool DeletesOnlyMatchingCopy =
6753         getLangOpts().MSVCCompat &&
6754         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6755 
6756     if (RD->hasUserDeclaredMoveConstructor() &&
6757         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6758       if (!Diagnose) return true;
6759 
6760       // Find any user-declared move constructor.
6761       for (auto *I : RD->ctors()) {
6762         if (I->isMoveConstructor()) {
6763           UserDeclaredMove = I;
6764           break;
6765         }
6766       }
6767       assert(UserDeclaredMove);
6768     } else if (RD->hasUserDeclaredMoveAssignment() &&
6769                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6770       if (!Diagnose) return true;
6771 
6772       // Find any user-declared move assignment operator.
6773       for (auto *I : RD->methods()) {
6774         if (I->isMoveAssignmentOperator()) {
6775           UserDeclaredMove = I;
6776           break;
6777         }
6778       }
6779       assert(UserDeclaredMove);
6780     }
6781 
6782     if (UserDeclaredMove) {
6783       Diag(UserDeclaredMove->getLocation(),
6784            diag::note_deleted_copy_user_declared_move)
6785         << (CSM == CXXCopyAssignment) << RD
6786         << UserDeclaredMove->isMoveAssignmentOperator();
6787       return true;
6788     }
6789   }
6790 
6791   // Do access control from the special member function
6792   ContextRAII MethodContext(*this, MD);
6793 
6794   // C++11 [class.dtor]p5:
6795   // -- for a virtual destructor, lookup of the non-array deallocation function
6796   //    results in an ambiguity or in a function that is deleted or inaccessible
6797   if (CSM == CXXDestructor && MD->isVirtual()) {
6798     FunctionDecl *OperatorDelete = nullptr;
6799     DeclarationName Name =
6800       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6801     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6802                                  OperatorDelete, /*Diagnose*/false)) {
6803       if (Diagnose)
6804         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6805       return true;
6806     }
6807   }
6808 
6809   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6810 
6811   for (auto &BI : RD->bases())
6812     if ((SMI.IsAssignment || !BI.isVirtual()) &&
6813         SMI.shouldDeleteForBase(&BI))
6814       return true;
6815 
6816   // Per DR1611, do not consider virtual bases of constructors of abstract
6817   // classes, since we are not going to construct them. For assignment
6818   // operators, we only assign (and thus only consider) direct bases.
6819   if ((!RD->isAbstract() || !SMI.IsConstructor) && !SMI.IsAssignment) {
6820     for (auto &BI : RD->vbases())
6821       if (SMI.shouldDeleteForBase(&BI))
6822         return true;
6823   }
6824 
6825   for (auto *FI : RD->fields())
6826     if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
6827         SMI.shouldDeleteForField(FI))
6828       return true;
6829 
6830   if (SMI.shouldDeleteForAllConstMembers())
6831     return true;
6832 
6833   if (getLangOpts().CUDA) {
6834     // We should delete the special member in CUDA mode if target inference
6835     // failed.
6836     return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6837                                                    Diagnose);
6838   }
6839 
6840   return false;
6841 }
6842 
6843 /// Perform lookup for a special member of the specified kind, and determine
6844 /// whether it is trivial. If the triviality can be determined without the
6845 /// lookup, skip it. This is intended for use when determining whether a
6846 /// special member of a containing object is trivial, and thus does not ever
6847 /// perform overload resolution for default constructors.
6848 ///
6849 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6850 /// member that was most likely to be intended to be trivial, if any.
6851 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6852                                      Sema::CXXSpecialMember CSM, unsigned Quals,
6853                                      bool ConstRHS, CXXMethodDecl **Selected) {
6854   if (Selected)
6855     *Selected = nullptr;
6856 
6857   switch (CSM) {
6858   case Sema::CXXInvalid:
6859     llvm_unreachable("not a special member");
6860 
6861   case Sema::CXXDefaultConstructor:
6862     // C++11 [class.ctor]p5:
6863     //   A default constructor is trivial if:
6864     //    - all the [direct subobjects] have trivial default constructors
6865     //
6866     // Note, no overload resolution is performed in this case.
6867     if (RD->hasTrivialDefaultConstructor())
6868       return true;
6869 
6870     if (Selected) {
6871       // If there's a default constructor which could have been trivial, dig it
6872       // out. Otherwise, if there's any user-provided default constructor, point
6873       // to that as an example of why there's not a trivial one.
6874       CXXConstructorDecl *DefCtor = nullptr;
6875       if (RD->needsImplicitDefaultConstructor())
6876         S.DeclareImplicitDefaultConstructor(RD);
6877       for (auto *CI : RD->ctors()) {
6878         if (!CI->isDefaultConstructor())
6879           continue;
6880         DefCtor = CI;
6881         if (!DefCtor->isUserProvided())
6882           break;
6883       }
6884 
6885       *Selected = DefCtor;
6886     }
6887 
6888     return false;
6889 
6890   case Sema::CXXDestructor:
6891     // C++11 [class.dtor]p5:
6892     //   A destructor is trivial if:
6893     //    - all the direct [subobjects] have trivial destructors
6894     if (RD->hasTrivialDestructor())
6895       return true;
6896 
6897     if (Selected) {
6898       if (RD->needsImplicitDestructor())
6899         S.DeclareImplicitDestructor(RD);
6900       *Selected = RD->getDestructor();
6901     }
6902 
6903     return false;
6904 
6905   case Sema::CXXCopyConstructor:
6906     // C++11 [class.copy]p12:
6907     //   A copy constructor is trivial if:
6908     //    - the constructor selected to copy each direct [subobject] is trivial
6909     if (RD->hasTrivialCopyConstructor()) {
6910       if (Quals == Qualifiers::Const)
6911         // We must either select the trivial copy constructor or reach an
6912         // ambiguity; no need to actually perform overload resolution.
6913         return true;
6914     } else if (!Selected) {
6915       return false;
6916     }
6917     // In C++98, we are not supposed to perform overload resolution here, but we
6918     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
6919     // cases like B as having a non-trivial copy constructor:
6920     //   struct A { template<typename T> A(T&); };
6921     //   struct B { mutable A a; };
6922     goto NeedOverloadResolution;
6923 
6924   case Sema::CXXCopyAssignment:
6925     // C++11 [class.copy]p25:
6926     //   A copy assignment operator is trivial if:
6927     //    - the assignment operator selected to copy each direct [subobject] is
6928     //      trivial
6929     if (RD->hasTrivialCopyAssignment()) {
6930       if (Quals == Qualifiers::Const)
6931         return true;
6932     } else if (!Selected) {
6933       return false;
6934     }
6935     // In C++98, we are not supposed to perform overload resolution here, but we
6936     // treat that as a language defect.
6937     goto NeedOverloadResolution;
6938 
6939   case Sema::CXXMoveConstructor:
6940   case Sema::CXXMoveAssignment:
6941   NeedOverloadResolution:
6942     Sema::SpecialMemberOverloadResult *SMOR =
6943         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
6944 
6945     // The standard doesn't describe how to behave if the lookup is ambiguous.
6946     // We treat it as not making the member non-trivial, just like the standard
6947     // mandates for the default constructor. This should rarely matter, because
6948     // the member will also be deleted.
6949     if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6950       return true;
6951 
6952     if (!SMOR->getMethod()) {
6953       assert(SMOR->getKind() ==
6954              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
6955       return false;
6956     }
6957 
6958     // We deliberately don't check if we found a deleted special member. We're
6959     // not supposed to!
6960     if (Selected)
6961       *Selected = SMOR->getMethod();
6962     return SMOR->getMethod()->isTrivial();
6963   }
6964 
6965   llvm_unreachable("unknown special method kind");
6966 }
6967 
6968 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
6969   for (auto *CI : RD->ctors())
6970     if (!CI->isImplicit())
6971       return CI;
6972 
6973   // Look for constructor templates.
6974   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
6975   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
6976     if (CXXConstructorDecl *CD =
6977           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
6978       return CD;
6979   }
6980 
6981   return nullptr;
6982 }
6983 
6984 /// The kind of subobject we are checking for triviality. The values of this
6985 /// enumeration are used in diagnostics.
6986 enum TrivialSubobjectKind {
6987   /// The subobject is a base class.
6988   TSK_BaseClass,
6989   /// The subobject is a non-static data member.
6990   TSK_Field,
6991   /// The object is actually the complete object.
6992   TSK_CompleteObject
6993 };
6994 
6995 /// Check whether the special member selected for a given type would be trivial.
6996 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
6997                                       QualType SubType, bool ConstRHS,
6998                                       Sema::CXXSpecialMember CSM,
6999                                       TrivialSubobjectKind Kind,
7000                                       bool Diagnose) {
7001   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7002   if (!SubRD)
7003     return true;
7004 
7005   CXXMethodDecl *Selected;
7006   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7007                                ConstRHS, Diagnose ? &Selected : nullptr))
7008     return true;
7009 
7010   if (Diagnose) {
7011     if (ConstRHS)
7012       SubType.addConst();
7013 
7014     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7015       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7016         << Kind << SubType.getUnqualifiedType();
7017       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7018         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7019     } else if (!Selected)
7020       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7021         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7022     else if (Selected->isUserProvided()) {
7023       if (Kind == TSK_CompleteObject)
7024         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7025           << Kind << SubType.getUnqualifiedType() << CSM;
7026       else {
7027         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7028           << Kind << SubType.getUnqualifiedType() << CSM;
7029         S.Diag(Selected->getLocation(), diag::note_declared_at);
7030       }
7031     } else {
7032       if (Kind != TSK_CompleteObject)
7033         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7034           << Kind << SubType.getUnqualifiedType() << CSM;
7035 
7036       // Explain why the defaulted or deleted special member isn't trivial.
7037       S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7038     }
7039   }
7040 
7041   return false;
7042 }
7043 
7044 /// Check whether the members of a class type allow a special member to be
7045 /// trivial.
7046 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7047                                      Sema::CXXSpecialMember CSM,
7048                                      bool ConstArg, bool Diagnose) {
7049   for (const auto *FI : RD->fields()) {
7050     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7051       continue;
7052 
7053     QualType FieldType = S.Context.getBaseElementType(FI->getType());
7054 
7055     // Pretend anonymous struct or union members are members of this class.
7056     if (FI->isAnonymousStructOrUnion()) {
7057       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7058                                     CSM, ConstArg, Diagnose))
7059         return false;
7060       continue;
7061     }
7062 
7063     // C++11 [class.ctor]p5:
7064     //   A default constructor is trivial if [...]
7065     //    -- no non-static data member of its class has a
7066     //       brace-or-equal-initializer
7067     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7068       if (Diagnose)
7069         S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7070       return false;
7071     }
7072 
7073     // Objective C ARC 4.3.5:
7074     //   [...] nontrivally ownership-qualified types are [...] not trivially
7075     //   default constructible, copy constructible, move constructible, copy
7076     //   assignable, move assignable, or destructible [...]
7077     if (S.getLangOpts().ObjCAutoRefCount &&
7078         FieldType.hasNonTrivialObjCLifetime()) {
7079       if (Diagnose)
7080         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7081           << RD << FieldType.getObjCLifetime();
7082       return false;
7083     }
7084 
7085     bool ConstRHS = ConstArg && !FI->isMutable();
7086     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7087                                    CSM, TSK_Field, Diagnose))
7088       return false;
7089   }
7090 
7091   return true;
7092 }
7093 
7094 /// Diagnose why the specified class does not have a trivial special member of
7095 /// the given kind.
7096 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7097   QualType Ty = Context.getRecordType(RD);
7098 
7099   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7100   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7101                             TSK_CompleteObject, /*Diagnose*/true);
7102 }
7103 
7104 /// Determine whether a defaulted or deleted special member function is trivial,
7105 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7106 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7107 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7108                                   bool Diagnose) {
7109   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7110 
7111   CXXRecordDecl *RD = MD->getParent();
7112 
7113   bool ConstArg = false;
7114 
7115   // C++11 [class.copy]p12, p25: [DR1593]
7116   //   A [special member] is trivial if [...] its parameter-type-list is
7117   //   equivalent to the parameter-type-list of an implicit declaration [...]
7118   switch (CSM) {
7119   case CXXDefaultConstructor:
7120   case CXXDestructor:
7121     // Trivial default constructors and destructors cannot have parameters.
7122     break;
7123 
7124   case CXXCopyConstructor:
7125   case CXXCopyAssignment: {
7126     // Trivial copy operations always have const, non-volatile parameter types.
7127     ConstArg = true;
7128     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7129     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7130     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7131       if (Diagnose)
7132         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7133           << Param0->getSourceRange() << Param0->getType()
7134           << Context.getLValueReferenceType(
7135                Context.getRecordType(RD).withConst());
7136       return false;
7137     }
7138     break;
7139   }
7140 
7141   case CXXMoveConstructor:
7142   case CXXMoveAssignment: {
7143     // Trivial move operations always have non-cv-qualified parameters.
7144     const ParmVarDecl *Param0 = MD->getParamDecl(0);
7145     const RValueReferenceType *RT =
7146       Param0->getType()->getAs<RValueReferenceType>();
7147     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7148       if (Diagnose)
7149         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7150           << Param0->getSourceRange() << Param0->getType()
7151           << Context.getRValueReferenceType(Context.getRecordType(RD));
7152       return false;
7153     }
7154     break;
7155   }
7156 
7157   case CXXInvalid:
7158     llvm_unreachable("not a special member");
7159   }
7160 
7161   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7162     if (Diagnose)
7163       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7164            diag::note_nontrivial_default_arg)
7165         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7166     return false;
7167   }
7168   if (MD->isVariadic()) {
7169     if (Diagnose)
7170       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7171     return false;
7172   }
7173 
7174   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7175   //   A copy/move [constructor or assignment operator] is trivial if
7176   //    -- the [member] selected to copy/move each direct base class subobject
7177   //       is trivial
7178   //
7179   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7180   //   A [default constructor or destructor] is trivial if
7181   //    -- all the direct base classes have trivial [default constructors or
7182   //       destructors]
7183   for (const auto &BI : RD->bases())
7184     if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7185                                    ConstArg, CSM, TSK_BaseClass, Diagnose))
7186       return false;
7187 
7188   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7189   //   A copy/move [constructor or assignment operator] for a class X is
7190   //   trivial if
7191   //    -- for each non-static data member of X that is of class type (or array
7192   //       thereof), the constructor selected to copy/move that member is
7193   //       trivial
7194   //
7195   // C++11 [class.copy]p12, C++11 [class.copy]p25:
7196   //   A [default constructor or destructor] is trivial if
7197   //    -- for all of the non-static data members of its class that are of class
7198   //       type (or array thereof), each such class has a trivial [default
7199   //       constructor or destructor]
7200   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7201     return false;
7202 
7203   // C++11 [class.dtor]p5:
7204   //   A destructor is trivial if [...]
7205   //    -- the destructor is not virtual
7206   if (CSM == CXXDestructor && MD->isVirtual()) {
7207     if (Diagnose)
7208       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7209     return false;
7210   }
7211 
7212   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7213   //   A [special member] for class X is trivial if [...]
7214   //    -- class X has no virtual functions and no virtual base classes
7215   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7216     if (!Diagnose)
7217       return false;
7218 
7219     if (RD->getNumVBases()) {
7220       // Check for virtual bases. We already know that the corresponding
7221       // member in all bases is trivial, so vbases must all be direct.
7222       CXXBaseSpecifier &BS = *RD->vbases_begin();
7223       assert(BS.isVirtual());
7224       Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7225       return false;
7226     }
7227 
7228     // Must have a virtual method.
7229     for (const auto *MI : RD->methods()) {
7230       if (MI->isVirtual()) {
7231         SourceLocation MLoc = MI->getLocStart();
7232         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7233         return false;
7234       }
7235     }
7236 
7237     llvm_unreachable("dynamic class with no vbases and no virtual functions");
7238   }
7239 
7240   // Looks like it's trivial!
7241   return true;
7242 }
7243 
7244 namespace {
7245 struct FindHiddenVirtualMethod {
7246   Sema *S;
7247   CXXMethodDecl *Method;
7248   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7249   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7250 
7251 private:
7252   /// Check whether any most overriden method from MD in Methods
7253   static bool CheckMostOverridenMethods(
7254       const CXXMethodDecl *MD,
7255       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7256     if (MD->size_overridden_methods() == 0)
7257       return Methods.count(MD->getCanonicalDecl());
7258     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7259                                         E = MD->end_overridden_methods();
7260          I != E; ++I)
7261       if (CheckMostOverridenMethods(*I, Methods))
7262         return true;
7263     return false;
7264   }
7265 
7266 public:
7267   /// Member lookup function that determines whether a given C++
7268   /// method overloads virtual methods in a base class without overriding any,
7269   /// to be used with CXXRecordDecl::lookupInBases().
7270   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7271     RecordDecl *BaseRecord =
7272         Specifier->getType()->getAs<RecordType>()->getDecl();
7273 
7274     DeclarationName Name = Method->getDeclName();
7275     assert(Name.getNameKind() == DeclarationName::Identifier);
7276 
7277     bool foundSameNameMethod = false;
7278     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7279     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7280          Path.Decls = Path.Decls.slice(1)) {
7281       NamedDecl *D = Path.Decls.front();
7282       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7283         MD = MD->getCanonicalDecl();
7284         foundSameNameMethod = true;
7285         // Interested only in hidden virtual methods.
7286         if (!MD->isVirtual())
7287           continue;
7288         // If the method we are checking overrides a method from its base
7289         // don't warn about the other overloaded methods. Clang deviates from
7290         // GCC by only diagnosing overloads of inherited virtual functions that
7291         // do not override any other virtual functions in the base. GCC's
7292         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7293         // function from a base class. These cases may be better served by a
7294         // warning (not specific to virtual functions) on call sites when the
7295         // call would select a different function from the base class, were it
7296         // visible.
7297         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7298         if (!S->IsOverload(Method, MD, false))
7299           return true;
7300         // Collect the overload only if its hidden.
7301         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7302           overloadedMethods.push_back(MD);
7303       }
7304     }
7305 
7306     if (foundSameNameMethod)
7307       OverloadedMethods.append(overloadedMethods.begin(),
7308                                overloadedMethods.end());
7309     return foundSameNameMethod;
7310   }
7311 };
7312 } // end anonymous namespace
7313 
7314 /// \brief Add the most overriden methods from MD to Methods
7315 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7316                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7317   if (MD->size_overridden_methods() == 0)
7318     Methods.insert(MD->getCanonicalDecl());
7319   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7320                                       E = MD->end_overridden_methods();
7321        I != E; ++I)
7322     AddMostOverridenMethods(*I, Methods);
7323 }
7324 
7325 /// \brief Check if a method overloads virtual methods in a base class without
7326 /// overriding any.
7327 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7328                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7329   if (!MD->getDeclName().isIdentifier())
7330     return;
7331 
7332   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7333                      /*bool RecordPaths=*/false,
7334                      /*bool DetectVirtual=*/false);
7335   FindHiddenVirtualMethod FHVM;
7336   FHVM.Method = MD;
7337   FHVM.S = this;
7338 
7339   // Keep the base methods that were overriden or introduced in the subclass
7340   // by 'using' in a set. A base method not in this set is hidden.
7341   CXXRecordDecl *DC = MD->getParent();
7342   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7343   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7344     NamedDecl *ND = *I;
7345     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7346       ND = shad->getTargetDecl();
7347     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7348       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7349   }
7350 
7351   if (DC->lookupInBases(FHVM, Paths))
7352     OverloadedMethods = FHVM.OverloadedMethods;
7353 }
7354 
7355 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7356                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7357   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7358     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7359     PartialDiagnostic PD = PDiag(
7360          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7361     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7362     Diag(overloadedMD->getLocation(), PD);
7363   }
7364 }
7365 
7366 /// \brief Diagnose methods which overload virtual methods in a base class
7367 /// without overriding any.
7368 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7369   if (MD->isInvalidDecl())
7370     return;
7371 
7372   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7373     return;
7374 
7375   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7376   FindHiddenVirtualMethods(MD, OverloadedMethods);
7377   if (!OverloadedMethods.empty()) {
7378     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7379       << MD << (OverloadedMethods.size() > 1);
7380 
7381     NoteHiddenVirtualMethods(MD, OverloadedMethods);
7382   }
7383 }
7384 
7385 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7386                                              Decl *TagDecl,
7387                                              SourceLocation LBrac,
7388                                              SourceLocation RBrac,
7389                                              AttributeList *AttrList) {
7390   if (!TagDecl)
7391     return;
7392 
7393   AdjustDeclIfTemplate(TagDecl);
7394 
7395   for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7396     if (l->getKind() != AttributeList::AT_Visibility)
7397       continue;
7398     l->setInvalid();
7399     Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7400       l->getName();
7401   }
7402 
7403   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7404               // strict aliasing violation!
7405               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7406               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7407 
7408   CheckCompletedCXXClass(
7409                         dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7410 }
7411 
7412 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7413 /// special functions, such as the default constructor, copy
7414 /// constructor, or destructor, to the given C++ class (C++
7415 /// [special]p1).  This routine can only be executed just before the
7416 /// definition of the class is complete.
7417 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7418   if (ClassDecl->needsImplicitDefaultConstructor()) {
7419     ++ASTContext::NumImplicitDefaultConstructors;
7420 
7421     if (ClassDecl->hasInheritedConstructor())
7422       DeclareImplicitDefaultConstructor(ClassDecl);
7423   }
7424 
7425   if (ClassDecl->needsImplicitCopyConstructor()) {
7426     ++ASTContext::NumImplicitCopyConstructors;
7427 
7428     // If the properties or semantics of the copy constructor couldn't be
7429     // determined while the class was being declared, force a declaration
7430     // of it now.
7431     if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7432         ClassDecl->hasInheritedConstructor())
7433       DeclareImplicitCopyConstructor(ClassDecl);
7434     // For the MS ABI we need to know whether the copy ctor is deleted. A
7435     // prerequisite for deleting the implicit copy ctor is that the class has a
7436     // move ctor or move assignment that is either user-declared or whose
7437     // semantics are inherited from a subobject. FIXME: We should provide a more
7438     // direct way for CodeGen to ask whether the constructor was deleted.
7439     else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7440              (ClassDecl->hasUserDeclaredMoveConstructor() ||
7441               ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7442               ClassDecl->hasUserDeclaredMoveAssignment() ||
7443               ClassDecl->needsOverloadResolutionForMoveAssignment()))
7444       DeclareImplicitCopyConstructor(ClassDecl);
7445   }
7446 
7447   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7448     ++ASTContext::NumImplicitMoveConstructors;
7449 
7450     if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7451         ClassDecl->hasInheritedConstructor())
7452       DeclareImplicitMoveConstructor(ClassDecl);
7453   }
7454 
7455   if (ClassDecl->needsImplicitCopyAssignment()) {
7456     ++ASTContext::NumImplicitCopyAssignmentOperators;
7457 
7458     // If we have a dynamic class, then the copy assignment operator may be
7459     // virtual, so we have to declare it immediately. This ensures that, e.g.,
7460     // it shows up in the right place in the vtable and that we diagnose
7461     // problems with the implicit exception specification.
7462     if (ClassDecl->isDynamicClass() ||
7463         ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7464         ClassDecl->hasInheritedAssignment())
7465       DeclareImplicitCopyAssignment(ClassDecl);
7466   }
7467 
7468   if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7469     ++ASTContext::NumImplicitMoveAssignmentOperators;
7470 
7471     // Likewise for the move assignment operator.
7472     if (ClassDecl->isDynamicClass() ||
7473         ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7474         ClassDecl->hasInheritedAssignment())
7475       DeclareImplicitMoveAssignment(ClassDecl);
7476   }
7477 
7478   if (ClassDecl->needsImplicitDestructor()) {
7479     ++ASTContext::NumImplicitDestructors;
7480 
7481     // If we have a dynamic class, then the destructor may be virtual, so we
7482     // have to declare the destructor immediately. This ensures that, e.g., it
7483     // shows up in the right place in the vtable and that we diagnose problems
7484     // with the implicit exception specification.
7485     if (ClassDecl->isDynamicClass() ||
7486         ClassDecl->needsOverloadResolutionForDestructor())
7487       DeclareImplicitDestructor(ClassDecl);
7488   }
7489 }
7490 
7491 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7492   if (!D)
7493     return 0;
7494 
7495   // The order of template parameters is not important here. All names
7496   // get added to the same scope.
7497   SmallVector<TemplateParameterList *, 4> ParameterLists;
7498 
7499   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7500     D = TD->getTemplatedDecl();
7501 
7502   if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7503     ParameterLists.push_back(PSD->getTemplateParameters());
7504 
7505   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7506     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7507       ParameterLists.push_back(DD->getTemplateParameterList(i));
7508 
7509     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7510       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7511         ParameterLists.push_back(FTD->getTemplateParameters());
7512     }
7513   }
7514 
7515   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7516     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7517       ParameterLists.push_back(TD->getTemplateParameterList(i));
7518 
7519     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7520       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7521         ParameterLists.push_back(CTD->getTemplateParameters());
7522     }
7523   }
7524 
7525   unsigned Count = 0;
7526   for (TemplateParameterList *Params : ParameterLists) {
7527     if (Params->size() > 0)
7528       // Ignore explicit specializations; they don't contribute to the template
7529       // depth.
7530       ++Count;
7531     for (NamedDecl *Param : *Params) {
7532       if (Param->getDeclName()) {
7533         S->AddDecl(Param);
7534         IdResolver.AddDecl(Param);
7535       }
7536     }
7537   }
7538 
7539   return Count;
7540 }
7541 
7542 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7543   if (!RecordD) return;
7544   AdjustDeclIfTemplate(RecordD);
7545   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7546   PushDeclContext(S, Record);
7547 }
7548 
7549 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7550   if (!RecordD) return;
7551   PopDeclContext();
7552 }
7553 
7554 /// This is used to implement the constant expression evaluation part of the
7555 /// attribute enable_if extension. There is nothing in standard C++ which would
7556 /// require reentering parameters.
7557 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7558   if (!Param)
7559     return;
7560 
7561   S->AddDecl(Param);
7562   if (Param->getDeclName())
7563     IdResolver.AddDecl(Param);
7564 }
7565 
7566 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7567 /// parsing a top-level (non-nested) C++ class, and we are now
7568 /// parsing those parts of the given Method declaration that could
7569 /// not be parsed earlier (C++ [class.mem]p2), such as default
7570 /// arguments. This action should enter the scope of the given
7571 /// Method declaration as if we had just parsed the qualified method
7572 /// name. However, it should not bring the parameters into scope;
7573 /// that will be performed by ActOnDelayedCXXMethodParameter.
7574 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7575 }
7576 
7577 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7578 /// C++ method declaration. We're (re-)introducing the given
7579 /// function parameter into scope for use in parsing later parts of
7580 /// the method declaration. For example, we could see an
7581 /// ActOnParamDefaultArgument event for this parameter.
7582 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7583   if (!ParamD)
7584     return;
7585 
7586   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7587 
7588   // If this parameter has an unparsed default argument, clear it out
7589   // to make way for the parsed default argument.
7590   if (Param->hasUnparsedDefaultArg())
7591     Param->setDefaultArg(nullptr);
7592 
7593   S->AddDecl(Param);
7594   if (Param->getDeclName())
7595     IdResolver.AddDecl(Param);
7596 }
7597 
7598 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7599 /// processing the delayed method declaration for Method. The method
7600 /// declaration is now considered finished. There may be a separate
7601 /// ActOnStartOfFunctionDef action later (not necessarily
7602 /// immediately!) for this method, if it was also defined inside the
7603 /// class body.
7604 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7605   if (!MethodD)
7606     return;
7607 
7608   AdjustDeclIfTemplate(MethodD);
7609 
7610   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7611 
7612   // Now that we have our default arguments, check the constructor
7613   // again. It could produce additional diagnostics or affect whether
7614   // the class has implicitly-declared destructors, among other
7615   // things.
7616   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7617     CheckConstructor(Constructor);
7618 
7619   // Check the default arguments, which we may have added.
7620   if (!Method->isInvalidDecl())
7621     CheckCXXDefaultArguments(Method);
7622 }
7623 
7624 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7625 /// the well-formedness of the constructor declarator @p D with type @p
7626 /// R. If there are any errors in the declarator, this routine will
7627 /// emit diagnostics and set the invalid bit to true.  In any case, the type
7628 /// will be updated to reflect a well-formed type for the constructor and
7629 /// returned.
7630 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7631                                           StorageClass &SC) {
7632   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7633 
7634   // C++ [class.ctor]p3:
7635   //   A constructor shall not be virtual (10.3) or static (9.4). A
7636   //   constructor can be invoked for a const, volatile or const
7637   //   volatile object. A constructor shall not be declared const,
7638   //   volatile, or const volatile (9.3.2).
7639   if (isVirtual) {
7640     if (!D.isInvalidType())
7641       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7642         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7643         << SourceRange(D.getIdentifierLoc());
7644     D.setInvalidType();
7645   }
7646   if (SC == SC_Static) {
7647     if (!D.isInvalidType())
7648       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7649         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7650         << SourceRange(D.getIdentifierLoc());
7651     D.setInvalidType();
7652     SC = SC_None;
7653   }
7654 
7655   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7656     diagnoseIgnoredQualifiers(
7657         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7658         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7659         D.getDeclSpec().getRestrictSpecLoc(),
7660         D.getDeclSpec().getAtomicSpecLoc());
7661     D.setInvalidType();
7662   }
7663 
7664   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7665   if (FTI.TypeQuals != 0) {
7666     if (FTI.TypeQuals & Qualifiers::Const)
7667       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7668         << "const" << SourceRange(D.getIdentifierLoc());
7669     if (FTI.TypeQuals & Qualifiers::Volatile)
7670       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7671         << "volatile" << SourceRange(D.getIdentifierLoc());
7672     if (FTI.TypeQuals & Qualifiers::Restrict)
7673       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7674         << "restrict" << SourceRange(D.getIdentifierLoc());
7675     D.setInvalidType();
7676   }
7677 
7678   // C++0x [class.ctor]p4:
7679   //   A constructor shall not be declared with a ref-qualifier.
7680   if (FTI.hasRefQualifier()) {
7681     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7682       << FTI.RefQualifierIsLValueRef
7683       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7684     D.setInvalidType();
7685   }
7686 
7687   // Rebuild the function type "R" without any type qualifiers (in
7688   // case any of the errors above fired) and with "void" as the
7689   // return type, since constructors don't have return types.
7690   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7691   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7692     return R;
7693 
7694   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7695   EPI.TypeQuals = 0;
7696   EPI.RefQualifier = RQ_None;
7697 
7698   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7699 }
7700 
7701 /// CheckConstructor - Checks a fully-formed constructor for
7702 /// well-formedness, issuing any diagnostics required. Returns true if
7703 /// the constructor declarator is invalid.
7704 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7705   CXXRecordDecl *ClassDecl
7706     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7707   if (!ClassDecl)
7708     return Constructor->setInvalidDecl();
7709 
7710   // C++ [class.copy]p3:
7711   //   A declaration of a constructor for a class X is ill-formed if
7712   //   its first parameter is of type (optionally cv-qualified) X and
7713   //   either there are no other parameters or else all other
7714   //   parameters have default arguments.
7715   if (!Constructor->isInvalidDecl() &&
7716       ((Constructor->getNumParams() == 1) ||
7717        (Constructor->getNumParams() > 1 &&
7718         Constructor->getParamDecl(1)->hasDefaultArg())) &&
7719       Constructor->getTemplateSpecializationKind()
7720                                               != TSK_ImplicitInstantiation) {
7721     QualType ParamType = Constructor->getParamDecl(0)->getType();
7722     QualType ClassTy = Context.getTagDeclType(ClassDecl);
7723     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7724       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7725       const char *ConstRef
7726         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7727                                                         : " const &";
7728       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7729         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7730 
7731       // FIXME: Rather that making the constructor invalid, we should endeavor
7732       // to fix the type.
7733       Constructor->setInvalidDecl();
7734     }
7735   }
7736 }
7737 
7738 /// CheckDestructor - Checks a fully-formed destructor definition for
7739 /// well-formedness, issuing any diagnostics required.  Returns true
7740 /// on error.
7741 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7742   CXXRecordDecl *RD = Destructor->getParent();
7743 
7744   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7745     SourceLocation Loc;
7746 
7747     if (!Destructor->isImplicit())
7748       Loc = Destructor->getLocation();
7749     else
7750       Loc = RD->getLocation();
7751 
7752     // If we have a virtual destructor, look up the deallocation function
7753     if (FunctionDecl *OperatorDelete =
7754             FindDeallocationFunctionForDestructor(Loc, RD)) {
7755       MarkFunctionReferenced(Loc, OperatorDelete);
7756       Destructor->setOperatorDelete(OperatorDelete);
7757     }
7758   }
7759 
7760   return false;
7761 }
7762 
7763 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7764 /// the well-formednes of the destructor declarator @p D with type @p
7765 /// R. If there are any errors in the declarator, this routine will
7766 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
7767 /// will be updated to reflect a well-formed type for the destructor and
7768 /// returned.
7769 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7770                                          StorageClass& SC) {
7771   // C++ [class.dtor]p1:
7772   //   [...] A typedef-name that names a class is a class-name
7773   //   (7.1.3); however, a typedef-name that names a class shall not
7774   //   be used as the identifier in the declarator for a destructor
7775   //   declaration.
7776   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7777   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7778     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7779       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7780   else if (const TemplateSpecializationType *TST =
7781              DeclaratorType->getAs<TemplateSpecializationType>())
7782     if (TST->isTypeAlias())
7783       Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7784         << DeclaratorType << 1;
7785 
7786   // C++ [class.dtor]p2:
7787   //   A destructor is used to destroy objects of its class type. A
7788   //   destructor takes no parameters, and no return type can be
7789   //   specified for it (not even void). The address of a destructor
7790   //   shall not be taken. A destructor shall not be static. A
7791   //   destructor can be invoked for a const, volatile or const
7792   //   volatile object. A destructor shall not be declared const,
7793   //   volatile or const volatile (9.3.2).
7794   if (SC == SC_Static) {
7795     if (!D.isInvalidType())
7796       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7797         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7798         << SourceRange(D.getIdentifierLoc())
7799         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7800 
7801     SC = SC_None;
7802   }
7803   if (!D.isInvalidType()) {
7804     // Destructors don't have return types, but the parser will
7805     // happily parse something like:
7806     //
7807     //   class X {
7808     //     float ~X();
7809     //   };
7810     //
7811     // The return type will be eliminated later.
7812     if (D.getDeclSpec().hasTypeSpecifier())
7813       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7814         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7815         << SourceRange(D.getIdentifierLoc());
7816     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7817       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7818                                 SourceLocation(),
7819                                 D.getDeclSpec().getConstSpecLoc(),
7820                                 D.getDeclSpec().getVolatileSpecLoc(),
7821                                 D.getDeclSpec().getRestrictSpecLoc(),
7822                                 D.getDeclSpec().getAtomicSpecLoc());
7823       D.setInvalidType();
7824     }
7825   }
7826 
7827   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7828   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7829     if (FTI.TypeQuals & Qualifiers::Const)
7830       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7831         << "const" << SourceRange(D.getIdentifierLoc());
7832     if (FTI.TypeQuals & Qualifiers::Volatile)
7833       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7834         << "volatile" << SourceRange(D.getIdentifierLoc());
7835     if (FTI.TypeQuals & Qualifiers::Restrict)
7836       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7837         << "restrict" << SourceRange(D.getIdentifierLoc());
7838     D.setInvalidType();
7839   }
7840 
7841   // C++0x [class.dtor]p2:
7842   //   A destructor shall not be declared with a ref-qualifier.
7843   if (FTI.hasRefQualifier()) {
7844     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7845       << FTI.RefQualifierIsLValueRef
7846       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7847     D.setInvalidType();
7848   }
7849 
7850   // Make sure we don't have any parameters.
7851   if (FTIHasNonVoidParameters(FTI)) {
7852     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7853 
7854     // Delete the parameters.
7855     FTI.freeParams();
7856     D.setInvalidType();
7857   }
7858 
7859   // Make sure the destructor isn't variadic.
7860   if (FTI.isVariadic) {
7861     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7862     D.setInvalidType();
7863   }
7864 
7865   // Rebuild the function type "R" without any type qualifiers or
7866   // parameters (in case any of the errors above fired) and with
7867   // "void" as the return type, since destructors don't have return
7868   // types.
7869   if (!D.isInvalidType())
7870     return R;
7871 
7872   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7873   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7874   EPI.Variadic = false;
7875   EPI.TypeQuals = 0;
7876   EPI.RefQualifier = RQ_None;
7877   return Context.getFunctionType(Context.VoidTy, None, EPI);
7878 }
7879 
7880 static void extendLeft(SourceRange &R, SourceRange Before) {
7881   if (Before.isInvalid())
7882     return;
7883   R.setBegin(Before.getBegin());
7884   if (R.getEnd().isInvalid())
7885     R.setEnd(Before.getEnd());
7886 }
7887 
7888 static void extendRight(SourceRange &R, SourceRange After) {
7889   if (After.isInvalid())
7890     return;
7891   if (R.getBegin().isInvalid())
7892     R.setBegin(After.getBegin());
7893   R.setEnd(After.getEnd());
7894 }
7895 
7896 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7897 /// well-formednes of the conversion function declarator @p D with
7898 /// type @p R. If there are any errors in the declarator, this routine
7899 /// will emit diagnostics and return true. Otherwise, it will return
7900 /// false. Either way, the type @p R will be updated to reflect a
7901 /// well-formed type for the conversion operator.
7902 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7903                                      StorageClass& SC) {
7904   // C++ [class.conv.fct]p1:
7905   //   Neither parameter types nor return type can be specified. The
7906   //   type of a conversion function (8.3.5) is "function taking no
7907   //   parameter returning conversion-type-id."
7908   if (SC == SC_Static) {
7909     if (!D.isInvalidType())
7910       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7911         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7912         << D.getName().getSourceRange();
7913     D.setInvalidType();
7914     SC = SC_None;
7915   }
7916 
7917   TypeSourceInfo *ConvTSI = nullptr;
7918   QualType ConvType =
7919       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
7920 
7921   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
7922     // Conversion functions don't have return types, but the parser will
7923     // happily parse something like:
7924     //
7925     //   class X {
7926     //     float operator bool();
7927     //   };
7928     //
7929     // The return type will be changed later anyway.
7930     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
7931       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7932       << SourceRange(D.getIdentifierLoc());
7933     D.setInvalidType();
7934   }
7935 
7936   const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7937 
7938   // Make sure we don't have any parameters.
7939   if (Proto->getNumParams() > 0) {
7940     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
7941 
7942     // Delete the parameters.
7943     D.getFunctionTypeInfo().freeParams();
7944     D.setInvalidType();
7945   } else if (Proto->isVariadic()) {
7946     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
7947     D.setInvalidType();
7948   }
7949 
7950   // Diagnose "&operator bool()" and other such nonsense.  This
7951   // is actually a gcc extension which we don't support.
7952   if (Proto->getReturnType() != ConvType) {
7953     bool NeedsTypedef = false;
7954     SourceRange Before, After;
7955 
7956     // Walk the chunks and extract information on them for our diagnostic.
7957     bool PastFunctionChunk = false;
7958     for (auto &Chunk : D.type_objects()) {
7959       switch (Chunk.Kind) {
7960       case DeclaratorChunk::Function:
7961         if (!PastFunctionChunk) {
7962           if (Chunk.Fun.HasTrailingReturnType) {
7963             TypeSourceInfo *TRT = nullptr;
7964             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
7965             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
7966           }
7967           PastFunctionChunk = true;
7968           break;
7969         }
7970         // Fall through.
7971       case DeclaratorChunk::Array:
7972         NeedsTypedef = true;
7973         extendRight(After, Chunk.getSourceRange());
7974         break;
7975 
7976       case DeclaratorChunk::Pointer:
7977       case DeclaratorChunk::BlockPointer:
7978       case DeclaratorChunk::Reference:
7979       case DeclaratorChunk::MemberPointer:
7980       case DeclaratorChunk::Pipe:
7981         extendLeft(Before, Chunk.getSourceRange());
7982         break;
7983 
7984       case DeclaratorChunk::Paren:
7985         extendLeft(Before, Chunk.Loc);
7986         extendRight(After, Chunk.EndLoc);
7987         break;
7988       }
7989     }
7990 
7991     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
7992                          After.isValid()  ? After.getBegin() :
7993                                             D.getIdentifierLoc();
7994     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
7995     DB << Before << After;
7996 
7997     if (!NeedsTypedef) {
7998       DB << /*don't need a typedef*/0;
7999 
8000       // If we can provide a correct fix-it hint, do so.
8001       if (After.isInvalid() && ConvTSI) {
8002         SourceLocation InsertLoc =
8003             getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8004         DB << FixItHint::CreateInsertion(InsertLoc, " ")
8005            << FixItHint::CreateInsertionFromRange(
8006                   InsertLoc, CharSourceRange::getTokenRange(Before))
8007            << FixItHint::CreateRemoval(Before);
8008       }
8009     } else if (!Proto->getReturnType()->isDependentType()) {
8010       DB << /*typedef*/1 << Proto->getReturnType();
8011     } else if (getLangOpts().CPlusPlus11) {
8012       DB << /*alias template*/2 << Proto->getReturnType();
8013     } else {
8014       DB << /*might not be fixable*/3;
8015     }
8016 
8017     // Recover by incorporating the other type chunks into the result type.
8018     // Note, this does *not* change the name of the function. This is compatible
8019     // with the GCC extension:
8020     //   struct S { &operator int(); } s;
8021     //   int &r = s.operator int(); // ok in GCC
8022     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
8023     ConvType = Proto->getReturnType();
8024   }
8025 
8026   // C++ [class.conv.fct]p4:
8027   //   The conversion-type-id shall not represent a function type nor
8028   //   an array type.
8029   if (ConvType->isArrayType()) {
8030     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8031     ConvType = Context.getPointerType(ConvType);
8032     D.setInvalidType();
8033   } else if (ConvType->isFunctionType()) {
8034     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8035     ConvType = Context.getPointerType(ConvType);
8036     D.setInvalidType();
8037   }
8038 
8039   // Rebuild the function type "R" without any parameters (in case any
8040   // of the errors above fired) and with the conversion type as the
8041   // return type.
8042   if (D.isInvalidType())
8043     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8044 
8045   // C++0x explicit conversion operators.
8046   if (D.getDeclSpec().isExplicitSpecified())
8047     Diag(D.getDeclSpec().getExplicitSpecLoc(),
8048          getLangOpts().CPlusPlus11 ?
8049            diag::warn_cxx98_compat_explicit_conversion_functions :
8050            diag::ext_explicit_conversion_functions)
8051       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
8052 }
8053 
8054 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8055 /// the declaration of the given C++ conversion function. This routine
8056 /// is responsible for recording the conversion function in the C++
8057 /// class, if possible.
8058 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8059   assert(Conversion && "Expected to receive a conversion function declaration");
8060 
8061   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8062 
8063   // Make sure we aren't redeclaring the conversion function.
8064   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8065 
8066   // C++ [class.conv.fct]p1:
8067   //   [...] A conversion function is never used to convert a
8068   //   (possibly cv-qualified) object to the (possibly cv-qualified)
8069   //   same object type (or a reference to it), to a (possibly
8070   //   cv-qualified) base class of that type (or a reference to it),
8071   //   or to (possibly cv-qualified) void.
8072   // FIXME: Suppress this warning if the conversion function ends up being a
8073   // virtual function that overrides a virtual function in a base class.
8074   QualType ClassType
8075     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8076   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8077     ConvType = ConvTypeRef->getPointeeType();
8078   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8079       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8080     /* Suppress diagnostics for instantiations. */;
8081   else if (ConvType->isRecordType()) {
8082     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8083     if (ConvType == ClassType)
8084       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8085         << ClassType;
8086     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8087       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8088         <<  ClassType << ConvType;
8089   } else if (ConvType->isVoidType()) {
8090     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8091       << ClassType << ConvType;
8092   }
8093 
8094   if (FunctionTemplateDecl *ConversionTemplate
8095                                 = Conversion->getDescribedFunctionTemplate())
8096     return ConversionTemplate;
8097 
8098   return Conversion;
8099 }
8100 
8101 namespace {
8102 /// Utility class to accumulate and print a diagnostic listing the invalid
8103 /// specifier(s) on a declaration.
8104 struct BadSpecifierDiagnoser {
8105   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8106       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8107   ~BadSpecifierDiagnoser() {
8108     Diagnostic << Specifiers;
8109   }
8110 
8111   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8112     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8113   }
8114   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8115     return check(SpecLoc,
8116                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8117   }
8118   void check(SourceLocation SpecLoc, const char *Spec) {
8119     if (SpecLoc.isInvalid()) return;
8120     Diagnostic << SourceRange(SpecLoc, SpecLoc);
8121     if (!Specifiers.empty()) Specifiers += " ";
8122     Specifiers += Spec;
8123   }
8124 
8125   Sema &S;
8126   Sema::SemaDiagnosticBuilder Diagnostic;
8127   std::string Specifiers;
8128 };
8129 }
8130 
8131 /// Check the validity of a declarator that we parsed for a deduction-guide.
8132 /// These aren't actually declarators in the grammar, so we need to check that
8133 /// the user didn't specify any pieces that are not part of the deduction-guide
8134 /// grammar.
8135 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8136                                          StorageClass &SC) {
8137   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8138   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8139   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8140 
8141   // C++ [temp.deduct.guide]p3:
8142   //   A deduction-gide shall be declared in the same scope as the
8143   //   corresponding class template.
8144   if (!CurContext->getRedeclContext()->Equals(
8145           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8146     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8147       << GuidedTemplateDecl;
8148     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8149   }
8150 
8151   auto &DS = D.getMutableDeclSpec();
8152   // We leave 'friend' and 'virtual' to be rejected in the normal way.
8153   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8154       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8155       DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8156       DS.isConceptSpecified()) {
8157     BadSpecifierDiagnoser Diagnoser(
8158         *this, D.getIdentifierLoc(),
8159         diag::err_deduction_guide_invalid_specifier);
8160 
8161     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8162     DS.ClearStorageClassSpecs();
8163     SC = SC_None;
8164 
8165     // 'explicit' is permitted.
8166     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8167     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8168     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8169     Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8170     DS.ClearConstexprSpec();
8171     DS.ClearConceptSpec();
8172 
8173     Diagnoser.check(DS.getConstSpecLoc(), "const");
8174     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8175     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8176     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8177     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8178     DS.ClearTypeQualifiers();
8179 
8180     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8181     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8182     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8183     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8184     DS.ClearTypeSpecType();
8185   }
8186 
8187   if (D.isInvalidType())
8188     return;
8189 
8190   // Check the declarator is simple enough.
8191   bool FoundFunction = false;
8192   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8193     if (Chunk.Kind == DeclaratorChunk::Paren)
8194       continue;
8195     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8196       Diag(D.getDeclSpec().getLocStart(),
8197           diag::err_deduction_guide_with_complex_decl)
8198         << D.getSourceRange();
8199       break;
8200     }
8201     if (!Chunk.Fun.hasTrailingReturnType()) {
8202       Diag(D.getName().getLocStart(),
8203            diag::err_deduction_guide_no_trailing_return_type);
8204       break;
8205     }
8206 
8207     // Check that the return type is written as a specialization of
8208     // the template specified as the deduction-guide's name.
8209     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8210     TypeSourceInfo *TSI = nullptr;
8211     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8212     assert(TSI && "deduction guide has valid type but invalid return type?");
8213     bool AcceptableReturnType = false;
8214     bool MightInstantiateToSpecialization = false;
8215     if (auto RetTST =
8216             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8217       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8218       bool TemplateMatches =
8219           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8220       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8221         AcceptableReturnType = true;
8222       else {
8223         // This could still instantiate to the right type, unless we know it
8224         // names the wrong class template.
8225         auto *TD = SpecifiedName.getAsTemplateDecl();
8226         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8227                                              !TemplateMatches);
8228       }
8229     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8230       MightInstantiateToSpecialization = true;
8231     }
8232 
8233     if (!AcceptableReturnType) {
8234       Diag(TSI->getTypeLoc().getLocStart(),
8235            diag::err_deduction_guide_bad_trailing_return_type)
8236         << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8237         << TSI->getTypeLoc().getSourceRange();
8238     }
8239 
8240     // Keep going to check that we don't have any inner declarator pieces (we
8241     // could still have a function returning a pointer to a function).
8242     FoundFunction = true;
8243   }
8244 
8245   if (D.isFunctionDefinition())
8246     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8247 }
8248 
8249 //===----------------------------------------------------------------------===//
8250 // Namespace Handling
8251 //===----------------------------------------------------------------------===//
8252 
8253 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8254 /// reopened.
8255 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8256                                             SourceLocation Loc,
8257                                             IdentifierInfo *II, bool *IsInline,
8258                                             NamespaceDecl *PrevNS) {
8259   assert(*IsInline != PrevNS->isInline());
8260 
8261   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8262   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8263   // inline namespaces, with the intention of bringing names into namespace std.
8264   //
8265   // We support this just well enough to get that case working; this is not
8266   // sufficient to support reopening namespaces as inline in general.
8267   if (*IsInline && II && II->getName().startswith("__atomic") &&
8268       S.getSourceManager().isInSystemHeader(Loc)) {
8269     // Mark all prior declarations of the namespace as inline.
8270     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8271          NS = NS->getPreviousDecl())
8272       NS->setInline(*IsInline);
8273     // Patch up the lookup table for the containing namespace. This isn't really
8274     // correct, but it's good enough for this particular case.
8275     for (auto *I : PrevNS->decls())
8276       if (auto *ND = dyn_cast<NamedDecl>(I))
8277         PrevNS->getParent()->makeDeclVisibleInContext(ND);
8278     return;
8279   }
8280 
8281   if (PrevNS->isInline())
8282     // The user probably just forgot the 'inline', so suggest that it
8283     // be added back.
8284     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8285       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8286   else
8287     S.Diag(Loc, diag::err_inline_namespace_mismatch);
8288 
8289   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8290   *IsInline = PrevNS->isInline();
8291 }
8292 
8293 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8294 /// definition.
8295 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8296                                    SourceLocation InlineLoc,
8297                                    SourceLocation NamespaceLoc,
8298                                    SourceLocation IdentLoc,
8299                                    IdentifierInfo *II,
8300                                    SourceLocation LBrace,
8301                                    AttributeList *AttrList,
8302                                    UsingDirectiveDecl *&UD) {
8303   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8304   // For anonymous namespace, take the location of the left brace.
8305   SourceLocation Loc = II ? IdentLoc : LBrace;
8306   bool IsInline = InlineLoc.isValid();
8307   bool IsInvalid = false;
8308   bool IsStd = false;
8309   bool AddToKnown = false;
8310   Scope *DeclRegionScope = NamespcScope->getParent();
8311 
8312   NamespaceDecl *PrevNS = nullptr;
8313   if (II) {
8314     // C++ [namespace.def]p2:
8315     //   The identifier in an original-namespace-definition shall not
8316     //   have been previously defined in the declarative region in
8317     //   which the original-namespace-definition appears. The
8318     //   identifier in an original-namespace-definition is the name of
8319     //   the namespace. Subsequently in that declarative region, it is
8320     //   treated as an original-namespace-name.
8321     //
8322     // Since namespace names are unique in their scope, and we don't
8323     // look through using directives, just look for any ordinary names
8324     // as if by qualified name lookup.
8325     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8326     LookupQualifiedName(R, CurContext->getRedeclContext());
8327     NamedDecl *PrevDecl =
8328         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8329     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8330 
8331     if (PrevNS) {
8332       // This is an extended namespace definition.
8333       if (IsInline != PrevNS->isInline())
8334         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8335                                         &IsInline, PrevNS);
8336     } else if (PrevDecl) {
8337       // This is an invalid name redefinition.
8338       Diag(Loc, diag::err_redefinition_different_kind)
8339         << II;
8340       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8341       IsInvalid = true;
8342       // Continue on to push Namespc as current DeclContext and return it.
8343     } else if (II->isStr("std") &&
8344                CurContext->getRedeclContext()->isTranslationUnit()) {
8345       // This is the first "real" definition of the namespace "std", so update
8346       // our cache of the "std" namespace to point at this definition.
8347       PrevNS = getStdNamespace();
8348       IsStd = true;
8349       AddToKnown = !IsInline;
8350     } else {
8351       // We've seen this namespace for the first time.
8352       AddToKnown = !IsInline;
8353     }
8354   } else {
8355     // Anonymous namespaces.
8356 
8357     // Determine whether the parent already has an anonymous namespace.
8358     DeclContext *Parent = CurContext->getRedeclContext();
8359     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8360       PrevNS = TU->getAnonymousNamespace();
8361     } else {
8362       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8363       PrevNS = ND->getAnonymousNamespace();
8364     }
8365 
8366     if (PrevNS && IsInline != PrevNS->isInline())
8367       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8368                                       &IsInline, PrevNS);
8369   }
8370 
8371   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8372                                                  StartLoc, Loc, II, PrevNS);
8373   if (IsInvalid)
8374     Namespc->setInvalidDecl();
8375 
8376   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8377 
8378   // FIXME: Should we be merging attributes?
8379   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8380     PushNamespaceVisibilityAttr(Attr, Loc);
8381 
8382   if (IsStd)
8383     StdNamespace = Namespc;
8384   if (AddToKnown)
8385     KnownNamespaces[Namespc] = false;
8386 
8387   if (II) {
8388     PushOnScopeChains(Namespc, DeclRegionScope);
8389   } else {
8390     // Link the anonymous namespace into its parent.
8391     DeclContext *Parent = CurContext->getRedeclContext();
8392     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8393       TU->setAnonymousNamespace(Namespc);
8394     } else {
8395       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8396     }
8397 
8398     CurContext->addDecl(Namespc);
8399 
8400     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
8401     //   behaves as if it were replaced by
8402     //     namespace unique { /* empty body */ }
8403     //     using namespace unique;
8404     //     namespace unique { namespace-body }
8405     //   where all occurrences of 'unique' in a translation unit are
8406     //   replaced by the same identifier and this identifier differs
8407     //   from all other identifiers in the entire program.
8408 
8409     // We just create the namespace with an empty name and then add an
8410     // implicit using declaration, just like the standard suggests.
8411     //
8412     // CodeGen enforces the "universally unique" aspect by giving all
8413     // declarations semantically contained within an anonymous
8414     // namespace internal linkage.
8415 
8416     if (!PrevNS) {
8417       UD = UsingDirectiveDecl::Create(Context, Parent,
8418                                       /* 'using' */ LBrace,
8419                                       /* 'namespace' */ SourceLocation(),
8420                                       /* qualifier */ NestedNameSpecifierLoc(),
8421                                       /* identifier */ SourceLocation(),
8422                                       Namespc,
8423                                       /* Ancestor */ Parent);
8424       UD->setImplicit();
8425       Parent->addDecl(UD);
8426     }
8427   }
8428 
8429   ActOnDocumentableDecl(Namespc);
8430 
8431   // Although we could have an invalid decl (i.e. the namespace name is a
8432   // redefinition), push it as current DeclContext and try to continue parsing.
8433   // FIXME: We should be able to push Namespc here, so that the each DeclContext
8434   // for the namespace has the declarations that showed up in that particular
8435   // namespace definition.
8436   PushDeclContext(NamespcScope, Namespc);
8437   return Namespc;
8438 }
8439 
8440 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8441 /// is a namespace alias, returns the namespace it points to.
8442 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8443   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8444     return AD->getNamespace();
8445   return dyn_cast_or_null<NamespaceDecl>(D);
8446 }
8447 
8448 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8449 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8450 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8451   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8452   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8453   Namespc->setRBraceLoc(RBrace);
8454   PopDeclContext();
8455   if (Namespc->hasAttr<VisibilityAttr>())
8456     PopPragmaVisibility(true, RBrace);
8457 }
8458 
8459 CXXRecordDecl *Sema::getStdBadAlloc() const {
8460   return cast_or_null<CXXRecordDecl>(
8461                                   StdBadAlloc.get(Context.getExternalSource()));
8462 }
8463 
8464 EnumDecl *Sema::getStdAlignValT() const {
8465   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8466 }
8467 
8468 NamespaceDecl *Sema::getStdNamespace() const {
8469   return cast_or_null<NamespaceDecl>(
8470                                  StdNamespace.get(Context.getExternalSource()));
8471 }
8472 
8473 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8474   if (!StdExperimentalNamespaceCache) {
8475     if (auto Std = getStdNamespace()) {
8476       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8477                           SourceLocation(), LookupNamespaceName);
8478       if (!LookupQualifiedName(Result, Std) ||
8479           !(StdExperimentalNamespaceCache =
8480                 Result.getAsSingle<NamespaceDecl>()))
8481         Result.suppressDiagnostics();
8482     }
8483   }
8484   return StdExperimentalNamespaceCache;
8485 }
8486 
8487 /// \brief Retrieve the special "std" namespace, which may require us to
8488 /// implicitly define the namespace.
8489 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8490   if (!StdNamespace) {
8491     // The "std" namespace has not yet been defined, so build one implicitly.
8492     StdNamespace = NamespaceDecl::Create(Context,
8493                                          Context.getTranslationUnitDecl(),
8494                                          /*Inline=*/false,
8495                                          SourceLocation(), SourceLocation(),
8496                                          &PP.getIdentifierTable().get("std"),
8497                                          /*PrevDecl=*/nullptr);
8498     getStdNamespace()->setImplicit(true);
8499   }
8500 
8501   return getStdNamespace();
8502 }
8503 
8504 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8505   assert(getLangOpts().CPlusPlus &&
8506          "Looking for std::initializer_list outside of C++.");
8507 
8508   // We're looking for implicit instantiations of
8509   // template <typename E> class std::initializer_list.
8510 
8511   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8512     return false;
8513 
8514   ClassTemplateDecl *Template = nullptr;
8515   const TemplateArgument *Arguments = nullptr;
8516 
8517   if (const RecordType *RT = Ty->getAs<RecordType>()) {
8518 
8519     ClassTemplateSpecializationDecl *Specialization =
8520         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8521     if (!Specialization)
8522       return false;
8523 
8524     Template = Specialization->getSpecializedTemplate();
8525     Arguments = Specialization->getTemplateArgs().data();
8526   } else if (const TemplateSpecializationType *TST =
8527                  Ty->getAs<TemplateSpecializationType>()) {
8528     Template = dyn_cast_or_null<ClassTemplateDecl>(
8529         TST->getTemplateName().getAsTemplateDecl());
8530     Arguments = TST->getArgs();
8531   }
8532   if (!Template)
8533     return false;
8534 
8535   if (!StdInitializerList) {
8536     // Haven't recognized std::initializer_list yet, maybe this is it.
8537     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8538     if (TemplateClass->getIdentifier() !=
8539             &PP.getIdentifierTable().get("initializer_list") ||
8540         !getStdNamespace()->InEnclosingNamespaceSetOf(
8541             TemplateClass->getDeclContext()))
8542       return false;
8543     // This is a template called std::initializer_list, but is it the right
8544     // template?
8545     TemplateParameterList *Params = Template->getTemplateParameters();
8546     if (Params->getMinRequiredArguments() != 1)
8547       return false;
8548     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8549       return false;
8550 
8551     // It's the right template.
8552     StdInitializerList = Template;
8553   }
8554 
8555   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8556     return false;
8557 
8558   // This is an instance of std::initializer_list. Find the argument type.
8559   if (Element)
8560     *Element = Arguments[0].getAsType();
8561   return true;
8562 }
8563 
8564 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8565   NamespaceDecl *Std = S.getStdNamespace();
8566   if (!Std) {
8567     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8568     return nullptr;
8569   }
8570 
8571   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8572                       Loc, Sema::LookupOrdinaryName);
8573   if (!S.LookupQualifiedName(Result, Std)) {
8574     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8575     return nullptr;
8576   }
8577   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8578   if (!Template) {
8579     Result.suppressDiagnostics();
8580     // We found something weird. Complain about the first thing we found.
8581     NamedDecl *Found = *Result.begin();
8582     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8583     return nullptr;
8584   }
8585 
8586   // We found some template called std::initializer_list. Now verify that it's
8587   // correct.
8588   TemplateParameterList *Params = Template->getTemplateParameters();
8589   if (Params->getMinRequiredArguments() != 1 ||
8590       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8591     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8592     return nullptr;
8593   }
8594 
8595   return Template;
8596 }
8597 
8598 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8599   if (!StdInitializerList) {
8600     StdInitializerList = LookupStdInitializerList(*this, Loc);
8601     if (!StdInitializerList)
8602       return QualType();
8603   }
8604 
8605   TemplateArgumentListInfo Args(Loc, Loc);
8606   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8607                                        Context.getTrivialTypeSourceInfo(Element,
8608                                                                         Loc)));
8609   return Context.getCanonicalType(
8610       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8611 }
8612 
8613 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
8614   // C++ [dcl.init.list]p2:
8615   //   A constructor is an initializer-list constructor if its first parameter
8616   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
8617   //   std::initializer_list<E> for some type E, and either there are no other
8618   //   parameters or else all other parameters have default arguments.
8619   if (Ctor->getNumParams() < 1 ||
8620       (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8621     return false;
8622 
8623   QualType ArgType = Ctor->getParamDecl(0)->getType();
8624   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8625     ArgType = RT->getPointeeType().getUnqualifiedType();
8626 
8627   return isStdInitializerList(ArgType, nullptr);
8628 }
8629 
8630 /// \brief Determine whether a using statement is in a context where it will be
8631 /// apply in all contexts.
8632 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8633   switch (CurContext->getDeclKind()) {
8634     case Decl::TranslationUnit:
8635       return true;
8636     case Decl::LinkageSpec:
8637       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8638     default:
8639       return false;
8640   }
8641 }
8642 
8643 namespace {
8644 
8645 // Callback to only accept typo corrections that are namespaces.
8646 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8647 public:
8648   bool ValidateCandidate(const TypoCorrection &candidate) override {
8649     if (NamedDecl *ND = candidate.getCorrectionDecl())
8650       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8651     return false;
8652   }
8653 };
8654 
8655 }
8656 
8657 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8658                                        CXXScopeSpec &SS,
8659                                        SourceLocation IdentLoc,
8660                                        IdentifierInfo *Ident) {
8661   R.clear();
8662   if (TypoCorrection Corrected =
8663           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8664                         llvm::make_unique<NamespaceValidatorCCC>(),
8665                         Sema::CTK_ErrorRecovery)) {
8666     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8667       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8668       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8669                               Ident->getName().equals(CorrectedStr);
8670       S.diagnoseTypo(Corrected,
8671                      S.PDiag(diag::err_using_directive_member_suggest)
8672                        << Ident << DC << DroppedSpecifier << SS.getRange(),
8673                      S.PDiag(diag::note_namespace_defined_here));
8674     } else {
8675       S.diagnoseTypo(Corrected,
8676                      S.PDiag(diag::err_using_directive_suggest) << Ident,
8677                      S.PDiag(diag::note_namespace_defined_here));
8678     }
8679     R.addDecl(Corrected.getFoundDecl());
8680     return true;
8681   }
8682   return false;
8683 }
8684 
8685 Decl *Sema::ActOnUsingDirective(Scope *S,
8686                                           SourceLocation UsingLoc,
8687                                           SourceLocation NamespcLoc,
8688                                           CXXScopeSpec &SS,
8689                                           SourceLocation IdentLoc,
8690                                           IdentifierInfo *NamespcName,
8691                                           AttributeList *AttrList) {
8692   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8693   assert(NamespcName && "Invalid NamespcName.");
8694   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8695 
8696   // This can only happen along a recovery path.
8697   while (S->isTemplateParamScope())
8698     S = S->getParent();
8699   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8700 
8701   UsingDirectiveDecl *UDir = nullptr;
8702   NestedNameSpecifier *Qualifier = nullptr;
8703   if (SS.isSet())
8704     Qualifier = SS.getScopeRep();
8705 
8706   // Lookup namespace name.
8707   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8708   LookupParsedName(R, S, &SS);
8709   if (R.isAmbiguous())
8710     return nullptr;
8711 
8712   if (R.empty()) {
8713     R.clear();
8714     // Allow "using namespace std;" or "using namespace ::std;" even if
8715     // "std" hasn't been defined yet, for GCC compatibility.
8716     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8717         NamespcName->isStr("std")) {
8718       Diag(IdentLoc, diag::ext_using_undefined_std);
8719       R.addDecl(getOrCreateStdNamespace());
8720       R.resolveKind();
8721     }
8722     // Otherwise, attempt typo correction.
8723     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8724   }
8725 
8726   if (!R.empty()) {
8727     NamedDecl *Named = R.getRepresentativeDecl();
8728     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8729     assert(NS && "expected namespace decl");
8730 
8731     // The use of a nested name specifier may trigger deprecation warnings.
8732     DiagnoseUseOfDecl(Named, IdentLoc);
8733 
8734     // C++ [namespace.udir]p1:
8735     //   A using-directive specifies that the names in the nominated
8736     //   namespace can be used in the scope in which the
8737     //   using-directive appears after the using-directive. During
8738     //   unqualified name lookup (3.4.1), the names appear as if they
8739     //   were declared in the nearest enclosing namespace which
8740     //   contains both the using-directive and the nominated
8741     //   namespace. [Note: in this context, "contains" means "contains
8742     //   directly or indirectly". ]
8743 
8744     // Find enclosing context containing both using-directive and
8745     // nominated namespace.
8746     DeclContext *CommonAncestor = cast<DeclContext>(NS);
8747     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8748       CommonAncestor = CommonAncestor->getParent();
8749 
8750     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8751                                       SS.getWithLocInContext(Context),
8752                                       IdentLoc, Named, CommonAncestor);
8753 
8754     if (IsUsingDirectiveInToplevelContext(CurContext) &&
8755         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8756       Diag(IdentLoc, diag::warn_using_directive_in_header);
8757     }
8758 
8759     PushUsingDirective(S, UDir);
8760   } else {
8761     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8762   }
8763 
8764   if (UDir)
8765     ProcessDeclAttributeList(S, UDir, AttrList);
8766 
8767   return UDir;
8768 }
8769 
8770 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8771   // If the scope has an associated entity and the using directive is at
8772   // namespace or translation unit scope, add the UsingDirectiveDecl into
8773   // its lookup structure so qualified name lookup can find it.
8774   DeclContext *Ctx = S->getEntity();
8775   if (Ctx && !Ctx->isFunctionOrMethod())
8776     Ctx->addDecl(UDir);
8777   else
8778     // Otherwise, it is at block scope. The using-directives will affect lookup
8779     // only to the end of the scope.
8780     S->PushUsingDirective(UDir);
8781 }
8782 
8783 
8784 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8785                                   AccessSpecifier AS,
8786                                   SourceLocation UsingLoc,
8787                                   SourceLocation TypenameLoc,
8788                                   CXXScopeSpec &SS,
8789                                   UnqualifiedId &Name,
8790                                   SourceLocation EllipsisLoc,
8791                                   AttributeList *AttrList) {
8792   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8793 
8794   if (SS.isEmpty()) {
8795     Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8796     return nullptr;
8797   }
8798 
8799   switch (Name.getKind()) {
8800   case UnqualifiedId::IK_ImplicitSelfParam:
8801   case UnqualifiedId::IK_Identifier:
8802   case UnqualifiedId::IK_OperatorFunctionId:
8803   case UnqualifiedId::IK_LiteralOperatorId:
8804   case UnqualifiedId::IK_ConversionFunctionId:
8805     break;
8806 
8807   case UnqualifiedId::IK_ConstructorName:
8808   case UnqualifiedId::IK_ConstructorTemplateId:
8809     // C++11 inheriting constructors.
8810     Diag(Name.getLocStart(),
8811          getLangOpts().CPlusPlus11 ?
8812            diag::warn_cxx98_compat_using_decl_constructor :
8813            diag::err_using_decl_constructor)
8814       << SS.getRange();
8815 
8816     if (getLangOpts().CPlusPlus11) break;
8817 
8818     return nullptr;
8819 
8820   case UnqualifiedId::IK_DestructorName:
8821     Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8822       << SS.getRange();
8823     return nullptr;
8824 
8825   case UnqualifiedId::IK_TemplateId:
8826     Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8827       << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8828     return nullptr;
8829 
8830   case UnqualifiedId::IK_DeductionGuideName:
8831     llvm_unreachable("cannot parse qualified deduction guide name");
8832   }
8833 
8834   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8835   DeclarationName TargetName = TargetNameInfo.getName();
8836   if (!TargetName)
8837     return nullptr;
8838 
8839   // Warn about access declarations.
8840   if (UsingLoc.isInvalid()) {
8841     Diag(Name.getLocStart(),
8842          getLangOpts().CPlusPlus11 ? diag::err_access_decl
8843                                    : diag::warn_access_decl_deprecated)
8844       << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8845   }
8846 
8847   if (EllipsisLoc.isInvalid()) {
8848     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8849         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8850       return nullptr;
8851   } else {
8852     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8853         !TargetNameInfo.containsUnexpandedParameterPack()) {
8854       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8855         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8856       EllipsisLoc = SourceLocation();
8857     }
8858   }
8859 
8860   NamedDecl *UD =
8861       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8862                             SS, TargetNameInfo, EllipsisLoc, AttrList,
8863                             /*IsInstantiation*/false);
8864   if (UD)
8865     PushOnScopeChains(UD, S, /*AddToContext*/ false);
8866 
8867   return UD;
8868 }
8869 
8870 /// \brief Determine whether a using declaration considers the given
8871 /// declarations as "equivalent", e.g., if they are redeclarations of
8872 /// the same entity or are both typedefs of the same type.
8873 static bool
8874 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8875   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8876     return true;
8877 
8878   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8879     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8880       return Context.hasSameType(TD1->getUnderlyingType(),
8881                                  TD2->getUnderlyingType());
8882 
8883   return false;
8884 }
8885 
8886 
8887 /// Determines whether to create a using shadow decl for a particular
8888 /// decl, given the set of decls existing prior to this using lookup.
8889 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8890                                 const LookupResult &Previous,
8891                                 UsingShadowDecl *&PrevShadow) {
8892   // Diagnose finding a decl which is not from a base class of the
8893   // current class.  We do this now because there are cases where this
8894   // function will silently decide not to build a shadow decl, which
8895   // will pre-empt further diagnostics.
8896   //
8897   // We don't need to do this in C++11 because we do the check once on
8898   // the qualifier.
8899   //
8900   // FIXME: diagnose the following if we care enough:
8901   //   struct A { int foo; };
8902   //   struct B : A { using A::foo; };
8903   //   template <class T> struct C : A {};
8904   //   template <class T> struct D : C<T> { using B::foo; } // <---
8905   // This is invalid (during instantiation) in C++03 because B::foo
8906   // resolves to the using decl in B, which is not a base class of D<T>.
8907   // We can't diagnose it immediately because C<T> is an unknown
8908   // specialization.  The UsingShadowDecl in D<T> then points directly
8909   // to A::foo, which will look well-formed when we instantiate.
8910   // The right solution is to not collapse the shadow-decl chain.
8911   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8912     DeclContext *OrigDC = Orig->getDeclContext();
8913 
8914     // Handle enums and anonymous structs.
8915     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8916     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
8917     while (OrigRec->isAnonymousStructOrUnion())
8918       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
8919 
8920     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
8921       if (OrigDC == CurContext) {
8922         Diag(Using->getLocation(),
8923              diag::err_using_decl_nested_name_specifier_is_current_class)
8924           << Using->getQualifierLoc().getSourceRange();
8925         Diag(Orig->getLocation(), diag::note_using_decl_target);
8926         Using->setInvalidDecl();
8927         return true;
8928       }
8929 
8930       Diag(Using->getQualifierLoc().getBeginLoc(),
8931            diag::err_using_decl_nested_name_specifier_is_not_base_class)
8932         << Using->getQualifier()
8933         << cast<CXXRecordDecl>(CurContext)
8934         << Using->getQualifierLoc().getSourceRange();
8935       Diag(Orig->getLocation(), diag::note_using_decl_target);
8936       Using->setInvalidDecl();
8937       return true;
8938     }
8939   }
8940 
8941   if (Previous.empty()) return false;
8942 
8943   NamedDecl *Target = Orig;
8944   if (isa<UsingShadowDecl>(Target))
8945     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
8946 
8947   // If the target happens to be one of the previous declarations, we
8948   // don't have a conflict.
8949   //
8950   // FIXME: but we might be increasing its access, in which case we
8951   // should redeclare it.
8952   NamedDecl *NonTag = nullptr, *Tag = nullptr;
8953   bool FoundEquivalentDecl = false;
8954   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8955          I != E; ++I) {
8956     NamedDecl *D = (*I)->getUnderlyingDecl();
8957     // We can have UsingDecls in our Previous results because we use the same
8958     // LookupResult for checking whether the UsingDecl itself is a valid
8959     // redeclaration.
8960     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
8961       continue;
8962 
8963     if (IsEquivalentForUsingDecl(Context, D, Target)) {
8964       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
8965         PrevShadow = Shadow;
8966       FoundEquivalentDecl = true;
8967     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
8968       // We don't conflict with an existing using shadow decl of an equivalent
8969       // declaration, but we're not a redeclaration of it.
8970       FoundEquivalentDecl = true;
8971     }
8972 
8973     if (isVisible(D))
8974       (isa<TagDecl>(D) ? Tag : NonTag) = D;
8975   }
8976 
8977   if (FoundEquivalentDecl)
8978     return false;
8979 
8980   if (FunctionDecl *FD = Target->getAsFunction()) {
8981     NamedDecl *OldDecl = nullptr;
8982     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
8983                           /*IsForUsingDecl*/ true)) {
8984     case Ovl_Overload:
8985       return false;
8986 
8987     case Ovl_NonFunction:
8988       Diag(Using->getLocation(), diag::err_using_decl_conflict);
8989       break;
8990 
8991     // We found a decl with the exact signature.
8992     case Ovl_Match:
8993       // If we're in a record, we want to hide the target, so we
8994       // return true (without a diagnostic) to tell the caller not to
8995       // build a shadow decl.
8996       if (CurContext->isRecord())
8997         return true;
8998 
8999       // If we're not in a record, this is an error.
9000       Diag(Using->getLocation(), diag::err_using_decl_conflict);
9001       break;
9002     }
9003 
9004     Diag(Target->getLocation(), diag::note_using_decl_target);
9005     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9006     Using->setInvalidDecl();
9007     return true;
9008   }
9009 
9010   // Target is not a function.
9011 
9012   if (isa<TagDecl>(Target)) {
9013     // No conflict between a tag and a non-tag.
9014     if (!Tag) return false;
9015 
9016     Diag(Using->getLocation(), diag::err_using_decl_conflict);
9017     Diag(Target->getLocation(), diag::note_using_decl_target);
9018     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9019     Using->setInvalidDecl();
9020     return true;
9021   }
9022 
9023   // No conflict between a tag and a non-tag.
9024   if (!NonTag) return false;
9025 
9026   Diag(Using->getLocation(), diag::err_using_decl_conflict);
9027   Diag(Target->getLocation(), diag::note_using_decl_target);
9028   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9029   Using->setInvalidDecl();
9030   return true;
9031 }
9032 
9033 /// Determine whether a direct base class is a virtual base class.
9034 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9035   if (!Derived->getNumVBases())
9036     return false;
9037   for (auto &B : Derived->bases())
9038     if (B.getType()->getAsCXXRecordDecl() == Base)
9039       return B.isVirtual();
9040   llvm_unreachable("not a direct base class");
9041 }
9042 
9043 /// Builds a shadow declaration corresponding to a 'using' declaration.
9044 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9045                                             UsingDecl *UD,
9046                                             NamedDecl *Orig,
9047                                             UsingShadowDecl *PrevDecl) {
9048   // If we resolved to another shadow declaration, just coalesce them.
9049   NamedDecl *Target = Orig;
9050   if (isa<UsingShadowDecl>(Target)) {
9051     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9052     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9053   }
9054 
9055   NamedDecl *NonTemplateTarget = Target;
9056   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9057     NonTemplateTarget = TargetTD->getTemplatedDecl();
9058 
9059   UsingShadowDecl *Shadow;
9060   if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9061     bool IsVirtualBase =
9062         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9063                             UD->getQualifier()->getAsRecordDecl());
9064     Shadow = ConstructorUsingShadowDecl::Create(
9065         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9066   } else {
9067     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9068                                      Target);
9069   }
9070   UD->addShadowDecl(Shadow);
9071 
9072   Shadow->setAccess(UD->getAccess());
9073   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9074     Shadow->setInvalidDecl();
9075 
9076   Shadow->setPreviousDecl(PrevDecl);
9077 
9078   if (S)
9079     PushOnScopeChains(Shadow, S);
9080   else
9081     CurContext->addDecl(Shadow);
9082 
9083 
9084   return Shadow;
9085 }
9086 
9087 /// Hides a using shadow declaration.  This is required by the current
9088 /// using-decl implementation when a resolvable using declaration in a
9089 /// class is followed by a declaration which would hide or override
9090 /// one or more of the using decl's targets; for example:
9091 ///
9092 ///   struct Base { void foo(int); };
9093 ///   struct Derived : Base {
9094 ///     using Base::foo;
9095 ///     void foo(int);
9096 ///   };
9097 ///
9098 /// The governing language is C++03 [namespace.udecl]p12:
9099 ///
9100 ///   When a using-declaration brings names from a base class into a
9101 ///   derived class scope, member functions in the derived class
9102 ///   override and/or hide member functions with the same name and
9103 ///   parameter types in a base class (rather than conflicting).
9104 ///
9105 /// There are two ways to implement this:
9106 ///   (1) optimistically create shadow decls when they're not hidden
9107 ///       by existing declarations, or
9108 ///   (2) don't create any shadow decls (or at least don't make them
9109 ///       visible) until we've fully parsed/instantiated the class.
9110 /// The problem with (1) is that we might have to retroactively remove
9111 /// a shadow decl, which requires several O(n) operations because the
9112 /// decl structures are (very reasonably) not designed for removal.
9113 /// (2) avoids this but is very fiddly and phase-dependent.
9114 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9115   if (Shadow->getDeclName().getNameKind() ==
9116         DeclarationName::CXXConversionFunctionName)
9117     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9118 
9119   // Remove it from the DeclContext...
9120   Shadow->getDeclContext()->removeDecl(Shadow);
9121 
9122   // ...and the scope, if applicable...
9123   if (S) {
9124     S->RemoveDecl(Shadow);
9125     IdResolver.RemoveDecl(Shadow);
9126   }
9127 
9128   // ...and the using decl.
9129   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9130 
9131   // TODO: complain somehow if Shadow was used.  It shouldn't
9132   // be possible for this to happen, because...?
9133 }
9134 
9135 /// Find the base specifier for a base class with the given type.
9136 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9137                                                 QualType DesiredBase,
9138                                                 bool &AnyDependentBases) {
9139   // Check whether the named type is a direct base class.
9140   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9141   for (auto &Base : Derived->bases()) {
9142     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9143     if (CanonicalDesiredBase == BaseType)
9144       return &Base;
9145     if (BaseType->isDependentType())
9146       AnyDependentBases = true;
9147   }
9148   return nullptr;
9149 }
9150 
9151 namespace {
9152 class UsingValidatorCCC : public CorrectionCandidateCallback {
9153 public:
9154   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9155                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9156       : HasTypenameKeyword(HasTypenameKeyword),
9157         IsInstantiation(IsInstantiation), OldNNS(NNS),
9158         RequireMemberOf(RequireMemberOf) {}
9159 
9160   bool ValidateCandidate(const TypoCorrection &Candidate) override {
9161     NamedDecl *ND = Candidate.getCorrectionDecl();
9162 
9163     // Keywords are not valid here.
9164     if (!ND || isa<NamespaceDecl>(ND))
9165       return false;
9166 
9167     // Completely unqualified names are invalid for a 'using' declaration.
9168     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9169       return false;
9170 
9171     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9172     // reject.
9173 
9174     if (RequireMemberOf) {
9175       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9176       if (FoundRecord && FoundRecord->isInjectedClassName()) {
9177         // No-one ever wants a using-declaration to name an injected-class-name
9178         // of a base class, unless they're declaring an inheriting constructor.
9179         ASTContext &Ctx = ND->getASTContext();
9180         if (!Ctx.getLangOpts().CPlusPlus11)
9181           return false;
9182         QualType FoundType = Ctx.getRecordType(FoundRecord);
9183 
9184         // Check that the injected-class-name is named as a member of its own
9185         // type; we don't want to suggest 'using Derived::Base;', since that
9186         // means something else.
9187         NestedNameSpecifier *Specifier =
9188             Candidate.WillReplaceSpecifier()
9189                 ? Candidate.getCorrectionSpecifier()
9190                 : OldNNS;
9191         if (!Specifier->getAsType() ||
9192             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9193           return false;
9194 
9195         // Check that this inheriting constructor declaration actually names a
9196         // direct base class of the current class.
9197         bool AnyDependentBases = false;
9198         if (!findDirectBaseWithType(RequireMemberOf,
9199                                     Ctx.getRecordType(FoundRecord),
9200                                     AnyDependentBases) &&
9201             !AnyDependentBases)
9202           return false;
9203       } else {
9204         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9205         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9206           return false;
9207 
9208         // FIXME: Check that the base class member is accessible?
9209       }
9210     } else {
9211       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9212       if (FoundRecord && FoundRecord->isInjectedClassName())
9213         return false;
9214     }
9215 
9216     if (isa<TypeDecl>(ND))
9217       return HasTypenameKeyword || !IsInstantiation;
9218 
9219     return !HasTypenameKeyword;
9220   }
9221 
9222 private:
9223   bool HasTypenameKeyword;
9224   bool IsInstantiation;
9225   NestedNameSpecifier *OldNNS;
9226   CXXRecordDecl *RequireMemberOf;
9227 };
9228 } // end anonymous namespace
9229 
9230 /// Builds a using declaration.
9231 ///
9232 /// \param IsInstantiation - Whether this call arises from an
9233 ///   instantiation of an unresolved using declaration.  We treat
9234 ///   the lookup differently for these declarations.
9235 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9236                                        SourceLocation UsingLoc,
9237                                        bool HasTypenameKeyword,
9238                                        SourceLocation TypenameLoc,
9239                                        CXXScopeSpec &SS,
9240                                        DeclarationNameInfo NameInfo,
9241                                        SourceLocation EllipsisLoc,
9242                                        AttributeList *AttrList,
9243                                        bool IsInstantiation) {
9244   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9245   SourceLocation IdentLoc = NameInfo.getLoc();
9246   assert(IdentLoc.isValid() && "Invalid TargetName location.");
9247 
9248   // FIXME: We ignore attributes for now.
9249 
9250   // For an inheriting constructor declaration, the name of the using
9251   // declaration is the name of a constructor in this class, not in the
9252   // base class.
9253   DeclarationNameInfo UsingName = NameInfo;
9254   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9255     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9256       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9257           Context.getCanonicalType(Context.getRecordType(RD))));
9258 
9259   // Do the redeclaration lookup in the current scope.
9260   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9261                         ForRedeclaration);
9262   Previous.setHideTags(false);
9263   if (S) {
9264     LookupName(Previous, S);
9265 
9266     // It is really dumb that we have to do this.
9267     LookupResult::Filter F = Previous.makeFilter();
9268     while (F.hasNext()) {
9269       NamedDecl *D = F.next();
9270       if (!isDeclInScope(D, CurContext, S))
9271         F.erase();
9272       // If we found a local extern declaration that's not ordinarily visible,
9273       // and this declaration is being added to a non-block scope, ignore it.
9274       // We're only checking for scope conflicts here, not also for violations
9275       // of the linkage rules.
9276       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9277                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9278         F.erase();
9279     }
9280     F.done();
9281   } else {
9282     assert(IsInstantiation && "no scope in non-instantiation");
9283     if (CurContext->isRecord())
9284       LookupQualifiedName(Previous, CurContext);
9285     else {
9286       // No redeclaration check is needed here; in non-member contexts we
9287       // diagnosed all possible conflicts with other using-declarations when
9288       // building the template:
9289       //
9290       // For a dependent non-type using declaration, the only valid case is
9291       // if we instantiate to a single enumerator. We check for conflicts
9292       // between shadow declarations we introduce, and we check in the template
9293       // definition for conflicts between a non-type using declaration and any
9294       // other declaration, which together covers all cases.
9295       //
9296       // A dependent typename using declaration will never successfully
9297       // instantiate, since it will always name a class member, so we reject
9298       // that in the template definition.
9299     }
9300   }
9301 
9302   // Check for invalid redeclarations.
9303   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9304                                   SS, IdentLoc, Previous))
9305     return nullptr;
9306 
9307   // Check for bad qualifiers.
9308   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9309                               IdentLoc))
9310     return nullptr;
9311 
9312   DeclContext *LookupContext = computeDeclContext(SS);
9313   NamedDecl *D;
9314   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9315   if (!LookupContext || EllipsisLoc.isValid()) {
9316     if (HasTypenameKeyword) {
9317       // FIXME: not all declaration name kinds are legal here
9318       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9319                                               UsingLoc, TypenameLoc,
9320                                               QualifierLoc,
9321                                               IdentLoc, NameInfo.getName(),
9322                                               EllipsisLoc);
9323     } else {
9324       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9325                                            QualifierLoc, NameInfo, EllipsisLoc);
9326     }
9327     D->setAccess(AS);
9328     CurContext->addDecl(D);
9329     return D;
9330   }
9331 
9332   auto Build = [&](bool Invalid) {
9333     UsingDecl *UD =
9334         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9335                           UsingName, HasTypenameKeyword);
9336     UD->setAccess(AS);
9337     CurContext->addDecl(UD);
9338     UD->setInvalidDecl(Invalid);
9339     return UD;
9340   };
9341   auto BuildInvalid = [&]{ return Build(true); };
9342   auto BuildValid = [&]{ return Build(false); };
9343 
9344   if (RequireCompleteDeclContext(SS, LookupContext))
9345     return BuildInvalid();
9346 
9347   // Look up the target name.
9348   LookupResult R(*this, NameInfo, LookupOrdinaryName);
9349 
9350   // Unlike most lookups, we don't always want to hide tag
9351   // declarations: tag names are visible through the using declaration
9352   // even if hidden by ordinary names, *except* in a dependent context
9353   // where it's important for the sanity of two-phase lookup.
9354   if (!IsInstantiation)
9355     R.setHideTags(false);
9356 
9357   // For the purposes of this lookup, we have a base object type
9358   // equal to that of the current context.
9359   if (CurContext->isRecord()) {
9360     R.setBaseObjectType(
9361                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9362   }
9363 
9364   LookupQualifiedName(R, LookupContext);
9365 
9366   // Try to correct typos if possible. If constructor name lookup finds no
9367   // results, that means the named class has no explicit constructors, and we
9368   // suppressed declaring implicit ones (probably because it's dependent or
9369   // invalid).
9370   if (R.empty() &&
9371       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9372     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9373     // it will believe that glibc provides a ::gets in cases where it does not,
9374     // and will try to pull it into namespace std with a using-declaration.
9375     // Just ignore the using-declaration in that case.
9376     auto *II = NameInfo.getName().getAsIdentifierInfo();
9377     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9378         CurContext->isStdNamespace() &&
9379         isa<TranslationUnitDecl>(LookupContext) &&
9380         getSourceManager().isInSystemHeader(UsingLoc))
9381       return nullptr;
9382     if (TypoCorrection Corrected = CorrectTypo(
9383             R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9384             llvm::make_unique<UsingValidatorCCC>(
9385                 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9386                 dyn_cast<CXXRecordDecl>(CurContext)),
9387             CTK_ErrorRecovery)) {
9388       // We reject candidates where DroppedSpecifier == true, hence the
9389       // literal '0' below.
9390       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9391                                 << NameInfo.getName() << LookupContext << 0
9392                                 << SS.getRange());
9393 
9394       // If we picked a correction with no attached Decl we can't do anything
9395       // useful with it, bail out.
9396       NamedDecl *ND = Corrected.getCorrectionDecl();
9397       if (!ND)
9398         return BuildInvalid();
9399 
9400       // If we corrected to an inheriting constructor, handle it as one.
9401       auto *RD = dyn_cast<CXXRecordDecl>(ND);
9402       if (RD && RD->isInjectedClassName()) {
9403         // The parent of the injected class name is the class itself.
9404         RD = cast<CXXRecordDecl>(RD->getParent());
9405 
9406         // Fix up the information we'll use to build the using declaration.
9407         if (Corrected.WillReplaceSpecifier()) {
9408           NestedNameSpecifierLocBuilder Builder;
9409           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9410                               QualifierLoc.getSourceRange());
9411           QualifierLoc = Builder.getWithLocInContext(Context);
9412         }
9413 
9414         // In this case, the name we introduce is the name of a derived class
9415         // constructor.
9416         auto *CurClass = cast<CXXRecordDecl>(CurContext);
9417         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9418             Context.getCanonicalType(Context.getRecordType(CurClass))));
9419         UsingName.setNamedTypeInfo(nullptr);
9420         for (auto *Ctor : LookupConstructors(RD))
9421           R.addDecl(Ctor);
9422         R.resolveKind();
9423       } else {
9424         // FIXME: Pick up all the declarations if we found an overloaded
9425         // function.
9426         UsingName.setName(ND->getDeclName());
9427         R.addDecl(ND);
9428       }
9429     } else {
9430       Diag(IdentLoc, diag::err_no_member)
9431         << NameInfo.getName() << LookupContext << SS.getRange();
9432       return BuildInvalid();
9433     }
9434   }
9435 
9436   if (R.isAmbiguous())
9437     return BuildInvalid();
9438 
9439   if (HasTypenameKeyword) {
9440     // If we asked for a typename and got a non-type decl, error out.
9441     if (!R.getAsSingle<TypeDecl>()) {
9442       Diag(IdentLoc, diag::err_using_typename_non_type);
9443       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9444         Diag((*I)->getUnderlyingDecl()->getLocation(),
9445              diag::note_using_decl_target);
9446       return BuildInvalid();
9447     }
9448   } else {
9449     // If we asked for a non-typename and we got a type, error out,
9450     // but only if this is an instantiation of an unresolved using
9451     // decl.  Otherwise just silently find the type name.
9452     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9453       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9454       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9455       return BuildInvalid();
9456     }
9457   }
9458 
9459   // C++14 [namespace.udecl]p6:
9460   // A using-declaration shall not name a namespace.
9461   if (R.getAsSingle<NamespaceDecl>()) {
9462     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9463       << SS.getRange();
9464     return BuildInvalid();
9465   }
9466 
9467   // C++14 [namespace.udecl]p7:
9468   // A using-declaration shall not name a scoped enumerator.
9469   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9470     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9471       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9472         << SS.getRange();
9473       return BuildInvalid();
9474     }
9475   }
9476 
9477   UsingDecl *UD = BuildValid();
9478 
9479   // Some additional rules apply to inheriting constructors.
9480   if (UsingName.getName().getNameKind() ==
9481         DeclarationName::CXXConstructorName) {
9482     // Suppress access diagnostics; the access check is instead performed at the
9483     // point of use for an inheriting constructor.
9484     R.suppressDiagnostics();
9485     if (CheckInheritingConstructorUsingDecl(UD))
9486       return UD;
9487   }
9488 
9489   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9490     UsingShadowDecl *PrevDecl = nullptr;
9491     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9492       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9493   }
9494 
9495   return UD;
9496 }
9497 
9498 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9499                                     ArrayRef<NamedDecl *> Expansions) {
9500   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9501          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9502          isa<UsingPackDecl>(InstantiatedFrom));
9503 
9504   auto *UPD =
9505       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9506   UPD->setAccess(InstantiatedFrom->getAccess());
9507   CurContext->addDecl(UPD);
9508   return UPD;
9509 }
9510 
9511 /// Additional checks for a using declaration referring to a constructor name.
9512 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9513   assert(!UD->hasTypename() && "expecting a constructor name");
9514 
9515   const Type *SourceType = UD->getQualifier()->getAsType();
9516   assert(SourceType &&
9517          "Using decl naming constructor doesn't have type in scope spec.");
9518   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9519 
9520   // Check whether the named type is a direct base class.
9521   bool AnyDependentBases = false;
9522   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9523                                       AnyDependentBases);
9524   if (!Base && !AnyDependentBases) {
9525     Diag(UD->getUsingLoc(),
9526          diag::err_using_decl_constructor_not_in_direct_base)
9527       << UD->getNameInfo().getSourceRange()
9528       << QualType(SourceType, 0) << TargetClass;
9529     UD->setInvalidDecl();
9530     return true;
9531   }
9532 
9533   if (Base)
9534     Base->setInheritConstructors();
9535 
9536   return false;
9537 }
9538 
9539 /// Checks that the given using declaration is not an invalid
9540 /// redeclaration.  Note that this is checking only for the using decl
9541 /// itself, not for any ill-formedness among the UsingShadowDecls.
9542 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9543                                        bool HasTypenameKeyword,
9544                                        const CXXScopeSpec &SS,
9545                                        SourceLocation NameLoc,
9546                                        const LookupResult &Prev) {
9547   NestedNameSpecifier *Qual = SS.getScopeRep();
9548 
9549   // C++03 [namespace.udecl]p8:
9550   // C++0x [namespace.udecl]p10:
9551   //   A using-declaration is a declaration and can therefore be used
9552   //   repeatedly where (and only where) multiple declarations are
9553   //   allowed.
9554   //
9555   // That's in non-member contexts.
9556   if (!CurContext->getRedeclContext()->isRecord()) {
9557     // A dependent qualifier outside a class can only ever resolve to an
9558     // enumeration type. Therefore it conflicts with any other non-type
9559     // declaration in the same scope.
9560     // FIXME: How should we check for dependent type-type conflicts at block
9561     // scope?
9562     if (Qual->isDependent() && !HasTypenameKeyword) {
9563       for (auto *D : Prev) {
9564         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9565           bool OldCouldBeEnumerator =
9566               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9567           Diag(NameLoc,
9568                OldCouldBeEnumerator ? diag::err_redefinition
9569                                     : diag::err_redefinition_different_kind)
9570               << Prev.getLookupName();
9571           Diag(D->getLocation(), diag::note_previous_definition);
9572           return true;
9573         }
9574       }
9575     }
9576     return false;
9577   }
9578 
9579   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9580     NamedDecl *D = *I;
9581 
9582     bool DTypename;
9583     NestedNameSpecifier *DQual;
9584     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9585       DTypename = UD->hasTypename();
9586       DQual = UD->getQualifier();
9587     } else if (UnresolvedUsingValueDecl *UD
9588                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9589       DTypename = false;
9590       DQual = UD->getQualifier();
9591     } else if (UnresolvedUsingTypenameDecl *UD
9592                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9593       DTypename = true;
9594       DQual = UD->getQualifier();
9595     } else continue;
9596 
9597     // using decls differ if one says 'typename' and the other doesn't.
9598     // FIXME: non-dependent using decls?
9599     if (HasTypenameKeyword != DTypename) continue;
9600 
9601     // using decls differ if they name different scopes (but note that
9602     // template instantiation can cause this check to trigger when it
9603     // didn't before instantiation).
9604     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9605         Context.getCanonicalNestedNameSpecifier(DQual))
9606       continue;
9607 
9608     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9609     Diag(D->getLocation(), diag::note_using_decl) << 1;
9610     return true;
9611   }
9612 
9613   return false;
9614 }
9615 
9616 
9617 /// Checks that the given nested-name qualifier used in a using decl
9618 /// in the current context is appropriately related to the current
9619 /// scope.  If an error is found, diagnoses it and returns true.
9620 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9621                                    bool HasTypename,
9622                                    const CXXScopeSpec &SS,
9623                                    const DeclarationNameInfo &NameInfo,
9624                                    SourceLocation NameLoc) {
9625   DeclContext *NamedContext = computeDeclContext(SS);
9626 
9627   if (!CurContext->isRecord()) {
9628     // C++03 [namespace.udecl]p3:
9629     // C++0x [namespace.udecl]p8:
9630     //   A using-declaration for a class member shall be a member-declaration.
9631 
9632     // If we weren't able to compute a valid scope, it might validly be a
9633     // dependent class scope or a dependent enumeration unscoped scope. If
9634     // we have a 'typename' keyword, the scope must resolve to a class type.
9635     if ((HasTypename && !NamedContext) ||
9636         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
9637       auto *RD = NamedContext
9638                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9639                      : nullptr;
9640       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9641         RD = nullptr;
9642 
9643       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9644         << SS.getRange();
9645 
9646       // If we have a complete, non-dependent source type, try to suggest a
9647       // way to get the same effect.
9648       if (!RD)
9649         return true;
9650 
9651       // Find what this using-declaration was referring to.
9652       LookupResult R(*this, NameInfo, LookupOrdinaryName);
9653       R.setHideTags(false);
9654       R.suppressDiagnostics();
9655       LookupQualifiedName(R, RD);
9656 
9657       if (R.getAsSingle<TypeDecl>()) {
9658         if (getLangOpts().CPlusPlus11) {
9659           // Convert 'using X::Y;' to 'using Y = X::Y;'.
9660           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9661             << 0 // alias declaration
9662             << FixItHint::CreateInsertion(SS.getBeginLoc(),
9663                                           NameInfo.getName().getAsString() +
9664                                               " = ");
9665         } else {
9666           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9667           SourceLocation InsertLoc =
9668               getLocForEndOfToken(NameInfo.getLocEnd());
9669           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9670             << 1 // typedef declaration
9671             << FixItHint::CreateReplacement(UsingLoc, "typedef")
9672             << FixItHint::CreateInsertion(
9673                    InsertLoc, " " + NameInfo.getName().getAsString());
9674         }
9675       } else if (R.getAsSingle<VarDecl>()) {
9676         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9677         // repeating the type of the static data member here.
9678         FixItHint FixIt;
9679         if (getLangOpts().CPlusPlus11) {
9680           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9681           FixIt = FixItHint::CreateReplacement(
9682               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9683         }
9684 
9685         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9686           << 2 // reference declaration
9687           << FixIt;
9688       } else if (R.getAsSingle<EnumConstantDecl>()) {
9689         // Don't provide a fixit outside C++11 mode; we don't want to suggest
9690         // repeating the type of the enumeration here, and we can't do so if
9691         // the type is anonymous.
9692         FixItHint FixIt;
9693         if (getLangOpts().CPlusPlus11) {
9694           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9695           FixIt = FixItHint::CreateReplacement(
9696               UsingLoc,
9697               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9698         }
9699 
9700         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9701           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9702           << FixIt;
9703       }
9704       return true;
9705     }
9706 
9707     // Otherwise, this might be valid.
9708     return false;
9709   }
9710 
9711   // The current scope is a record.
9712 
9713   // If the named context is dependent, we can't decide much.
9714   if (!NamedContext) {
9715     // FIXME: in C++0x, we can diagnose if we can prove that the
9716     // nested-name-specifier does not refer to a base class, which is
9717     // still possible in some cases.
9718 
9719     // Otherwise we have to conservatively report that things might be
9720     // okay.
9721     return false;
9722   }
9723 
9724   if (!NamedContext->isRecord()) {
9725     // Ideally this would point at the last name in the specifier,
9726     // but we don't have that level of source info.
9727     Diag(SS.getRange().getBegin(),
9728          diag::err_using_decl_nested_name_specifier_is_not_class)
9729       << SS.getScopeRep() << SS.getRange();
9730     return true;
9731   }
9732 
9733   if (!NamedContext->isDependentContext() &&
9734       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9735     return true;
9736 
9737   if (getLangOpts().CPlusPlus11) {
9738     // C++11 [namespace.udecl]p3:
9739     //   In a using-declaration used as a member-declaration, the
9740     //   nested-name-specifier shall name a base class of the class
9741     //   being defined.
9742 
9743     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9744                                  cast<CXXRecordDecl>(NamedContext))) {
9745       if (CurContext == NamedContext) {
9746         Diag(NameLoc,
9747              diag::err_using_decl_nested_name_specifier_is_current_class)
9748           << SS.getRange();
9749         return true;
9750       }
9751 
9752       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9753         Diag(SS.getRange().getBegin(),
9754              diag::err_using_decl_nested_name_specifier_is_not_base_class)
9755           << SS.getScopeRep()
9756           << cast<CXXRecordDecl>(CurContext)
9757           << SS.getRange();
9758       }
9759       return true;
9760     }
9761 
9762     return false;
9763   }
9764 
9765   // C++03 [namespace.udecl]p4:
9766   //   A using-declaration used as a member-declaration shall refer
9767   //   to a member of a base class of the class being defined [etc.].
9768 
9769   // Salient point: SS doesn't have to name a base class as long as
9770   // lookup only finds members from base classes.  Therefore we can
9771   // diagnose here only if we can prove that that can't happen,
9772   // i.e. if the class hierarchies provably don't intersect.
9773 
9774   // TODO: it would be nice if "definitely valid" results were cached
9775   // in the UsingDecl and UsingShadowDecl so that these checks didn't
9776   // need to be repeated.
9777 
9778   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9779   auto Collect = [&Bases](const CXXRecordDecl *Base) {
9780     Bases.insert(Base);
9781     return true;
9782   };
9783 
9784   // Collect all bases. Return false if we find a dependent base.
9785   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9786     return false;
9787 
9788   // Returns true if the base is dependent or is one of the accumulated base
9789   // classes.
9790   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9791     return !Bases.count(Base);
9792   };
9793 
9794   // Return false if the class has a dependent base or if it or one
9795   // of its bases is present in the base set of the current context.
9796   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9797       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9798     return false;
9799 
9800   Diag(SS.getRange().getBegin(),
9801        diag::err_using_decl_nested_name_specifier_is_not_base_class)
9802     << SS.getScopeRep()
9803     << cast<CXXRecordDecl>(CurContext)
9804     << SS.getRange();
9805 
9806   return true;
9807 }
9808 
9809 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9810                                   AccessSpecifier AS,
9811                                   MultiTemplateParamsArg TemplateParamLists,
9812                                   SourceLocation UsingLoc,
9813                                   UnqualifiedId &Name,
9814                                   AttributeList *AttrList,
9815                                   TypeResult Type,
9816                                   Decl *DeclFromDeclSpec) {
9817   // Skip up to the relevant declaration scope.
9818   while (S->isTemplateParamScope())
9819     S = S->getParent();
9820   assert((S->getFlags() & Scope::DeclScope) &&
9821          "got alias-declaration outside of declaration scope");
9822 
9823   if (Type.isInvalid())
9824     return nullptr;
9825 
9826   bool Invalid = false;
9827   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9828   TypeSourceInfo *TInfo = nullptr;
9829   GetTypeFromParser(Type.get(), &TInfo);
9830 
9831   if (DiagnoseClassNameShadow(CurContext, NameInfo))
9832     return nullptr;
9833 
9834   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9835                                       UPPC_DeclarationType)) {
9836     Invalid = true;
9837     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9838                                              TInfo->getTypeLoc().getBeginLoc());
9839   }
9840 
9841   LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9842   LookupName(Previous, S);
9843 
9844   // Warn about shadowing the name of a template parameter.
9845   if (Previous.isSingleResult() &&
9846       Previous.getFoundDecl()->isTemplateParameter()) {
9847     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9848     Previous.clear();
9849   }
9850 
9851   assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9852          "name in alias declaration must be an identifier");
9853   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9854                                                Name.StartLocation,
9855                                                Name.Identifier, TInfo);
9856 
9857   NewTD->setAccess(AS);
9858 
9859   if (Invalid)
9860     NewTD->setInvalidDecl();
9861 
9862   ProcessDeclAttributeList(S, NewTD, AttrList);
9863 
9864   CheckTypedefForVariablyModifiedType(S, NewTD);
9865   Invalid |= NewTD->isInvalidDecl();
9866 
9867   bool Redeclaration = false;
9868 
9869   NamedDecl *NewND;
9870   if (TemplateParamLists.size()) {
9871     TypeAliasTemplateDecl *OldDecl = nullptr;
9872     TemplateParameterList *OldTemplateParams = nullptr;
9873 
9874     if (TemplateParamLists.size() != 1) {
9875       Diag(UsingLoc, diag::err_alias_template_extra_headers)
9876         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9877          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9878     }
9879     TemplateParameterList *TemplateParams = TemplateParamLists[0];
9880 
9881     // Check that we can declare a template here.
9882     if (CheckTemplateDeclScope(S, TemplateParams))
9883       return nullptr;
9884 
9885     // Only consider previous declarations in the same scope.
9886     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9887                          /*ExplicitInstantiationOrSpecialization*/false);
9888     if (!Previous.empty()) {
9889       Redeclaration = true;
9890 
9891       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9892       if (!OldDecl && !Invalid) {
9893         Diag(UsingLoc, diag::err_redefinition_different_kind)
9894           << Name.Identifier;
9895 
9896         NamedDecl *OldD = Previous.getRepresentativeDecl();
9897         if (OldD->getLocation().isValid())
9898           Diag(OldD->getLocation(), diag::note_previous_definition);
9899 
9900         Invalid = true;
9901       }
9902 
9903       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9904         if (TemplateParameterListsAreEqual(TemplateParams,
9905                                            OldDecl->getTemplateParameters(),
9906                                            /*Complain=*/true,
9907                                            TPL_TemplateMatch))
9908           OldTemplateParams = OldDecl->getTemplateParameters();
9909         else
9910           Invalid = true;
9911 
9912         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9913         if (!Invalid &&
9914             !Context.hasSameType(OldTD->getUnderlyingType(),
9915                                  NewTD->getUnderlyingType())) {
9916           // FIXME: The C++0x standard does not clearly say this is ill-formed,
9917           // but we can't reasonably accept it.
9918           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
9919             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
9920           if (OldTD->getLocation().isValid())
9921             Diag(OldTD->getLocation(), diag::note_previous_definition);
9922           Invalid = true;
9923         }
9924       }
9925     }
9926 
9927     // Merge any previous default template arguments into our parameters,
9928     // and check the parameter list.
9929     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
9930                                    TPC_TypeAliasTemplate))
9931       return nullptr;
9932 
9933     TypeAliasTemplateDecl *NewDecl =
9934       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
9935                                     Name.Identifier, TemplateParams,
9936                                     NewTD);
9937     NewTD->setDescribedAliasTemplate(NewDecl);
9938 
9939     NewDecl->setAccess(AS);
9940 
9941     if (Invalid)
9942       NewDecl->setInvalidDecl();
9943     else if (OldDecl)
9944       NewDecl->setPreviousDecl(OldDecl);
9945 
9946     NewND = NewDecl;
9947   } else {
9948     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
9949       setTagNameForLinkagePurposes(TD, NewTD);
9950       handleTagNumbering(TD, S);
9951     }
9952     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
9953     NewND = NewTD;
9954   }
9955 
9956   PushOnScopeChains(NewND, S);
9957   ActOnDocumentableDecl(NewND);
9958   return NewND;
9959 }
9960 
9961 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
9962                                    SourceLocation AliasLoc,
9963                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
9964                                    SourceLocation IdentLoc,
9965                                    IdentifierInfo *Ident) {
9966 
9967   // Lookup the namespace name.
9968   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
9969   LookupParsedName(R, S, &SS);
9970 
9971   if (R.isAmbiguous())
9972     return nullptr;
9973 
9974   if (R.empty()) {
9975     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
9976       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9977       return nullptr;
9978     }
9979   }
9980   assert(!R.isAmbiguous() && !R.empty());
9981   NamedDecl *ND = R.getRepresentativeDecl();
9982 
9983   // Check if we have a previous declaration with the same name.
9984   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
9985                      ForRedeclaration);
9986   LookupName(PrevR, S);
9987 
9988   // Check we're not shadowing a template parameter.
9989   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
9990     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
9991     PrevR.clear();
9992   }
9993 
9994   // Filter out any other lookup result from an enclosing scope.
9995   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
9996                        /*AllowInlineNamespace*/false);
9997 
9998   // Find the previous declaration and check that we can redeclare it.
9999   NamespaceAliasDecl *Prev = nullptr;
10000   if (PrevR.isSingleResult()) {
10001     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10002     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10003       // We already have an alias with the same name that points to the same
10004       // namespace; check that it matches.
10005       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10006         Prev = AD;
10007       } else if (isVisible(PrevDecl)) {
10008         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10009           << Alias;
10010         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10011           << AD->getNamespace();
10012         return nullptr;
10013       }
10014     } else if (isVisible(PrevDecl)) {
10015       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10016                             ? diag::err_redefinition
10017                             : diag::err_redefinition_different_kind;
10018       Diag(AliasLoc, DiagID) << Alias;
10019       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10020       return nullptr;
10021     }
10022   }
10023 
10024   // The use of a nested name specifier may trigger deprecation warnings.
10025   DiagnoseUseOfDecl(ND, IdentLoc);
10026 
10027   NamespaceAliasDecl *AliasDecl =
10028     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10029                                Alias, SS.getWithLocInContext(Context),
10030                                IdentLoc, ND);
10031   if (Prev)
10032     AliasDecl->setPreviousDecl(Prev);
10033 
10034   PushOnScopeChains(AliasDecl, S);
10035   return AliasDecl;
10036 }
10037 
10038 Sema::ImplicitExceptionSpecification
10039 Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
10040                                                CXXMethodDecl *MD) {
10041   CXXRecordDecl *ClassDecl = MD->getParent();
10042 
10043   // C++ [except.spec]p14:
10044   //   An implicitly declared special member function (Clause 12) shall have an
10045   //   exception-specification. [...]
10046   ImplicitExceptionSpecification ExceptSpec(*this);
10047   if (ClassDecl->isInvalidDecl())
10048     return ExceptSpec;
10049 
10050   // Direct base-class constructors.
10051   for (const auto &B : ClassDecl->bases()) {
10052     if (B.isVirtual()) // Handled below.
10053       continue;
10054 
10055     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10056       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10057       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
10058       // If this is a deleted function, add it anyway. This might be conformant
10059       // with the standard. This might not. I'm not sure. It might not matter.
10060       if (Constructor)
10061         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10062     }
10063   }
10064 
10065   // Virtual base-class constructors.
10066   for (const auto &B : ClassDecl->vbases()) {
10067     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
10068       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10069       CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
10070       // If this is a deleted function, add it anyway. This might be conformant
10071       // with the standard. This might not. I'm not sure. It might not matter.
10072       if (Constructor)
10073         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10074     }
10075   }
10076 
10077   // Field constructors.
10078   for (auto *F : ClassDecl->fields()) {
10079     if (F->hasInClassInitializer()) {
10080       Expr *E = F->getInClassInitializer();
10081       if (!E)
10082         // FIXME: It's a little wasteful to build and throw away a
10083         // CXXDefaultInitExpr here.
10084         E = BuildCXXDefaultInitExpr(Loc, F).get();
10085       if (E)
10086         ExceptSpec.CalledExpr(E);
10087     } else if (const RecordType *RecordTy
10088               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
10089       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10090       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
10091       // If this is a deleted function, add it anyway. This might be conformant
10092       // with the standard. This might not. I'm not sure. It might not matter.
10093       // In particular, the problem is that this function never gets called. It
10094       // might just be ill-formed because this function attempts to refer to
10095       // a deleted function here.
10096       if (Constructor)
10097         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10098     }
10099   }
10100 
10101   return ExceptSpec;
10102 }
10103 
10104 Sema::ImplicitExceptionSpecification
10105 Sema::ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
10106                                          CXXConstructorDecl *CD) {
10107   CXXRecordDecl *ClassDecl = CD->getParent();
10108 
10109   // C++ [except.spec]p14:
10110   //   An inheriting constructor [...] shall have an exception-specification. [...]
10111   ImplicitExceptionSpecification ExceptSpec(*this);
10112   if (ClassDecl->isInvalidDecl())
10113     return ExceptSpec;
10114 
10115   auto Inherited = CD->getInheritedConstructor();
10116   InheritedConstructorInfo ICI(*this, Loc, Inherited.getShadowDecl());
10117 
10118   // Direct and virtual base-class constructors.
10119   for (bool VBase : {false, true}) {
10120     for (CXXBaseSpecifier &B :
10121          VBase ? ClassDecl->vbases() : ClassDecl->bases()) {
10122       // Don't visit direct vbases twice.
10123       if (B.isVirtual() != VBase)
10124         continue;
10125 
10126       CXXRecordDecl *BaseClass = B.getType()->getAsCXXRecordDecl();
10127       if (!BaseClass)
10128         continue;
10129 
10130       CXXConstructorDecl *Constructor =
10131           ICI.findConstructorForBase(BaseClass, Inherited.getConstructor())
10132               .first;
10133       if (!Constructor)
10134         Constructor = LookupDefaultConstructor(BaseClass);
10135       if (Constructor)
10136         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
10137     }
10138   }
10139 
10140   // Field constructors.
10141   for (const auto *F : ClassDecl->fields()) {
10142     if (F->hasInClassInitializer()) {
10143       if (Expr *E = F->getInClassInitializer())
10144         ExceptSpec.CalledExpr(E);
10145     } else if (const RecordType *RecordTy
10146               = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
10147       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10148       CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
10149       if (Constructor)
10150         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10151     }
10152   }
10153 
10154   return ExceptSpec;
10155 }
10156 
10157 namespace {
10158 /// RAII object to register a special member as being currently declared.
10159 struct DeclaringSpecialMember {
10160   Sema &S;
10161   Sema::SpecialMemberDecl D;
10162   Sema::ContextRAII SavedContext;
10163   bool WasAlreadyBeingDeclared;
10164 
10165   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10166     : S(S), D(RD, CSM), SavedContext(S, RD) {
10167     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10168     if (WasAlreadyBeingDeclared)
10169       // This almost never happens, but if it does, ensure that our cache
10170       // doesn't contain a stale result.
10171       S.SpecialMemberCache.clear();
10172 
10173     // FIXME: Register a note to be produced if we encounter an error while
10174     // declaring the special member.
10175   }
10176   ~DeclaringSpecialMember() {
10177     if (!WasAlreadyBeingDeclared)
10178       S.SpecialMembersBeingDeclared.erase(D);
10179   }
10180 
10181   /// \brief Are we already trying to declare this special member?
10182   bool isAlreadyBeingDeclared() const {
10183     return WasAlreadyBeingDeclared;
10184   }
10185 };
10186 }
10187 
10188 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10189   // Look up any existing declarations, but don't trigger declaration of all
10190   // implicit special members with this name.
10191   DeclarationName Name = FD->getDeclName();
10192   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10193                  ForRedeclaration);
10194   for (auto *D : FD->getParent()->lookup(Name))
10195     if (auto *Acceptable = R.getAcceptableDecl(D))
10196       R.addDecl(Acceptable);
10197   R.resolveKind();
10198   R.suppressDiagnostics();
10199 
10200   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10201 }
10202 
10203 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10204                                                      CXXRecordDecl *ClassDecl) {
10205   // C++ [class.ctor]p5:
10206   //   A default constructor for a class X is a constructor of class X
10207   //   that can be called without an argument. If there is no
10208   //   user-declared constructor for class X, a default constructor is
10209   //   implicitly declared. An implicitly-declared default constructor
10210   //   is an inline public member of its class.
10211   assert(ClassDecl->needsImplicitDefaultConstructor() &&
10212          "Should not build implicit default constructor!");
10213 
10214   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10215   if (DSM.isAlreadyBeingDeclared())
10216     return nullptr;
10217 
10218   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10219                                                      CXXDefaultConstructor,
10220                                                      false);
10221 
10222   // Create the actual constructor declaration.
10223   CanQualType ClassType
10224     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10225   SourceLocation ClassLoc = ClassDecl->getLocation();
10226   DeclarationName Name
10227     = Context.DeclarationNames.getCXXConstructorName(ClassType);
10228   DeclarationNameInfo NameInfo(Name, ClassLoc);
10229   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10230       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10231       /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10232       /*isImplicitlyDeclared=*/true, Constexpr);
10233   DefaultCon->setAccess(AS_public);
10234   DefaultCon->setDefaulted();
10235 
10236   if (getLangOpts().CUDA) {
10237     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10238                                             DefaultCon,
10239                                             /* ConstRHS */ false,
10240                                             /* Diagnose */ false);
10241   }
10242 
10243   // Build an exception specification pointing back at this constructor.
10244   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10245   DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10246 
10247   // We don't need to use SpecialMemberIsTrivial here; triviality for default
10248   // constructors is easy to compute.
10249   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10250 
10251   // Note that we have declared this constructor.
10252   ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10253 
10254   Scope *S = getScopeForContext(ClassDecl);
10255   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10256 
10257   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10258     SetDeclDeleted(DefaultCon, ClassLoc);
10259 
10260   if (S)
10261     PushOnScopeChains(DefaultCon, S, false);
10262   ClassDecl->addDecl(DefaultCon);
10263 
10264   return DefaultCon;
10265 }
10266 
10267 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10268                                             CXXConstructorDecl *Constructor) {
10269   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10270           !Constructor->doesThisDeclarationHaveABody() &&
10271           !Constructor->isDeleted()) &&
10272     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10273 
10274   CXXRecordDecl *ClassDecl = Constructor->getParent();
10275   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10276 
10277   SynthesizedFunctionScope Scope(*this, Constructor);
10278   DiagnosticErrorTrap Trap(Diags);
10279   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
10280       Trap.hasErrorOccurred()) {
10281     Diag(CurrentLocation, diag::note_member_synthesized_at)
10282       << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
10283     Constructor->setInvalidDecl();
10284     return;
10285   }
10286 
10287   // The exception specification is needed because we are defining the
10288   // function.
10289   ResolveExceptionSpec(CurrentLocation,
10290                        Constructor->getType()->castAs<FunctionProtoType>());
10291 
10292   SourceLocation Loc = Constructor->getLocEnd().isValid()
10293                            ? Constructor->getLocEnd()
10294                            : Constructor->getLocation();
10295   Constructor->setBody(new (Context) CompoundStmt(Loc));
10296 
10297   Constructor->markUsed(Context);
10298   MarkVTableUsed(CurrentLocation, ClassDecl);
10299 
10300   if (ASTMutationListener *L = getASTMutationListener()) {
10301     L->CompletedImplicitDefinition(Constructor);
10302   }
10303 
10304   DiagnoseUninitializedFields(*this, Constructor);
10305 }
10306 
10307 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10308   // Perform any delayed checks on exception specifications.
10309   CheckDelayedMemberExceptionSpecs();
10310 }
10311 
10312 /// Find or create the fake constructor we synthesize to model constructing an
10313 /// object of a derived class via a constructor of a base class.
10314 CXXConstructorDecl *
10315 Sema::findInheritingConstructor(SourceLocation Loc,
10316                                 CXXConstructorDecl *BaseCtor,
10317                                 ConstructorUsingShadowDecl *Shadow) {
10318   CXXRecordDecl *Derived = Shadow->getParent();
10319   SourceLocation UsingLoc = Shadow->getLocation();
10320 
10321   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10322   // For now we use the name of the base class constructor as a member of the
10323   // derived class to indicate a (fake) inherited constructor name.
10324   DeclarationName Name = BaseCtor->getDeclName();
10325 
10326   // Check to see if we already have a fake constructor for this inherited
10327   // constructor call.
10328   for (NamedDecl *Ctor : Derived->lookup(Name))
10329     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10330                                ->getInheritedConstructor()
10331                                .getConstructor(),
10332                            BaseCtor))
10333       return cast<CXXConstructorDecl>(Ctor);
10334 
10335   DeclarationNameInfo NameInfo(Name, UsingLoc);
10336   TypeSourceInfo *TInfo =
10337       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10338   FunctionProtoTypeLoc ProtoLoc =
10339       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10340 
10341   // Check the inherited constructor is valid and find the list of base classes
10342   // from which it was inherited.
10343   InheritedConstructorInfo ICI(*this, Loc, Shadow);
10344 
10345   bool Constexpr =
10346       BaseCtor->isConstexpr() &&
10347       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10348                                         false, BaseCtor, &ICI);
10349 
10350   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10351       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10352       BaseCtor->isExplicit(), /*Inline=*/true,
10353       /*ImplicitlyDeclared=*/true, Constexpr,
10354       InheritedConstructor(Shadow, BaseCtor));
10355   if (Shadow->isInvalidDecl())
10356     DerivedCtor->setInvalidDecl();
10357 
10358   // Build an unevaluated exception specification for this fake constructor.
10359   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10360   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10361   EPI.ExceptionSpec.Type = EST_Unevaluated;
10362   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10363   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10364                                                FPT->getParamTypes(), EPI));
10365 
10366   // Build the parameter declarations.
10367   SmallVector<ParmVarDecl *, 16> ParamDecls;
10368   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10369     TypeSourceInfo *TInfo =
10370         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10371     ParmVarDecl *PD = ParmVarDecl::Create(
10372         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10373         FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10374     PD->setScopeInfo(0, I);
10375     PD->setImplicit();
10376     // Ensure attributes are propagated onto parameters (this matters for
10377     // format, pass_object_size, ...).
10378     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10379     ParamDecls.push_back(PD);
10380     ProtoLoc.setParam(I, PD);
10381   }
10382 
10383   // Set up the new constructor.
10384   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10385   DerivedCtor->setAccess(BaseCtor->getAccess());
10386   DerivedCtor->setParams(ParamDecls);
10387   Derived->addDecl(DerivedCtor);
10388 
10389   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10390     SetDeclDeleted(DerivedCtor, UsingLoc);
10391 
10392   return DerivedCtor;
10393 }
10394 
10395 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10396   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10397                                Ctor->getInheritedConstructor().getShadowDecl());
10398   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10399                             /*Diagnose*/true);
10400 }
10401 
10402 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10403                                        CXXConstructorDecl *Constructor) {
10404   CXXRecordDecl *ClassDecl = Constructor->getParent();
10405   assert(Constructor->getInheritedConstructor() &&
10406          !Constructor->doesThisDeclarationHaveABody() &&
10407          !Constructor->isDeleted());
10408   if (Constructor->isInvalidDecl())
10409     return;
10410 
10411   ConstructorUsingShadowDecl *Shadow =
10412       Constructor->getInheritedConstructor().getShadowDecl();
10413   CXXConstructorDecl *InheritedCtor =
10414       Constructor->getInheritedConstructor().getConstructor();
10415 
10416   // [class.inhctor.init]p1:
10417   //   initialization proceeds as if a defaulted default constructor is used to
10418   //   initialize the D object and each base class subobject from which the
10419   //   constructor was inherited
10420 
10421   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10422   CXXRecordDecl *RD = Shadow->getParent();
10423   SourceLocation InitLoc = Shadow->getLocation();
10424 
10425   // Initializations are performed "as if by a defaulted default constructor",
10426   // so enter the appropriate scope.
10427   SynthesizedFunctionScope Scope(*this, Constructor);
10428   DiagnosticErrorTrap Trap(Diags);
10429 
10430   // Build explicit initializers for all base classes from which the
10431   // constructor was inherited.
10432   SmallVector<CXXCtorInitializer*, 8> Inits;
10433   for (bool VBase : {false, true}) {
10434     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10435       if (B.isVirtual() != VBase)
10436         continue;
10437 
10438       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10439       if (!BaseRD)
10440         continue;
10441 
10442       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10443       if (!BaseCtor.first)
10444         continue;
10445 
10446       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10447       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10448           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10449 
10450       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10451       Inits.push_back(new (Context) CXXCtorInitializer(
10452           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10453           SourceLocation()));
10454     }
10455   }
10456 
10457   // We now proceed as if for a defaulted default constructor, with the relevant
10458   // initializers replaced.
10459 
10460   bool HadError = SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits);
10461   if (HadError || Trap.hasErrorOccurred()) {
10462     Diag(CurrentLocation, diag::note_inhctor_synthesized_at) << RD;
10463     Constructor->setInvalidDecl();
10464     return;
10465   }
10466 
10467   // The exception specification is needed because we are defining the
10468   // function.
10469   ResolveExceptionSpec(CurrentLocation,
10470                        Constructor->getType()->castAs<FunctionProtoType>());
10471 
10472   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10473 
10474   Constructor->markUsed(Context);
10475   MarkVTableUsed(CurrentLocation, ClassDecl);
10476 
10477   if (ASTMutationListener *L = getASTMutationListener()) {
10478     L->CompletedImplicitDefinition(Constructor);
10479   }
10480 
10481   DiagnoseUninitializedFields(*this, Constructor);
10482 }
10483 
10484 Sema::ImplicitExceptionSpecification
10485 Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
10486   CXXRecordDecl *ClassDecl = MD->getParent();
10487 
10488   // C++ [except.spec]p14:
10489   //   An implicitly declared special member function (Clause 12) shall have
10490   //   an exception-specification.
10491   ImplicitExceptionSpecification ExceptSpec(*this);
10492   if (ClassDecl->isInvalidDecl())
10493     return ExceptSpec;
10494 
10495   // Direct base-class destructors.
10496   for (const auto &B : ClassDecl->bases()) {
10497     if (B.isVirtual()) // Handled below.
10498       continue;
10499 
10500     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10501       ExceptSpec.CalledDecl(B.getLocStart(),
10502                    LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10503   }
10504 
10505   // Virtual base-class destructors.
10506   for (const auto &B : ClassDecl->vbases()) {
10507     if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
10508       ExceptSpec.CalledDecl(B.getLocStart(),
10509                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
10510   }
10511 
10512   // Field destructors.
10513   for (const auto *F : ClassDecl->fields()) {
10514     if (const RecordType *RecordTy
10515         = Context.getBaseElementType(F->getType())->getAs<RecordType>())
10516       ExceptSpec.CalledDecl(F->getLocation(),
10517                   LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
10518   }
10519 
10520   return ExceptSpec;
10521 }
10522 
10523 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10524   // C++ [class.dtor]p2:
10525   //   If a class has no user-declared destructor, a destructor is
10526   //   declared implicitly. An implicitly-declared destructor is an
10527   //   inline public member of its class.
10528   assert(ClassDecl->needsImplicitDestructor());
10529 
10530   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10531   if (DSM.isAlreadyBeingDeclared())
10532     return nullptr;
10533 
10534   // Create the actual destructor declaration.
10535   CanQualType ClassType
10536     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10537   SourceLocation ClassLoc = ClassDecl->getLocation();
10538   DeclarationName Name
10539     = Context.DeclarationNames.getCXXDestructorName(ClassType);
10540   DeclarationNameInfo NameInfo(Name, ClassLoc);
10541   CXXDestructorDecl *Destructor
10542       = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10543                                   QualType(), nullptr, /*isInline=*/true,
10544                                   /*isImplicitlyDeclared=*/true);
10545   Destructor->setAccess(AS_public);
10546   Destructor->setDefaulted();
10547 
10548   if (getLangOpts().CUDA) {
10549     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10550                                             Destructor,
10551                                             /* ConstRHS */ false,
10552                                             /* Diagnose */ false);
10553   }
10554 
10555   // Build an exception specification pointing back at this destructor.
10556   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10557   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10558 
10559   // We don't need to use SpecialMemberIsTrivial here; triviality for
10560   // destructors is easy to compute.
10561   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10562 
10563   // Note that we have declared this destructor.
10564   ++ASTContext::NumImplicitDestructorsDeclared;
10565 
10566   Scope *S = getScopeForContext(ClassDecl);
10567   CheckImplicitSpecialMemberDeclaration(S, Destructor);
10568 
10569   // We can't check whether an implicit destructor is deleted before we complete
10570   // the definition of the class, because its validity depends on the alignment
10571   // of the class. We'll check this from ActOnFields once the class is complete.
10572   if (ClassDecl->isCompleteDefinition() &&
10573       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10574     SetDeclDeleted(Destructor, ClassLoc);
10575 
10576   // Introduce this destructor into its scope.
10577   if (S)
10578     PushOnScopeChains(Destructor, S, false);
10579   ClassDecl->addDecl(Destructor);
10580 
10581   return Destructor;
10582 }
10583 
10584 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10585                                     CXXDestructorDecl *Destructor) {
10586   assert((Destructor->isDefaulted() &&
10587           !Destructor->doesThisDeclarationHaveABody() &&
10588           !Destructor->isDeleted()) &&
10589          "DefineImplicitDestructor - call it for implicit default dtor");
10590   CXXRecordDecl *ClassDecl = Destructor->getParent();
10591   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10592 
10593   if (Destructor->isInvalidDecl())
10594     return;
10595 
10596   SynthesizedFunctionScope Scope(*this, Destructor);
10597 
10598   DiagnosticErrorTrap Trap(Diags);
10599   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10600                                          Destructor->getParent());
10601 
10602   if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
10603     Diag(CurrentLocation, diag::note_member_synthesized_at)
10604       << CXXDestructor << Context.getTagDeclType(ClassDecl);
10605 
10606     Destructor->setInvalidDecl();
10607     return;
10608   }
10609 
10610   // The exception specification is needed because we are defining the
10611   // function.
10612   ResolveExceptionSpec(CurrentLocation,
10613                        Destructor->getType()->castAs<FunctionProtoType>());
10614 
10615   SourceLocation Loc = Destructor->getLocEnd().isValid()
10616                            ? Destructor->getLocEnd()
10617                            : Destructor->getLocation();
10618   Destructor->setBody(new (Context) CompoundStmt(Loc));
10619   Destructor->markUsed(Context);
10620   MarkVTableUsed(CurrentLocation, ClassDecl);
10621 
10622   if (ASTMutationListener *L = getASTMutationListener()) {
10623     L->CompletedImplicitDefinition(Destructor);
10624   }
10625 }
10626 
10627 /// \brief Perform any semantic analysis which needs to be delayed until all
10628 /// pending class member declarations have been parsed.
10629 void Sema::ActOnFinishCXXMemberDecls() {
10630   // If the context is an invalid C++ class, just suppress these checks.
10631   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10632     if (Record->isInvalidDecl()) {
10633       DelayedDefaultedMemberExceptionSpecs.clear();
10634       DelayedExceptionSpecChecks.clear();
10635       return;
10636     }
10637     checkForMultipleExportedDefaultConstructors(*this, Record);
10638   }
10639 }
10640 
10641 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10642   referenceDLLExportedClassMethods();
10643 }
10644 
10645 void Sema::referenceDLLExportedClassMethods() {
10646   if (!DelayedDllExportClasses.empty()) {
10647     // Calling ReferenceDllExportedMethods might cause the current function to
10648     // be called again, so use a local copy of DelayedDllExportClasses.
10649     SmallVector<CXXRecordDecl *, 4> WorkList;
10650     std::swap(DelayedDllExportClasses, WorkList);
10651     for (CXXRecordDecl *Class : WorkList)
10652       ReferenceDllExportedMethods(*this, Class);
10653   }
10654 }
10655 
10656 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10657                                          CXXDestructorDecl *Destructor) {
10658   assert(getLangOpts().CPlusPlus11 &&
10659          "adjusting dtor exception specs was introduced in c++11");
10660 
10661   // C++11 [class.dtor]p3:
10662   //   A declaration of a destructor that does not have an exception-
10663   //   specification is implicitly considered to have the same exception-
10664   //   specification as an implicit declaration.
10665   const FunctionProtoType *DtorType = Destructor->getType()->
10666                                         getAs<FunctionProtoType>();
10667   if (DtorType->hasExceptionSpec())
10668     return;
10669 
10670   // Replace the destructor's type, building off the existing one. Fortunately,
10671   // the only thing of interest in the destructor type is its extended info.
10672   // The return and arguments are fixed.
10673   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10674   EPI.ExceptionSpec.Type = EST_Unevaluated;
10675   EPI.ExceptionSpec.SourceDecl = Destructor;
10676   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10677 
10678   // FIXME: If the destructor has a body that could throw, and the newly created
10679   // spec doesn't allow exceptions, we should emit a warning, because this
10680   // change in behavior can break conforming C++03 programs at runtime.
10681   // However, we don't have a body or an exception specification yet, so it
10682   // needs to be done somewhere else.
10683 }
10684 
10685 namespace {
10686 /// \brief An abstract base class for all helper classes used in building the
10687 //  copy/move operators. These classes serve as factory functions and help us
10688 //  avoid using the same Expr* in the AST twice.
10689 class ExprBuilder {
10690   ExprBuilder(const ExprBuilder&) = delete;
10691   ExprBuilder &operator=(const ExprBuilder&) = delete;
10692 
10693 protected:
10694   static Expr *assertNotNull(Expr *E) {
10695     assert(E && "Expression construction must not fail.");
10696     return E;
10697   }
10698 
10699 public:
10700   ExprBuilder() {}
10701   virtual ~ExprBuilder() {}
10702 
10703   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10704 };
10705 
10706 class RefBuilder: public ExprBuilder {
10707   VarDecl *Var;
10708   QualType VarType;
10709 
10710 public:
10711   Expr *build(Sema &S, SourceLocation Loc) const override {
10712     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10713   }
10714 
10715   RefBuilder(VarDecl *Var, QualType VarType)
10716       : Var(Var), VarType(VarType) {}
10717 };
10718 
10719 class ThisBuilder: public ExprBuilder {
10720 public:
10721   Expr *build(Sema &S, SourceLocation Loc) const override {
10722     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10723   }
10724 };
10725 
10726 class CastBuilder: public ExprBuilder {
10727   const ExprBuilder &Builder;
10728   QualType Type;
10729   ExprValueKind Kind;
10730   const CXXCastPath &Path;
10731 
10732 public:
10733   Expr *build(Sema &S, SourceLocation Loc) const override {
10734     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10735                                              CK_UncheckedDerivedToBase, Kind,
10736                                              &Path).get());
10737   }
10738 
10739   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10740               const CXXCastPath &Path)
10741       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10742 };
10743 
10744 class DerefBuilder: public ExprBuilder {
10745   const ExprBuilder &Builder;
10746 
10747 public:
10748   Expr *build(Sema &S, SourceLocation Loc) const override {
10749     return assertNotNull(
10750         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10751   }
10752 
10753   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10754 };
10755 
10756 class MemberBuilder: public ExprBuilder {
10757   const ExprBuilder &Builder;
10758   QualType Type;
10759   CXXScopeSpec SS;
10760   bool IsArrow;
10761   LookupResult &MemberLookup;
10762 
10763 public:
10764   Expr *build(Sema &S, SourceLocation Loc) const override {
10765     return assertNotNull(S.BuildMemberReferenceExpr(
10766         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10767         nullptr, MemberLookup, nullptr, nullptr).get());
10768   }
10769 
10770   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10771                 LookupResult &MemberLookup)
10772       : Builder(Builder), Type(Type), IsArrow(IsArrow),
10773         MemberLookup(MemberLookup) {}
10774 };
10775 
10776 class MoveCastBuilder: public ExprBuilder {
10777   const ExprBuilder &Builder;
10778 
10779 public:
10780   Expr *build(Sema &S, SourceLocation Loc) const override {
10781     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10782   }
10783 
10784   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10785 };
10786 
10787 class LvalueConvBuilder: public ExprBuilder {
10788   const ExprBuilder &Builder;
10789 
10790 public:
10791   Expr *build(Sema &S, SourceLocation Loc) const override {
10792     return assertNotNull(
10793         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10794   }
10795 
10796   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10797 };
10798 
10799 class SubscriptBuilder: public ExprBuilder {
10800   const ExprBuilder &Base;
10801   const ExprBuilder &Index;
10802 
10803 public:
10804   Expr *build(Sema &S, SourceLocation Loc) const override {
10805     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10806         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10807   }
10808 
10809   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10810       : Base(Base), Index(Index) {}
10811 };
10812 
10813 } // end anonymous namespace
10814 
10815 /// When generating a defaulted copy or move assignment operator, if a field
10816 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10817 /// do so. This optimization only applies for arrays of scalars, and for arrays
10818 /// of class type where the selected copy/move-assignment operator is trivial.
10819 static StmtResult
10820 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10821                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
10822   // Compute the size of the memory buffer to be copied.
10823   QualType SizeType = S.Context.getSizeType();
10824   llvm::APInt Size(S.Context.getTypeSize(SizeType),
10825                    S.Context.getTypeSizeInChars(T).getQuantity());
10826 
10827   // Take the address of the field references for "from" and "to". We
10828   // directly construct UnaryOperators here because semantic analysis
10829   // does not permit us to take the address of an xvalue.
10830   Expr *From = FromB.build(S, Loc);
10831   From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10832                          S.Context.getPointerType(From->getType()),
10833                          VK_RValue, OK_Ordinary, Loc);
10834   Expr *To = ToB.build(S, Loc);
10835   To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10836                        S.Context.getPointerType(To->getType()),
10837                        VK_RValue, OK_Ordinary, Loc);
10838 
10839   const Type *E = T->getBaseElementTypeUnsafe();
10840   bool NeedsCollectableMemCpy =
10841     E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10842 
10843   // Create a reference to the __builtin_objc_memmove_collectable function
10844   StringRef MemCpyName = NeedsCollectableMemCpy ?
10845     "__builtin_objc_memmove_collectable" :
10846     "__builtin_memcpy";
10847   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10848                  Sema::LookupOrdinaryName);
10849   S.LookupName(R, S.TUScope, true);
10850 
10851   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10852   if (!MemCpy)
10853     // Something went horribly wrong earlier, and we will have complained
10854     // about it.
10855     return StmtError();
10856 
10857   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10858                                             VK_RValue, Loc, nullptr);
10859   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10860 
10861   Expr *CallArgs[] = {
10862     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10863   };
10864   ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10865                                     Loc, CallArgs, Loc);
10866 
10867   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10868   return Call.getAs<Stmt>();
10869 }
10870 
10871 /// \brief Builds a statement that copies/moves the given entity from \p From to
10872 /// \c To.
10873 ///
10874 /// This routine is used to copy/move the members of a class with an
10875 /// implicitly-declared copy/move assignment operator. When the entities being
10876 /// copied are arrays, this routine builds for loops to copy them.
10877 ///
10878 /// \param S The Sema object used for type-checking.
10879 ///
10880 /// \param Loc The location where the implicit copy/move is being generated.
10881 ///
10882 /// \param T The type of the expressions being copied/moved. Both expressions
10883 /// must have this type.
10884 ///
10885 /// \param To The expression we are copying/moving to.
10886 ///
10887 /// \param From The expression we are copying/moving from.
10888 ///
10889 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10890 /// Otherwise, it's a non-static member subobject.
10891 ///
10892 /// \param Copying Whether we're copying or moving.
10893 ///
10894 /// \param Depth Internal parameter recording the depth of the recursion.
10895 ///
10896 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10897 /// if a memcpy should be used instead.
10898 static StmtResult
10899 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10900                                  const ExprBuilder &To, const ExprBuilder &From,
10901                                  bool CopyingBaseSubobject, bool Copying,
10902                                  unsigned Depth = 0) {
10903   // C++11 [class.copy]p28:
10904   //   Each subobject is assigned in the manner appropriate to its type:
10905   //
10906   //     - if the subobject is of class type, as if by a call to operator= with
10907   //       the subobject as the object expression and the corresponding
10908   //       subobject of x as a single function argument (as if by explicit
10909   //       qualification; that is, ignoring any possible virtual overriding
10910   //       functions in more derived classes);
10911   //
10912   // C++03 [class.copy]p13:
10913   //     - if the subobject is of class type, the copy assignment operator for
10914   //       the class is used (as if by explicit qualification; that is,
10915   //       ignoring any possible virtual overriding functions in more derived
10916   //       classes);
10917   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10918     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10919 
10920     // Look for operator=.
10921     DeclarationName Name
10922       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10923     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10924     S.LookupQualifiedName(OpLookup, ClassDecl, false);
10925 
10926     // Prior to C++11, filter out any result that isn't a copy/move-assignment
10927     // operator.
10928     if (!S.getLangOpts().CPlusPlus11) {
10929       LookupResult::Filter F = OpLookup.makeFilter();
10930       while (F.hasNext()) {
10931         NamedDecl *D = F.next();
10932         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10933           if (Method->isCopyAssignmentOperator() ||
10934               (!Copying && Method->isMoveAssignmentOperator()))
10935             continue;
10936 
10937         F.erase();
10938       }
10939       F.done();
10940     }
10941 
10942     // Suppress the protected check (C++ [class.protected]) for each of the
10943     // assignment operators we found. This strange dance is required when
10944     // we're assigning via a base classes's copy-assignment operator. To
10945     // ensure that we're getting the right base class subobject (without
10946     // ambiguities), we need to cast "this" to that subobject type; to
10947     // ensure that we don't go through the virtual call mechanism, we need
10948     // to qualify the operator= name with the base class (see below). However,
10949     // this means that if the base class has a protected copy assignment
10950     // operator, the protected member access check will fail. So, we
10951     // rewrite "protected" access to "public" access in this case, since we
10952     // know by construction that we're calling from a derived class.
10953     if (CopyingBaseSubobject) {
10954       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
10955            L != LEnd; ++L) {
10956         if (L.getAccess() == AS_protected)
10957           L.setAccess(AS_public);
10958       }
10959     }
10960 
10961     // Create the nested-name-specifier that will be used to qualify the
10962     // reference to operator=; this is required to suppress the virtual
10963     // call mechanism.
10964     CXXScopeSpec SS;
10965     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
10966     SS.MakeTrivial(S.Context,
10967                    NestedNameSpecifier::Create(S.Context, nullptr, false,
10968                                                CanonicalT),
10969                    Loc);
10970 
10971     // Create the reference to operator=.
10972     ExprResult OpEqualRef
10973       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
10974                                    SS, /*TemplateKWLoc=*/SourceLocation(),
10975                                    /*FirstQualifierInScope=*/nullptr,
10976                                    OpLookup,
10977                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
10978                                    /*SuppressQualifierCheck=*/true);
10979     if (OpEqualRef.isInvalid())
10980       return StmtError();
10981 
10982     // Build the call to the assignment operator.
10983 
10984     Expr *FromInst = From.build(S, Loc);
10985     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
10986                                                   OpEqualRef.getAs<Expr>(),
10987                                                   Loc, FromInst, Loc);
10988     if (Call.isInvalid())
10989       return StmtError();
10990 
10991     // If we built a call to a trivial 'operator=' while copying an array,
10992     // bail out. We'll replace the whole shebang with a memcpy.
10993     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
10994     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
10995       return StmtResult((Stmt*)nullptr);
10996 
10997     // Convert to an expression-statement, and clean up any produced
10998     // temporaries.
10999     return S.ActOnExprStmt(Call);
11000   }
11001 
11002   //     - if the subobject is of scalar type, the built-in assignment
11003   //       operator is used.
11004   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11005   if (!ArrayTy) {
11006     ExprResult Assignment = S.CreateBuiltinBinOp(
11007         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11008     if (Assignment.isInvalid())
11009       return StmtError();
11010     return S.ActOnExprStmt(Assignment);
11011   }
11012 
11013   //     - if the subobject is an array, each element is assigned, in the
11014   //       manner appropriate to the element type;
11015 
11016   // Construct a loop over the array bounds, e.g.,
11017   //
11018   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11019   //
11020   // that will copy each of the array elements.
11021   QualType SizeType = S.Context.getSizeType();
11022 
11023   // Create the iteration variable.
11024   IdentifierInfo *IterationVarName = nullptr;
11025   {
11026     SmallString<8> Str;
11027     llvm::raw_svector_ostream OS(Str);
11028     OS << "__i" << Depth;
11029     IterationVarName = &S.Context.Idents.get(OS.str());
11030   }
11031   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11032                                           IterationVarName, SizeType,
11033                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11034                                           SC_None);
11035 
11036   // Initialize the iteration variable to zero.
11037   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11038   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11039 
11040   // Creates a reference to the iteration variable.
11041   RefBuilder IterationVarRef(IterationVar, SizeType);
11042   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11043 
11044   // Create the DeclStmt that holds the iteration variable.
11045   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11046 
11047   // Subscript the "from" and "to" expressions with the iteration variable.
11048   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11049   MoveCastBuilder FromIndexMove(FromIndexCopy);
11050   const ExprBuilder *FromIndex;
11051   if (Copying)
11052     FromIndex = &FromIndexCopy;
11053   else
11054     FromIndex = &FromIndexMove;
11055 
11056   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11057 
11058   // Build the copy/move for an individual element of the array.
11059   StmtResult Copy =
11060     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11061                                      ToIndex, *FromIndex, CopyingBaseSubobject,
11062                                      Copying, Depth + 1);
11063   // Bail out if copying fails or if we determined that we should use memcpy.
11064   if (Copy.isInvalid() || !Copy.get())
11065     return Copy;
11066 
11067   // Create the comparison against the array bound.
11068   llvm::APInt Upper
11069     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11070   Expr *Comparison
11071     = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11072                      IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11073                                      BO_NE, S.Context.BoolTy,
11074                                      VK_RValue, OK_Ordinary, Loc, false);
11075 
11076   // Create the pre-increment of the iteration variable.
11077   Expr *Increment
11078     = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11079                                     SizeType, VK_LValue, OK_Ordinary, Loc);
11080 
11081   // Construct the loop that copies all elements of this array.
11082   return S.ActOnForStmt(
11083       Loc, Loc, InitStmt,
11084       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11085       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11086 }
11087 
11088 static StmtResult
11089 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11090                       const ExprBuilder &To, const ExprBuilder &From,
11091                       bool CopyingBaseSubobject, bool Copying) {
11092   // Maybe we should use a memcpy?
11093   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11094       T.isTriviallyCopyableType(S.Context))
11095     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11096 
11097   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11098                                                      CopyingBaseSubobject,
11099                                                      Copying, 0));
11100 
11101   // If we ended up picking a trivial assignment operator for an array of a
11102   // non-trivially-copyable class type, just emit a memcpy.
11103   if (!Result.isInvalid() && !Result.get())
11104     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11105 
11106   return Result;
11107 }
11108 
11109 Sema::ImplicitExceptionSpecification
11110 Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
11111   CXXRecordDecl *ClassDecl = MD->getParent();
11112 
11113   ImplicitExceptionSpecification ExceptSpec(*this);
11114   if (ClassDecl->isInvalidDecl())
11115     return ExceptSpec;
11116 
11117   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
11118   assert(T->getNumParams() == 1 && "not a copy assignment op");
11119   unsigned ArgQuals =
11120       T->getParamType(0).getNonReferenceType().getCVRQualifiers();
11121 
11122   // C++ [except.spec]p14:
11123   //   An implicitly declared special member function (Clause 12) shall have an
11124   //   exception-specification. [...]
11125 
11126   // It is unspecified whether or not an implicit copy assignment operator
11127   // attempts to deduplicate calls to assignment operators of virtual bases are
11128   // made. As such, this exception specification is effectively unspecified.
11129   // Based on a similar decision made for constness in C++0x, we're erring on
11130   // the side of assuming such calls to be made regardless of whether they
11131   // actually happen.
11132   for (const auto &Base : ClassDecl->bases()) {
11133     if (Base.isVirtual())
11134       continue;
11135 
11136     CXXRecordDecl *BaseClassDecl
11137       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11138     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
11139                                                             ArgQuals, false, 0))
11140       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
11141   }
11142 
11143   for (const auto &Base : ClassDecl->vbases()) {
11144     CXXRecordDecl *BaseClassDecl
11145       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11146     if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
11147                                                             ArgQuals, false, 0))
11148       ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
11149   }
11150 
11151   for (const auto *Field : ClassDecl->fields()) {
11152     QualType FieldType = Context.getBaseElementType(Field->getType());
11153     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11154       if (CXXMethodDecl *CopyAssign =
11155           LookupCopyingAssignment(FieldClassDecl,
11156                                   ArgQuals | FieldType.getCVRQualifiers(),
11157                                   false, 0))
11158         ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
11159     }
11160   }
11161 
11162   return ExceptSpec;
11163 }
11164 
11165 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11166   // Note: The following rules are largely analoguous to the copy
11167   // constructor rules. Note that virtual bases are not taken into account
11168   // for determining the argument type of the operator. Note also that
11169   // operators taking an object instead of a reference are allowed.
11170   assert(ClassDecl->needsImplicitCopyAssignment());
11171 
11172   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11173   if (DSM.isAlreadyBeingDeclared())
11174     return nullptr;
11175 
11176   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11177   QualType RetType = Context.getLValueReferenceType(ArgType);
11178   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11179   if (Const)
11180     ArgType = ArgType.withConst();
11181   ArgType = Context.getLValueReferenceType(ArgType);
11182 
11183   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11184                                                      CXXCopyAssignment,
11185                                                      Const);
11186 
11187   //   An implicitly-declared copy assignment operator is an inline public
11188   //   member of its class.
11189   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11190   SourceLocation ClassLoc = ClassDecl->getLocation();
11191   DeclarationNameInfo NameInfo(Name, ClassLoc);
11192   CXXMethodDecl *CopyAssignment =
11193       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11194                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11195                             /*isInline=*/true, Constexpr, SourceLocation());
11196   CopyAssignment->setAccess(AS_public);
11197   CopyAssignment->setDefaulted();
11198   CopyAssignment->setImplicit();
11199 
11200   if (getLangOpts().CUDA) {
11201     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11202                                             CopyAssignment,
11203                                             /* ConstRHS */ Const,
11204                                             /* Diagnose */ false);
11205   }
11206 
11207   // Build an exception specification pointing back at this member.
11208   FunctionProtoType::ExtProtoInfo EPI =
11209       getImplicitMethodEPI(*this, CopyAssignment);
11210   CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11211 
11212   // Add the parameter to the operator.
11213   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11214                                                ClassLoc, ClassLoc,
11215                                                /*Id=*/nullptr, ArgType,
11216                                                /*TInfo=*/nullptr, SC_None,
11217                                                nullptr);
11218   CopyAssignment->setParams(FromParam);
11219 
11220   CopyAssignment->setTrivial(
11221     ClassDecl->needsOverloadResolutionForCopyAssignment()
11222       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11223       : ClassDecl->hasTrivialCopyAssignment());
11224 
11225   // Note that we have added this copy-assignment operator.
11226   ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11227 
11228   Scope *S = getScopeForContext(ClassDecl);
11229   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11230 
11231   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11232     SetDeclDeleted(CopyAssignment, ClassLoc);
11233 
11234   if (S)
11235     PushOnScopeChains(CopyAssignment, S, false);
11236   ClassDecl->addDecl(CopyAssignment);
11237 
11238   return CopyAssignment;
11239 }
11240 
11241 /// Diagnose an implicit copy operation for a class which is odr-used, but
11242 /// which is deprecated because the class has a user-declared copy constructor,
11243 /// copy assignment operator, or destructor.
11244 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
11245                                             SourceLocation UseLoc) {
11246   assert(CopyOp->isImplicit());
11247 
11248   CXXRecordDecl *RD = CopyOp->getParent();
11249   CXXMethodDecl *UserDeclaredOperation = nullptr;
11250 
11251   // In Microsoft mode, assignment operations don't affect constructors and
11252   // vice versa.
11253   if (RD->hasUserDeclaredDestructor()) {
11254     UserDeclaredOperation = RD->getDestructor();
11255   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11256              RD->hasUserDeclaredCopyConstructor() &&
11257              !S.getLangOpts().MSVCCompat) {
11258     // Find any user-declared copy constructor.
11259     for (auto *I : RD->ctors()) {
11260       if (I->isCopyConstructor()) {
11261         UserDeclaredOperation = I;
11262         break;
11263       }
11264     }
11265     assert(UserDeclaredOperation);
11266   } else if (isa<CXXConstructorDecl>(CopyOp) &&
11267              RD->hasUserDeclaredCopyAssignment() &&
11268              !S.getLangOpts().MSVCCompat) {
11269     // Find any user-declared move assignment operator.
11270     for (auto *I : RD->methods()) {
11271       if (I->isCopyAssignmentOperator()) {
11272         UserDeclaredOperation = I;
11273         break;
11274       }
11275     }
11276     assert(UserDeclaredOperation);
11277   }
11278 
11279   if (UserDeclaredOperation) {
11280     S.Diag(UserDeclaredOperation->getLocation(),
11281          diag::warn_deprecated_copy_operation)
11282       << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11283       << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11284     S.Diag(UseLoc, diag::note_member_synthesized_at)
11285       << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
11286                                           : Sema::CXXCopyAssignment)
11287       << RD;
11288   }
11289 }
11290 
11291 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11292                                         CXXMethodDecl *CopyAssignOperator) {
11293   assert((CopyAssignOperator->isDefaulted() &&
11294           CopyAssignOperator->isOverloadedOperator() &&
11295           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11296           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11297           !CopyAssignOperator->isDeleted()) &&
11298          "DefineImplicitCopyAssignment called for wrong function");
11299 
11300   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11301 
11302   if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
11303     CopyAssignOperator->setInvalidDecl();
11304     return;
11305   }
11306 
11307   // C++11 [class.copy]p18:
11308   //   The [definition of an implicitly declared copy assignment operator] is
11309   //   deprecated if the class has a user-declared copy constructor or a
11310   //   user-declared destructor.
11311   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11312     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
11313 
11314   CopyAssignOperator->markUsed(Context);
11315 
11316   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11317   DiagnosticErrorTrap Trap(Diags);
11318 
11319   // C++0x [class.copy]p30:
11320   //   The implicitly-defined or explicitly-defaulted copy assignment operator
11321   //   for a non-union class X performs memberwise copy assignment of its
11322   //   subobjects. The direct base classes of X are assigned first, in the
11323   //   order of their declaration in the base-specifier-list, and then the
11324   //   immediate non-static data members of X are assigned, in the order in
11325   //   which they were declared in the class definition.
11326 
11327   // The statements that form the synthesized function body.
11328   SmallVector<Stmt*, 8> Statements;
11329 
11330   // The parameter for the "other" object, which we are copying from.
11331   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11332   Qualifiers OtherQuals = Other->getType().getQualifiers();
11333   QualType OtherRefType = Other->getType();
11334   if (const LValueReferenceType *OtherRef
11335                                 = OtherRefType->getAs<LValueReferenceType>()) {
11336     OtherRefType = OtherRef->getPointeeType();
11337     OtherQuals = OtherRefType.getQualifiers();
11338   }
11339 
11340   // Our location for everything implicitly-generated.
11341   SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11342                            ? CopyAssignOperator->getLocEnd()
11343                            : CopyAssignOperator->getLocation();
11344 
11345   // Builds a DeclRefExpr for the "other" object.
11346   RefBuilder OtherRef(Other, OtherRefType);
11347 
11348   // Builds the "this" pointer.
11349   ThisBuilder This;
11350 
11351   // Assign base classes.
11352   bool Invalid = false;
11353   for (auto &Base : ClassDecl->bases()) {
11354     // Form the assignment:
11355     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11356     QualType BaseType = Base.getType().getUnqualifiedType();
11357     if (!BaseType->isRecordType()) {
11358       Invalid = true;
11359       continue;
11360     }
11361 
11362     CXXCastPath BasePath;
11363     BasePath.push_back(&Base);
11364 
11365     // Construct the "from" expression, which is an implicit cast to the
11366     // appropriately-qualified base type.
11367     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11368                      VK_LValue, BasePath);
11369 
11370     // Dereference "this".
11371     DerefBuilder DerefThis(This);
11372     CastBuilder To(DerefThis,
11373                    Context.getCVRQualifiedType(
11374                        BaseType, CopyAssignOperator->getTypeQualifiers()),
11375                    VK_LValue, BasePath);
11376 
11377     // Build the copy.
11378     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11379                                             To, From,
11380                                             /*CopyingBaseSubobject=*/true,
11381                                             /*Copying=*/true);
11382     if (Copy.isInvalid()) {
11383       Diag(CurrentLocation, diag::note_member_synthesized_at)
11384         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11385       CopyAssignOperator->setInvalidDecl();
11386       return;
11387     }
11388 
11389     // Success! Record the copy.
11390     Statements.push_back(Copy.getAs<Expr>());
11391   }
11392 
11393   // Assign non-static members.
11394   for (auto *Field : ClassDecl->fields()) {
11395     // FIXME: We should form some kind of AST representation for the implied
11396     // memcpy in a union copy operation.
11397     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11398       continue;
11399 
11400     if (Field->isInvalidDecl()) {
11401       Invalid = true;
11402       continue;
11403     }
11404 
11405     // Check for members of reference type; we can't copy those.
11406     if (Field->getType()->isReferenceType()) {
11407       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11408         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11409       Diag(Field->getLocation(), diag::note_declared_at);
11410       Diag(CurrentLocation, diag::note_member_synthesized_at)
11411         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11412       Invalid = true;
11413       continue;
11414     }
11415 
11416     // Check for members of const-qualified, non-class type.
11417     QualType BaseType = Context.getBaseElementType(Field->getType());
11418     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11419       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11420         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11421       Diag(Field->getLocation(), diag::note_declared_at);
11422       Diag(CurrentLocation, diag::note_member_synthesized_at)
11423         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11424       Invalid = true;
11425       continue;
11426     }
11427 
11428     // Suppress assigning zero-width bitfields.
11429     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11430       continue;
11431 
11432     QualType FieldType = Field->getType().getNonReferenceType();
11433     if (FieldType->isIncompleteArrayType()) {
11434       assert(ClassDecl->hasFlexibleArrayMember() &&
11435              "Incomplete array type is not valid");
11436       continue;
11437     }
11438 
11439     // Build references to the field in the object we're copying from and to.
11440     CXXScopeSpec SS; // Intentionally empty
11441     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11442                               LookupMemberName);
11443     MemberLookup.addDecl(Field);
11444     MemberLookup.resolveKind();
11445 
11446     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11447 
11448     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11449 
11450     // Build the copy of this field.
11451     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11452                                             To, From,
11453                                             /*CopyingBaseSubobject=*/false,
11454                                             /*Copying=*/true);
11455     if (Copy.isInvalid()) {
11456       Diag(CurrentLocation, diag::note_member_synthesized_at)
11457         << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11458       CopyAssignOperator->setInvalidDecl();
11459       return;
11460     }
11461 
11462     // Success! Record the copy.
11463     Statements.push_back(Copy.getAs<Stmt>());
11464   }
11465 
11466   if (!Invalid) {
11467     // Add a "return *this;"
11468     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11469 
11470     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11471     if (Return.isInvalid())
11472       Invalid = true;
11473     else {
11474       Statements.push_back(Return.getAs<Stmt>());
11475 
11476       if (Trap.hasErrorOccurred()) {
11477         Diag(CurrentLocation, diag::note_member_synthesized_at)
11478           << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
11479         Invalid = true;
11480       }
11481     }
11482   }
11483 
11484   // The exception specification is needed because we are defining the
11485   // function.
11486   ResolveExceptionSpec(CurrentLocation,
11487                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11488 
11489   if (Invalid) {
11490     CopyAssignOperator->setInvalidDecl();
11491     return;
11492   }
11493 
11494   StmtResult Body;
11495   {
11496     CompoundScopeRAII CompoundScope(*this);
11497     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11498                              /*isStmtExpr=*/false);
11499     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11500   }
11501   CopyAssignOperator->setBody(Body.getAs<Stmt>());
11502 
11503   if (ASTMutationListener *L = getASTMutationListener()) {
11504     L->CompletedImplicitDefinition(CopyAssignOperator);
11505   }
11506 }
11507 
11508 Sema::ImplicitExceptionSpecification
11509 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
11510   CXXRecordDecl *ClassDecl = MD->getParent();
11511 
11512   ImplicitExceptionSpecification ExceptSpec(*this);
11513   if (ClassDecl->isInvalidDecl())
11514     return ExceptSpec;
11515 
11516   // C++0x [except.spec]p14:
11517   //   An implicitly declared special member function (Clause 12) shall have an
11518   //   exception-specification. [...]
11519 
11520   // It is unspecified whether or not an implicit move assignment operator
11521   // attempts to deduplicate calls to assignment operators of virtual bases are
11522   // made. As such, this exception specification is effectively unspecified.
11523   // Based on a similar decision made for constness in C++0x, we're erring on
11524   // the side of assuming such calls to be made regardless of whether they
11525   // actually happen.
11526   // Note that a move constructor is not implicitly declared when there are
11527   // virtual bases, but it can still be user-declared and explicitly defaulted.
11528   for (const auto &Base : ClassDecl->bases()) {
11529     if (Base.isVirtual())
11530       continue;
11531 
11532     CXXRecordDecl *BaseClassDecl
11533       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11534     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11535                                                            0, false, 0))
11536       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11537   }
11538 
11539   for (const auto &Base : ClassDecl->vbases()) {
11540     CXXRecordDecl *BaseClassDecl
11541       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11542     if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
11543                                                            0, false, 0))
11544       ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
11545   }
11546 
11547   for (const auto *Field : ClassDecl->fields()) {
11548     QualType FieldType = Context.getBaseElementType(Field->getType());
11549     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11550       if (CXXMethodDecl *MoveAssign =
11551               LookupMovingAssignment(FieldClassDecl,
11552                                      FieldType.getCVRQualifiers(),
11553                                      false, 0))
11554         ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
11555     }
11556   }
11557 
11558   return ExceptSpec;
11559 }
11560 
11561 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11562   assert(ClassDecl->needsImplicitMoveAssignment());
11563 
11564   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11565   if (DSM.isAlreadyBeingDeclared())
11566     return nullptr;
11567 
11568   // Note: The following rules are largely analoguous to the move
11569   // constructor rules.
11570 
11571   QualType ArgType = Context.getTypeDeclType(ClassDecl);
11572   QualType RetType = Context.getLValueReferenceType(ArgType);
11573   ArgType = Context.getRValueReferenceType(ArgType);
11574 
11575   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11576                                                      CXXMoveAssignment,
11577                                                      false);
11578 
11579   //   An implicitly-declared move assignment operator is an inline public
11580   //   member of its class.
11581   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11582   SourceLocation ClassLoc = ClassDecl->getLocation();
11583   DeclarationNameInfo NameInfo(Name, ClassLoc);
11584   CXXMethodDecl *MoveAssignment =
11585       CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11586                             /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11587                             /*isInline=*/true, Constexpr, SourceLocation());
11588   MoveAssignment->setAccess(AS_public);
11589   MoveAssignment->setDefaulted();
11590   MoveAssignment->setImplicit();
11591 
11592   if (getLangOpts().CUDA) {
11593     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11594                                             MoveAssignment,
11595                                             /* ConstRHS */ false,
11596                                             /* Diagnose */ false);
11597   }
11598 
11599   // Build an exception specification pointing back at this member.
11600   FunctionProtoType::ExtProtoInfo EPI =
11601       getImplicitMethodEPI(*this, MoveAssignment);
11602   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11603 
11604   // Add the parameter to the operator.
11605   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11606                                                ClassLoc, ClassLoc,
11607                                                /*Id=*/nullptr, ArgType,
11608                                                /*TInfo=*/nullptr, SC_None,
11609                                                nullptr);
11610   MoveAssignment->setParams(FromParam);
11611 
11612   MoveAssignment->setTrivial(
11613     ClassDecl->needsOverloadResolutionForMoveAssignment()
11614       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11615       : ClassDecl->hasTrivialMoveAssignment());
11616 
11617   // Note that we have added this copy-assignment operator.
11618   ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11619 
11620   Scope *S = getScopeForContext(ClassDecl);
11621   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11622 
11623   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11624     ClassDecl->setImplicitMoveAssignmentIsDeleted();
11625     SetDeclDeleted(MoveAssignment, ClassLoc);
11626   }
11627 
11628   if (S)
11629     PushOnScopeChains(MoveAssignment, S, false);
11630   ClassDecl->addDecl(MoveAssignment);
11631 
11632   return MoveAssignment;
11633 }
11634 
11635 /// Check if we're implicitly defining a move assignment operator for a class
11636 /// with virtual bases. Such a move assignment might move-assign the virtual
11637 /// base multiple times.
11638 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11639                                                SourceLocation CurrentLocation) {
11640   assert(!Class->isDependentContext() && "should not define dependent move");
11641 
11642   // Only a virtual base could get implicitly move-assigned multiple times.
11643   // Only a non-trivial move assignment can observe this. We only want to
11644   // diagnose if we implicitly define an assignment operator that assigns
11645   // two base classes, both of which move-assign the same virtual base.
11646   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11647       Class->getNumBases() < 2)
11648     return;
11649 
11650   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11651   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11652   VBaseMap VBases;
11653 
11654   for (auto &BI : Class->bases()) {
11655     Worklist.push_back(&BI);
11656     while (!Worklist.empty()) {
11657       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11658       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11659 
11660       // If the base has no non-trivial move assignment operators,
11661       // we don't care about moves from it.
11662       if (!Base->hasNonTrivialMoveAssignment())
11663         continue;
11664 
11665       // If there's nothing virtual here, skip it.
11666       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11667         continue;
11668 
11669       // If we're not actually going to call a move assignment for this base,
11670       // or the selected move assignment is trivial, skip it.
11671       Sema::SpecialMemberOverloadResult *SMOR =
11672         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11673                               /*ConstArg*/false, /*VolatileArg*/false,
11674                               /*RValueThis*/true, /*ConstThis*/false,
11675                               /*VolatileThis*/false);
11676       if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
11677           !SMOR->getMethod()->isMoveAssignmentOperator())
11678         continue;
11679 
11680       if (BaseSpec->isVirtual()) {
11681         // We're going to move-assign this virtual base, and its move
11682         // assignment operator is not trivial. If this can happen for
11683         // multiple distinct direct bases of Class, diagnose it. (If it
11684         // only happens in one base, we'll diagnose it when synthesizing
11685         // that base class's move assignment operator.)
11686         CXXBaseSpecifier *&Existing =
11687             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11688                 .first->second;
11689         if (Existing && Existing != &BI) {
11690           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11691             << Class << Base;
11692           S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11693             << (Base->getCanonicalDecl() ==
11694                 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11695             << Base << Existing->getType() << Existing->getSourceRange();
11696           S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11697             << (Base->getCanonicalDecl() ==
11698                 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11699             << Base << BI.getType() << BaseSpec->getSourceRange();
11700 
11701           // Only diagnose each vbase once.
11702           Existing = nullptr;
11703         }
11704       } else {
11705         // Only walk over bases that have defaulted move assignment operators.
11706         // We assume that any user-provided move assignment operator handles
11707         // the multiple-moves-of-vbase case itself somehow.
11708         if (!SMOR->getMethod()->isDefaulted())
11709           continue;
11710 
11711         // We're going to move the base classes of Base. Add them to the list.
11712         for (auto &BI : Base->bases())
11713           Worklist.push_back(&BI);
11714       }
11715     }
11716   }
11717 }
11718 
11719 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11720                                         CXXMethodDecl *MoveAssignOperator) {
11721   assert((MoveAssignOperator->isDefaulted() &&
11722           MoveAssignOperator->isOverloadedOperator() &&
11723           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11724           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11725           !MoveAssignOperator->isDeleted()) &&
11726          "DefineImplicitMoveAssignment called for wrong function");
11727 
11728   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11729 
11730   if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
11731     MoveAssignOperator->setInvalidDecl();
11732     return;
11733   }
11734 
11735   MoveAssignOperator->markUsed(Context);
11736 
11737   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11738   DiagnosticErrorTrap Trap(Diags);
11739 
11740   // C++0x [class.copy]p28:
11741   //   The implicitly-defined or move assignment operator for a non-union class
11742   //   X performs memberwise move assignment of its subobjects. The direct base
11743   //   classes of X are assigned first, in the order of their declaration in the
11744   //   base-specifier-list, and then the immediate non-static data members of X
11745   //   are assigned, in the order in which they were declared in the class
11746   //   definition.
11747 
11748   // Issue a warning if our implicit move assignment operator will move
11749   // from a virtual base more than once.
11750   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11751 
11752   // The statements that form the synthesized function body.
11753   SmallVector<Stmt*, 8> Statements;
11754 
11755   // The parameter for the "other" object, which we are move from.
11756   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11757   QualType OtherRefType = Other->getType()->
11758       getAs<RValueReferenceType>()->getPointeeType();
11759   assert(!OtherRefType.getQualifiers() &&
11760          "Bad argument type of defaulted move assignment");
11761 
11762   // Our location for everything implicitly-generated.
11763   SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11764                            ? MoveAssignOperator->getLocEnd()
11765                            : MoveAssignOperator->getLocation();
11766 
11767   // Builds a reference to the "other" object.
11768   RefBuilder OtherRef(Other, OtherRefType);
11769   // Cast to rvalue.
11770   MoveCastBuilder MoveOther(OtherRef);
11771 
11772   // Builds the "this" pointer.
11773   ThisBuilder This;
11774 
11775   // Assign base classes.
11776   bool Invalid = false;
11777   for (auto &Base : ClassDecl->bases()) {
11778     // C++11 [class.copy]p28:
11779     //   It is unspecified whether subobjects representing virtual base classes
11780     //   are assigned more than once by the implicitly-defined copy assignment
11781     //   operator.
11782     // FIXME: Do not assign to a vbase that will be assigned by some other base
11783     // class. For a move-assignment, this can result in the vbase being moved
11784     // multiple times.
11785 
11786     // Form the assignment:
11787     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11788     QualType BaseType = Base.getType().getUnqualifiedType();
11789     if (!BaseType->isRecordType()) {
11790       Invalid = true;
11791       continue;
11792     }
11793 
11794     CXXCastPath BasePath;
11795     BasePath.push_back(&Base);
11796 
11797     // Construct the "from" expression, which is an implicit cast to the
11798     // appropriately-qualified base type.
11799     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11800 
11801     // Dereference "this".
11802     DerefBuilder DerefThis(This);
11803 
11804     // Implicitly cast "this" to the appropriately-qualified base type.
11805     CastBuilder To(DerefThis,
11806                    Context.getCVRQualifiedType(
11807                        BaseType, MoveAssignOperator->getTypeQualifiers()),
11808                    VK_LValue, BasePath);
11809 
11810     // Build the move.
11811     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11812                                             To, From,
11813                                             /*CopyingBaseSubobject=*/true,
11814                                             /*Copying=*/false);
11815     if (Move.isInvalid()) {
11816       Diag(CurrentLocation, diag::note_member_synthesized_at)
11817         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11818       MoveAssignOperator->setInvalidDecl();
11819       return;
11820     }
11821 
11822     // Success! Record the move.
11823     Statements.push_back(Move.getAs<Expr>());
11824   }
11825 
11826   // Assign non-static members.
11827   for (auto *Field : ClassDecl->fields()) {
11828     // FIXME: We should form some kind of AST representation for the implied
11829     // memcpy in a union copy operation.
11830     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11831       continue;
11832 
11833     if (Field->isInvalidDecl()) {
11834       Invalid = true;
11835       continue;
11836     }
11837 
11838     // Check for members of reference type; we can't move those.
11839     if (Field->getType()->isReferenceType()) {
11840       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11841         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11842       Diag(Field->getLocation(), diag::note_declared_at);
11843       Diag(CurrentLocation, diag::note_member_synthesized_at)
11844         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11845       Invalid = true;
11846       continue;
11847     }
11848 
11849     // Check for members of const-qualified, non-class type.
11850     QualType BaseType = Context.getBaseElementType(Field->getType());
11851     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11852       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11853         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11854       Diag(Field->getLocation(), diag::note_declared_at);
11855       Diag(CurrentLocation, diag::note_member_synthesized_at)
11856         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11857       Invalid = true;
11858       continue;
11859     }
11860 
11861     // Suppress assigning zero-width bitfields.
11862     if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11863       continue;
11864 
11865     QualType FieldType = Field->getType().getNonReferenceType();
11866     if (FieldType->isIncompleteArrayType()) {
11867       assert(ClassDecl->hasFlexibleArrayMember() &&
11868              "Incomplete array type is not valid");
11869       continue;
11870     }
11871 
11872     // Build references to the field in the object we're copying from and to.
11873     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11874                               LookupMemberName);
11875     MemberLookup.addDecl(Field);
11876     MemberLookup.resolveKind();
11877     MemberBuilder From(MoveOther, OtherRefType,
11878                        /*IsArrow=*/false, MemberLookup);
11879     MemberBuilder To(This, getCurrentThisType(),
11880                      /*IsArrow=*/true, MemberLookup);
11881 
11882     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11883         "Member reference with rvalue base must be rvalue except for reference "
11884         "members, which aren't allowed for move assignment.");
11885 
11886     // Build the move of this field.
11887     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11888                                             To, From,
11889                                             /*CopyingBaseSubobject=*/false,
11890                                             /*Copying=*/false);
11891     if (Move.isInvalid()) {
11892       Diag(CurrentLocation, diag::note_member_synthesized_at)
11893         << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11894       MoveAssignOperator->setInvalidDecl();
11895       return;
11896     }
11897 
11898     // Success! Record the copy.
11899     Statements.push_back(Move.getAs<Stmt>());
11900   }
11901 
11902   if (!Invalid) {
11903     // Add a "return *this;"
11904     ExprResult ThisObj =
11905         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11906 
11907     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11908     if (Return.isInvalid())
11909       Invalid = true;
11910     else {
11911       Statements.push_back(Return.getAs<Stmt>());
11912 
11913       if (Trap.hasErrorOccurred()) {
11914         Diag(CurrentLocation, diag::note_member_synthesized_at)
11915           << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
11916         Invalid = true;
11917       }
11918     }
11919   }
11920 
11921   // The exception specification is needed because we are defining the
11922   // function.
11923   ResolveExceptionSpec(CurrentLocation,
11924                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11925 
11926   if (Invalid) {
11927     MoveAssignOperator->setInvalidDecl();
11928     return;
11929   }
11930 
11931   StmtResult Body;
11932   {
11933     CompoundScopeRAII CompoundScope(*this);
11934     Body = ActOnCompoundStmt(Loc, Loc, Statements,
11935                              /*isStmtExpr=*/false);
11936     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11937   }
11938   MoveAssignOperator->setBody(Body.getAs<Stmt>());
11939 
11940   if (ASTMutationListener *L = getASTMutationListener()) {
11941     L->CompletedImplicitDefinition(MoveAssignOperator);
11942   }
11943 }
11944 
11945 Sema::ImplicitExceptionSpecification
11946 Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
11947   CXXRecordDecl *ClassDecl = MD->getParent();
11948 
11949   ImplicitExceptionSpecification ExceptSpec(*this);
11950   if (ClassDecl->isInvalidDecl())
11951     return ExceptSpec;
11952 
11953   const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
11954   assert(T->getNumParams() >= 1 && "not a copy ctor");
11955   unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
11956 
11957   // C++ [except.spec]p14:
11958   //   An implicitly declared special member function (Clause 12) shall have an
11959   //   exception-specification. [...]
11960   for (const auto &Base : ClassDecl->bases()) {
11961     // Virtual bases are handled below.
11962     if (Base.isVirtual())
11963       continue;
11964 
11965     CXXRecordDecl *BaseClassDecl
11966       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11967     if (CXXConstructorDecl *CopyConstructor =
11968           LookupCopyingConstructor(BaseClassDecl, Quals))
11969       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11970   }
11971   for (const auto &Base : ClassDecl->vbases()) {
11972     CXXRecordDecl *BaseClassDecl
11973       = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
11974     if (CXXConstructorDecl *CopyConstructor =
11975           LookupCopyingConstructor(BaseClassDecl, Quals))
11976       ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
11977   }
11978   for (const auto *Field : ClassDecl->fields()) {
11979     QualType FieldType = Context.getBaseElementType(Field->getType());
11980     if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
11981       if (CXXConstructorDecl *CopyConstructor =
11982               LookupCopyingConstructor(FieldClassDecl,
11983                                        Quals | FieldType.getCVRQualifiers()))
11984       ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
11985     }
11986   }
11987 
11988   return ExceptSpec;
11989 }
11990 
11991 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11992                                                     CXXRecordDecl *ClassDecl) {
11993   // C++ [class.copy]p4:
11994   //   If the class definition does not explicitly declare a copy
11995   //   constructor, one is declared implicitly.
11996   assert(ClassDecl->needsImplicitCopyConstructor());
11997 
11998   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11999   if (DSM.isAlreadyBeingDeclared())
12000     return nullptr;
12001 
12002   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12003   QualType ArgType = ClassType;
12004   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12005   if (Const)
12006     ArgType = ArgType.withConst();
12007   ArgType = Context.getLValueReferenceType(ArgType);
12008 
12009   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12010                                                      CXXCopyConstructor,
12011                                                      Const);
12012 
12013   DeclarationName Name
12014     = Context.DeclarationNames.getCXXConstructorName(
12015                                            Context.getCanonicalType(ClassType));
12016   SourceLocation ClassLoc = ClassDecl->getLocation();
12017   DeclarationNameInfo NameInfo(Name, ClassLoc);
12018 
12019   //   An implicitly-declared copy constructor is an inline public
12020   //   member of its class.
12021   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12022       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12023       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12024       Constexpr);
12025   CopyConstructor->setAccess(AS_public);
12026   CopyConstructor->setDefaulted();
12027 
12028   if (getLangOpts().CUDA) {
12029     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12030                                             CopyConstructor,
12031                                             /* ConstRHS */ Const,
12032                                             /* Diagnose */ false);
12033   }
12034 
12035   // Build an exception specification pointing back at this member.
12036   FunctionProtoType::ExtProtoInfo EPI =
12037       getImplicitMethodEPI(*this, CopyConstructor);
12038   CopyConstructor->setType(
12039       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12040 
12041   // Add the parameter to the constructor.
12042   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12043                                                ClassLoc, ClassLoc,
12044                                                /*IdentifierInfo=*/nullptr,
12045                                                ArgType, /*TInfo=*/nullptr,
12046                                                SC_None, nullptr);
12047   CopyConstructor->setParams(FromParam);
12048 
12049   CopyConstructor->setTrivial(
12050     ClassDecl->needsOverloadResolutionForCopyConstructor()
12051       ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12052       : ClassDecl->hasTrivialCopyConstructor());
12053 
12054   // Note that we have declared this constructor.
12055   ++ASTContext::NumImplicitCopyConstructorsDeclared;
12056 
12057   Scope *S = getScopeForContext(ClassDecl);
12058   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12059 
12060   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
12061     SetDeclDeleted(CopyConstructor, ClassLoc);
12062 
12063   if (S)
12064     PushOnScopeChains(CopyConstructor, S, false);
12065   ClassDecl->addDecl(CopyConstructor);
12066 
12067   return CopyConstructor;
12068 }
12069 
12070 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12071                                    CXXConstructorDecl *CopyConstructor) {
12072   assert((CopyConstructor->isDefaulted() &&
12073           CopyConstructor->isCopyConstructor() &&
12074           !CopyConstructor->doesThisDeclarationHaveABody() &&
12075           !CopyConstructor->isDeleted()) &&
12076          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12077 
12078   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12079   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12080 
12081   // C++11 [class.copy]p7:
12082   //   The [definition of an implicitly declared copy constructor] is
12083   //   deprecated if the class has a user-declared copy assignment operator
12084   //   or a user-declared destructor.
12085   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12086     diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
12087 
12088   SynthesizedFunctionScope Scope(*this, CopyConstructor);
12089   DiagnosticErrorTrap Trap(Diags);
12090 
12091   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
12092       Trap.hasErrorOccurred()) {
12093     Diag(CurrentLocation, diag::note_member_synthesized_at)
12094       << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
12095     CopyConstructor->setInvalidDecl();
12096   }  else {
12097     SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12098                              ? CopyConstructor->getLocEnd()
12099                              : CopyConstructor->getLocation();
12100     Sema::CompoundScopeRAII CompoundScope(*this);
12101     CopyConstructor->setBody(
12102         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12103   }
12104 
12105   // The exception specification is needed because we are defining the
12106   // function.
12107   ResolveExceptionSpec(CurrentLocation,
12108                        CopyConstructor->getType()->castAs<FunctionProtoType>());
12109 
12110   CopyConstructor->markUsed(Context);
12111   MarkVTableUsed(CurrentLocation, ClassDecl);
12112 
12113   if (ASTMutationListener *L = getASTMutationListener()) {
12114     L->CompletedImplicitDefinition(CopyConstructor);
12115   }
12116 }
12117 
12118 Sema::ImplicitExceptionSpecification
12119 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
12120   CXXRecordDecl *ClassDecl = MD->getParent();
12121 
12122   // C++ [except.spec]p14:
12123   //   An implicitly declared special member function (Clause 12) shall have an
12124   //   exception-specification. [...]
12125   ImplicitExceptionSpecification ExceptSpec(*this);
12126   if (ClassDecl->isInvalidDecl())
12127     return ExceptSpec;
12128 
12129   // Direct base-class constructors.
12130   for (const auto &B : ClassDecl->bases()) {
12131     if (B.isVirtual()) // Handled below.
12132       continue;
12133 
12134     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
12135       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
12136       CXXConstructorDecl *Constructor =
12137           LookupMovingConstructor(BaseClassDecl, 0);
12138       // If this is a deleted function, add it anyway. This might be conformant
12139       // with the standard. This might not. I'm not sure. It might not matter.
12140       if (Constructor)
12141         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
12142     }
12143   }
12144 
12145   // Virtual base-class constructors.
12146   for (const auto &B : ClassDecl->vbases()) {
12147     if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
12148       CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
12149       CXXConstructorDecl *Constructor =
12150           LookupMovingConstructor(BaseClassDecl, 0);
12151       // If this is a deleted function, add it anyway. This might be conformant
12152       // with the standard. This might not. I'm not sure. It might not matter.
12153       if (Constructor)
12154         ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
12155     }
12156   }
12157 
12158   // Field constructors.
12159   for (const auto *F : ClassDecl->fields()) {
12160     QualType FieldType = Context.getBaseElementType(F->getType());
12161     if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
12162       CXXConstructorDecl *Constructor =
12163           LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
12164       // If this is a deleted function, add it anyway. This might be conformant
12165       // with the standard. This might not. I'm not sure. It might not matter.
12166       // In particular, the problem is that this function never gets called. It
12167       // might just be ill-formed because this function attempts to refer to
12168       // a deleted function here.
12169       if (Constructor)
12170         ExceptSpec.CalledDecl(F->getLocation(), Constructor);
12171     }
12172   }
12173 
12174   return ExceptSpec;
12175 }
12176 
12177 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12178                                                     CXXRecordDecl *ClassDecl) {
12179   assert(ClassDecl->needsImplicitMoveConstructor());
12180 
12181   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12182   if (DSM.isAlreadyBeingDeclared())
12183     return nullptr;
12184 
12185   QualType ClassType = Context.getTypeDeclType(ClassDecl);
12186   QualType ArgType = Context.getRValueReferenceType(ClassType);
12187 
12188   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12189                                                      CXXMoveConstructor,
12190                                                      false);
12191 
12192   DeclarationName Name
12193     = Context.DeclarationNames.getCXXConstructorName(
12194                                            Context.getCanonicalType(ClassType));
12195   SourceLocation ClassLoc = ClassDecl->getLocation();
12196   DeclarationNameInfo NameInfo(Name, ClassLoc);
12197 
12198   // C++11 [class.copy]p11:
12199   //   An implicitly-declared copy/move constructor is an inline public
12200   //   member of its class.
12201   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12202       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12203       /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12204       Constexpr);
12205   MoveConstructor->setAccess(AS_public);
12206   MoveConstructor->setDefaulted();
12207 
12208   if (getLangOpts().CUDA) {
12209     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12210                                             MoveConstructor,
12211                                             /* ConstRHS */ false,
12212                                             /* Diagnose */ false);
12213   }
12214 
12215   // Build an exception specification pointing back at this member.
12216   FunctionProtoType::ExtProtoInfo EPI =
12217       getImplicitMethodEPI(*this, MoveConstructor);
12218   MoveConstructor->setType(
12219       Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12220 
12221   // Add the parameter to the constructor.
12222   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12223                                                ClassLoc, ClassLoc,
12224                                                /*IdentifierInfo=*/nullptr,
12225                                                ArgType, /*TInfo=*/nullptr,
12226                                                SC_None, nullptr);
12227   MoveConstructor->setParams(FromParam);
12228 
12229   MoveConstructor->setTrivial(
12230     ClassDecl->needsOverloadResolutionForMoveConstructor()
12231       ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12232       : ClassDecl->hasTrivialMoveConstructor());
12233 
12234   // Note that we have declared this constructor.
12235   ++ASTContext::NumImplicitMoveConstructorsDeclared;
12236 
12237   Scope *S = getScopeForContext(ClassDecl);
12238   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12239 
12240   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12241     ClassDecl->setImplicitMoveConstructorIsDeleted();
12242     SetDeclDeleted(MoveConstructor, ClassLoc);
12243   }
12244 
12245   if (S)
12246     PushOnScopeChains(MoveConstructor, S, false);
12247   ClassDecl->addDecl(MoveConstructor);
12248 
12249   return MoveConstructor;
12250 }
12251 
12252 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12253                                    CXXConstructorDecl *MoveConstructor) {
12254   assert((MoveConstructor->isDefaulted() &&
12255           MoveConstructor->isMoveConstructor() &&
12256           !MoveConstructor->doesThisDeclarationHaveABody() &&
12257           !MoveConstructor->isDeleted()) &&
12258          "DefineImplicitMoveConstructor - call it for implicit move ctor");
12259 
12260   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12261   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12262 
12263   SynthesizedFunctionScope Scope(*this, MoveConstructor);
12264   DiagnosticErrorTrap Trap(Diags);
12265 
12266   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
12267       Trap.hasErrorOccurred()) {
12268     Diag(CurrentLocation, diag::note_member_synthesized_at)
12269       << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
12270     MoveConstructor->setInvalidDecl();
12271   }  else {
12272     SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12273                              ? MoveConstructor->getLocEnd()
12274                              : MoveConstructor->getLocation();
12275     Sema::CompoundScopeRAII CompoundScope(*this);
12276     MoveConstructor->setBody(ActOnCompoundStmt(
12277         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12278   }
12279 
12280   // The exception specification is needed because we are defining the
12281   // function.
12282   ResolveExceptionSpec(CurrentLocation,
12283                        MoveConstructor->getType()->castAs<FunctionProtoType>());
12284 
12285   MoveConstructor->markUsed(Context);
12286   MarkVTableUsed(CurrentLocation, ClassDecl);
12287 
12288   if (ASTMutationListener *L = getASTMutationListener()) {
12289     L->CompletedImplicitDefinition(MoveConstructor);
12290   }
12291 }
12292 
12293 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12294   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12295 }
12296 
12297 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12298                             SourceLocation CurrentLocation,
12299                             CXXConversionDecl *Conv) {
12300   CXXRecordDecl *Lambda = Conv->getParent();
12301   CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12302   // If we are defining a specialization of a conversion to function-ptr
12303   // cache the deduced template arguments for this specialization
12304   // so that we can use them to retrieve the corresponding call-operator
12305   // and static-invoker.
12306   const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12307 
12308   // Retrieve the corresponding call-operator specialization.
12309   if (Lambda->isGenericLambda()) {
12310     assert(Conv->isFunctionTemplateSpecialization());
12311     FunctionTemplateDecl *CallOpTemplate =
12312         CallOp->getDescribedFunctionTemplate();
12313     DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12314     void *InsertPos = nullptr;
12315     FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12316                                                 DeducedTemplateArgs->asArray(),
12317                                                 InsertPos);
12318     assert(CallOpSpec &&
12319           "Conversion operator must have a corresponding call operator");
12320     CallOp = cast<CXXMethodDecl>(CallOpSpec);
12321   }
12322   // Mark the call operator referenced (and add to pending instantiations
12323   // if necessary).
12324   // For both the conversion and static-invoker template specializations
12325   // we construct their body's in this function, so no need to add them
12326   // to the PendingInstantiations.
12327   MarkFunctionReferenced(CurrentLocation, CallOp);
12328 
12329   SynthesizedFunctionScope Scope(*this, Conv);
12330   DiagnosticErrorTrap Trap(Diags);
12331 
12332   // Retrieve the static invoker...
12333   CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12334   // ... and get the corresponding specialization for a generic lambda.
12335   if (Lambda->isGenericLambda()) {
12336     assert(DeducedTemplateArgs &&
12337       "Must have deduced template arguments from Conversion Operator");
12338     FunctionTemplateDecl *InvokeTemplate =
12339                           Invoker->getDescribedFunctionTemplate();
12340     void *InsertPos = nullptr;
12341     FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12342                                                 DeducedTemplateArgs->asArray(),
12343                                                 InsertPos);
12344     assert(InvokeSpec &&
12345       "Must have a corresponding static invoker specialization");
12346     Invoker = cast<CXXMethodDecl>(InvokeSpec);
12347   }
12348   // Construct the body of the conversion function { return __invoke; }.
12349   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12350                                         VK_LValue, Conv->getLocation()).get();
12351    assert(FunctionRef && "Can't refer to __invoke function?");
12352    Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12353    Conv->setBody(new (Context) CompoundStmt(Context, Return,
12354                                             Conv->getLocation(),
12355                                             Conv->getLocation()));
12356 
12357   Conv->markUsed(Context);
12358   Conv->setReferenced();
12359 
12360   // Fill in the __invoke function with a dummy implementation. IR generation
12361   // will fill in the actual details.
12362   Invoker->markUsed(Context);
12363   Invoker->setReferenced();
12364   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12365 
12366   if (ASTMutationListener *L = getASTMutationListener()) {
12367     L->CompletedImplicitDefinition(Conv);
12368     L->CompletedImplicitDefinition(Invoker);
12369    }
12370 }
12371 
12372 
12373 
12374 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12375        SourceLocation CurrentLocation,
12376        CXXConversionDecl *Conv)
12377 {
12378   assert(!Conv->getParent()->isGenericLambda());
12379 
12380   Conv->markUsed(Context);
12381 
12382   SynthesizedFunctionScope Scope(*this, Conv);
12383   DiagnosticErrorTrap Trap(Diags);
12384 
12385   // Copy-initialize the lambda object as needed to capture it.
12386   Expr *This = ActOnCXXThis(CurrentLocation).get();
12387   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12388 
12389   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12390                                                         Conv->getLocation(),
12391                                                         Conv, DerefThis);
12392 
12393   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12394   // behavior.  Note that only the general conversion function does this
12395   // (since it's unusable otherwise); in the case where we inline the
12396   // block literal, it has block literal lifetime semantics.
12397   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12398     BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12399                                           CK_CopyAndAutoreleaseBlockObject,
12400                                           BuildBlock.get(), nullptr, VK_RValue);
12401 
12402   if (BuildBlock.isInvalid()) {
12403     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12404     Conv->setInvalidDecl();
12405     return;
12406   }
12407 
12408   // Create the return statement that returns the block from the conversion
12409   // function.
12410   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12411   if (Return.isInvalid()) {
12412     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12413     Conv->setInvalidDecl();
12414     return;
12415   }
12416 
12417   // Set the body of the conversion function.
12418   Stmt *ReturnS = Return.get();
12419   Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12420                                            Conv->getLocation(),
12421                                            Conv->getLocation()));
12422 
12423   // We're done; notify the mutation listener, if any.
12424   if (ASTMutationListener *L = getASTMutationListener()) {
12425     L->CompletedImplicitDefinition(Conv);
12426   }
12427 }
12428 
12429 /// \brief Determine whether the given list arguments contains exactly one
12430 /// "real" (non-default) argument.
12431 static bool hasOneRealArgument(MultiExprArg Args) {
12432   switch (Args.size()) {
12433   case 0:
12434     return false;
12435 
12436   default:
12437     if (!Args[1]->isDefaultArgument())
12438       return false;
12439 
12440     // fall through
12441   case 1:
12442     return !Args[0]->isDefaultArgument();
12443   }
12444 
12445   return false;
12446 }
12447 
12448 ExprResult
12449 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12450                             NamedDecl *FoundDecl,
12451                             CXXConstructorDecl *Constructor,
12452                             MultiExprArg ExprArgs,
12453                             bool HadMultipleCandidates,
12454                             bool IsListInitialization,
12455                             bool IsStdInitListInitialization,
12456                             bool RequiresZeroInit,
12457                             unsigned ConstructKind,
12458                             SourceRange ParenRange) {
12459   bool Elidable = false;
12460 
12461   // C++0x [class.copy]p34:
12462   //   When certain criteria are met, an implementation is allowed to
12463   //   omit the copy/move construction of a class object, even if the
12464   //   copy/move constructor and/or destructor for the object have
12465   //   side effects. [...]
12466   //     - when a temporary class object that has not been bound to a
12467   //       reference (12.2) would be copied/moved to a class object
12468   //       with the same cv-unqualified type, the copy/move operation
12469   //       can be omitted by constructing the temporary object
12470   //       directly into the target of the omitted copy/move
12471   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12472       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12473     Expr *SubExpr = ExprArgs[0];
12474     Elidable = SubExpr->isTemporaryObject(
12475         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12476   }
12477 
12478   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12479                                FoundDecl, Constructor,
12480                                Elidable, ExprArgs, HadMultipleCandidates,
12481                                IsListInitialization,
12482                                IsStdInitListInitialization, RequiresZeroInit,
12483                                ConstructKind, ParenRange);
12484 }
12485 
12486 ExprResult
12487 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12488                             NamedDecl *FoundDecl,
12489                             CXXConstructorDecl *Constructor,
12490                             bool Elidable,
12491                             MultiExprArg ExprArgs,
12492                             bool HadMultipleCandidates,
12493                             bool IsListInitialization,
12494                             bool IsStdInitListInitialization,
12495                             bool RequiresZeroInit,
12496                             unsigned ConstructKind,
12497                             SourceRange ParenRange) {
12498   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12499     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12500     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12501       return ExprError();
12502   }
12503 
12504   return BuildCXXConstructExpr(
12505       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12506       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12507       RequiresZeroInit, ConstructKind, ParenRange);
12508 }
12509 
12510 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12511 /// including handling of its default argument expressions.
12512 ExprResult
12513 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12514                             CXXConstructorDecl *Constructor,
12515                             bool Elidable,
12516                             MultiExprArg ExprArgs,
12517                             bool HadMultipleCandidates,
12518                             bool IsListInitialization,
12519                             bool IsStdInitListInitialization,
12520                             bool RequiresZeroInit,
12521                             unsigned ConstructKind,
12522                             SourceRange ParenRange) {
12523   assert(declaresSameEntity(
12524              Constructor->getParent(),
12525              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12526          "given constructor for wrong type");
12527   MarkFunctionReferenced(ConstructLoc, Constructor);
12528   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12529     return ExprError();
12530 
12531   return CXXConstructExpr::Create(
12532       Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12533       ExprArgs, HadMultipleCandidates, IsListInitialization,
12534       IsStdInitListInitialization, RequiresZeroInit,
12535       static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12536       ParenRange);
12537 }
12538 
12539 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12540   assert(Field->hasInClassInitializer());
12541 
12542   // If we already have the in-class initializer nothing needs to be done.
12543   if (Field->getInClassInitializer())
12544     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12545 
12546   // If we might have already tried and failed to instantiate, don't try again.
12547   if (Field->isInvalidDecl())
12548     return ExprError();
12549 
12550   // Maybe we haven't instantiated the in-class initializer. Go check the
12551   // pattern FieldDecl to see if it has one.
12552   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12553 
12554   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12555     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12556     DeclContext::lookup_result Lookup =
12557         ClassPattern->lookup(Field->getDeclName());
12558 
12559     // Lookup can return at most two results: the pattern for the field, or the
12560     // injected class name of the parent record. No other member can have the
12561     // same name as the field.
12562     // In modules mode, lookup can return multiple results (coming from
12563     // different modules).
12564     assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12565            "more than two lookup results for field name");
12566     FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12567     if (!Pattern) {
12568       assert(isa<CXXRecordDecl>(Lookup[0]) &&
12569              "cannot have other non-field member with same name");
12570       for (auto L : Lookup)
12571         if (isa<FieldDecl>(L)) {
12572           Pattern = cast<FieldDecl>(L);
12573           break;
12574         }
12575       assert(Pattern && "We must have set the Pattern!");
12576     }
12577 
12578     if (InstantiateInClassInitializer(Loc, Field, Pattern,
12579                                       getTemplateInstantiationArgs(Field))) {
12580       // Don't diagnose this again.
12581       Field->setInvalidDecl();
12582       return ExprError();
12583     }
12584     return CXXDefaultInitExpr::Create(Context, Loc, Field);
12585   }
12586 
12587   // DR1351:
12588   //   If the brace-or-equal-initializer of a non-static data member
12589   //   invokes a defaulted default constructor of its class or of an
12590   //   enclosing class in a potentially evaluated subexpression, the
12591   //   program is ill-formed.
12592   //
12593   // This resolution is unworkable: the exception specification of the
12594   // default constructor can be needed in an unevaluated context, in
12595   // particular, in the operand of a noexcept-expression, and we can be
12596   // unable to compute an exception specification for an enclosed class.
12597   //
12598   // Any attempt to resolve the exception specification of a defaulted default
12599   // constructor before the initializer is lexically complete will ultimately
12600   // come here at which point we can diagnose it.
12601   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12602   Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12603       << OutermostClass << Field;
12604   Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12605   // Recover by marking the field invalid, unless we're in a SFINAE context.
12606   if (!isSFINAEContext())
12607     Field->setInvalidDecl();
12608   return ExprError();
12609 }
12610 
12611 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12612   if (VD->isInvalidDecl()) return;
12613 
12614   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12615   if (ClassDecl->isInvalidDecl()) return;
12616   if (ClassDecl->hasIrrelevantDestructor()) return;
12617   if (ClassDecl->isDependentContext()) return;
12618 
12619   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12620   MarkFunctionReferenced(VD->getLocation(), Destructor);
12621   CheckDestructorAccess(VD->getLocation(), Destructor,
12622                         PDiag(diag::err_access_dtor_var)
12623                         << VD->getDeclName()
12624                         << VD->getType());
12625   DiagnoseUseOfDecl(Destructor, VD->getLocation());
12626 
12627   if (Destructor->isTrivial()) return;
12628   if (!VD->hasGlobalStorage()) return;
12629 
12630   // Emit warning for non-trivial dtor in global scope (a real global,
12631   // class-static, function-static).
12632   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12633 
12634   // TODO: this should be re-enabled for static locals by !CXAAtExit
12635   if (!VD->isStaticLocal())
12636     Diag(VD->getLocation(), diag::warn_global_destructor);
12637 }
12638 
12639 /// \brief Given a constructor and the set of arguments provided for the
12640 /// constructor, convert the arguments and add any required default arguments
12641 /// to form a proper call to this constructor.
12642 ///
12643 /// \returns true if an error occurred, false otherwise.
12644 bool
12645 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12646                               MultiExprArg ArgsPtr,
12647                               SourceLocation Loc,
12648                               SmallVectorImpl<Expr*> &ConvertedArgs,
12649                               bool AllowExplicit,
12650                               bool IsListInitialization) {
12651   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12652   unsigned NumArgs = ArgsPtr.size();
12653   Expr **Args = ArgsPtr.data();
12654 
12655   const FunctionProtoType *Proto
12656     = Constructor->getType()->getAs<FunctionProtoType>();
12657   assert(Proto && "Constructor without a prototype?");
12658   unsigned NumParams = Proto->getNumParams();
12659 
12660   // If too few arguments are available, we'll fill in the rest with defaults.
12661   if (NumArgs < NumParams)
12662     ConvertedArgs.reserve(NumParams);
12663   else
12664     ConvertedArgs.reserve(NumArgs);
12665 
12666   VariadicCallType CallType =
12667     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12668   SmallVector<Expr *, 8> AllArgs;
12669   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12670                                         Proto, 0,
12671                                         llvm::makeArrayRef(Args, NumArgs),
12672                                         AllArgs,
12673                                         CallType, AllowExplicit,
12674                                         IsListInitialization);
12675   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12676 
12677   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12678 
12679   CheckConstructorCall(Constructor,
12680                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12681                        Proto, Loc);
12682 
12683   return Invalid;
12684 }
12685 
12686 static inline bool
12687 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12688                                        const FunctionDecl *FnDecl) {
12689   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12690   if (isa<NamespaceDecl>(DC)) {
12691     return SemaRef.Diag(FnDecl->getLocation(),
12692                         diag::err_operator_new_delete_declared_in_namespace)
12693       << FnDecl->getDeclName();
12694   }
12695 
12696   if (isa<TranslationUnitDecl>(DC) &&
12697       FnDecl->getStorageClass() == SC_Static) {
12698     return SemaRef.Diag(FnDecl->getLocation(),
12699                         diag::err_operator_new_delete_declared_static)
12700       << FnDecl->getDeclName();
12701   }
12702 
12703   return false;
12704 }
12705 
12706 static inline bool
12707 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12708                             CanQualType ExpectedResultType,
12709                             CanQualType ExpectedFirstParamType,
12710                             unsigned DependentParamTypeDiag,
12711                             unsigned InvalidParamTypeDiag) {
12712   QualType ResultType =
12713       FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12714 
12715   // Check that the result type is not dependent.
12716   if (ResultType->isDependentType())
12717     return SemaRef.Diag(FnDecl->getLocation(),
12718                         diag::err_operator_new_delete_dependent_result_type)
12719     << FnDecl->getDeclName() << ExpectedResultType;
12720 
12721   // Check that the result type is what we expect.
12722   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12723     return SemaRef.Diag(FnDecl->getLocation(),
12724                         diag::err_operator_new_delete_invalid_result_type)
12725     << FnDecl->getDeclName() << ExpectedResultType;
12726 
12727   // A function template must have at least 2 parameters.
12728   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12729     return SemaRef.Diag(FnDecl->getLocation(),
12730                       diag::err_operator_new_delete_template_too_few_parameters)
12731         << FnDecl->getDeclName();
12732 
12733   // The function decl must have at least 1 parameter.
12734   if (FnDecl->getNumParams() == 0)
12735     return SemaRef.Diag(FnDecl->getLocation(),
12736                         diag::err_operator_new_delete_too_few_parameters)
12737       << FnDecl->getDeclName();
12738 
12739   // Check the first parameter type is not dependent.
12740   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12741   if (FirstParamType->isDependentType())
12742     return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12743       << FnDecl->getDeclName() << ExpectedFirstParamType;
12744 
12745   // Check that the first parameter type is what we expect.
12746   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12747       ExpectedFirstParamType)
12748     return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12749     << FnDecl->getDeclName() << ExpectedFirstParamType;
12750 
12751   return false;
12752 }
12753 
12754 static bool
12755 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12756   // C++ [basic.stc.dynamic.allocation]p1:
12757   //   A program is ill-formed if an allocation function is declared in a
12758   //   namespace scope other than global scope or declared static in global
12759   //   scope.
12760   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12761     return true;
12762 
12763   CanQualType SizeTy =
12764     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12765 
12766   // C++ [basic.stc.dynamic.allocation]p1:
12767   //  The return type shall be void*. The first parameter shall have type
12768   //  std::size_t.
12769   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12770                                   SizeTy,
12771                                   diag::err_operator_new_dependent_param_type,
12772                                   diag::err_operator_new_param_type))
12773     return true;
12774 
12775   // C++ [basic.stc.dynamic.allocation]p1:
12776   //  The first parameter shall not have an associated default argument.
12777   if (FnDecl->getParamDecl(0)->hasDefaultArg())
12778     return SemaRef.Diag(FnDecl->getLocation(),
12779                         diag::err_operator_new_default_arg)
12780       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12781 
12782   return false;
12783 }
12784 
12785 static bool
12786 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12787   // C++ [basic.stc.dynamic.deallocation]p1:
12788   //   A program is ill-formed if deallocation functions are declared in a
12789   //   namespace scope other than global scope or declared static in global
12790   //   scope.
12791   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12792     return true;
12793 
12794   // C++ [basic.stc.dynamic.deallocation]p2:
12795   //   Each deallocation function shall return void and its first parameter
12796   //   shall be void*.
12797   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12798                                   SemaRef.Context.VoidPtrTy,
12799                                  diag::err_operator_delete_dependent_param_type,
12800                                  diag::err_operator_delete_param_type))
12801     return true;
12802 
12803   return false;
12804 }
12805 
12806 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12807 /// of this overloaded operator is well-formed. If so, returns false;
12808 /// otherwise, emits appropriate diagnostics and returns true.
12809 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12810   assert(FnDecl && FnDecl->isOverloadedOperator() &&
12811          "Expected an overloaded operator declaration");
12812 
12813   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12814 
12815   // C++ [over.oper]p5:
12816   //   The allocation and deallocation functions, operator new,
12817   //   operator new[], operator delete and operator delete[], are
12818   //   described completely in 3.7.3. The attributes and restrictions
12819   //   found in the rest of this subclause do not apply to them unless
12820   //   explicitly stated in 3.7.3.
12821   if (Op == OO_Delete || Op == OO_Array_Delete)
12822     return CheckOperatorDeleteDeclaration(*this, FnDecl);
12823 
12824   if (Op == OO_New || Op == OO_Array_New)
12825     return CheckOperatorNewDeclaration(*this, FnDecl);
12826 
12827   // C++ [over.oper]p6:
12828   //   An operator function shall either be a non-static member
12829   //   function or be a non-member function and have at least one
12830   //   parameter whose type is a class, a reference to a class, an
12831   //   enumeration, or a reference to an enumeration.
12832   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12833     if (MethodDecl->isStatic())
12834       return Diag(FnDecl->getLocation(),
12835                   diag::err_operator_overload_static) << FnDecl->getDeclName();
12836   } else {
12837     bool ClassOrEnumParam = false;
12838     for (auto Param : FnDecl->parameters()) {
12839       QualType ParamType = Param->getType().getNonReferenceType();
12840       if (ParamType->isDependentType() || ParamType->isRecordType() ||
12841           ParamType->isEnumeralType()) {
12842         ClassOrEnumParam = true;
12843         break;
12844       }
12845     }
12846 
12847     if (!ClassOrEnumParam)
12848       return Diag(FnDecl->getLocation(),
12849                   diag::err_operator_overload_needs_class_or_enum)
12850         << FnDecl->getDeclName();
12851   }
12852 
12853   // C++ [over.oper]p8:
12854   //   An operator function cannot have default arguments (8.3.6),
12855   //   except where explicitly stated below.
12856   //
12857   // Only the function-call operator allows default arguments
12858   // (C++ [over.call]p1).
12859   if (Op != OO_Call) {
12860     for (auto Param : FnDecl->parameters()) {
12861       if (Param->hasDefaultArg())
12862         return Diag(Param->getLocation(),
12863                     diag::err_operator_overload_default_arg)
12864           << FnDecl->getDeclName() << Param->getDefaultArgRange();
12865     }
12866   }
12867 
12868   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12869     { false, false, false }
12870 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12871     , { Unary, Binary, MemberOnly }
12872 #include "clang/Basic/OperatorKinds.def"
12873   };
12874 
12875   bool CanBeUnaryOperator = OperatorUses[Op][0];
12876   bool CanBeBinaryOperator = OperatorUses[Op][1];
12877   bool MustBeMemberOperator = OperatorUses[Op][2];
12878 
12879   // C++ [over.oper]p8:
12880   //   [...] Operator functions cannot have more or fewer parameters
12881   //   than the number required for the corresponding operator, as
12882   //   described in the rest of this subclause.
12883   unsigned NumParams = FnDecl->getNumParams()
12884                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12885   if (Op != OO_Call &&
12886       ((NumParams == 1 && !CanBeUnaryOperator) ||
12887        (NumParams == 2 && !CanBeBinaryOperator) ||
12888        (NumParams < 1) || (NumParams > 2))) {
12889     // We have the wrong number of parameters.
12890     unsigned ErrorKind;
12891     if (CanBeUnaryOperator && CanBeBinaryOperator) {
12892       ErrorKind = 2;  // 2 -> unary or binary.
12893     } else if (CanBeUnaryOperator) {
12894       ErrorKind = 0;  // 0 -> unary
12895     } else {
12896       assert(CanBeBinaryOperator &&
12897              "All non-call overloaded operators are unary or binary!");
12898       ErrorKind = 1;  // 1 -> binary
12899     }
12900 
12901     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12902       << FnDecl->getDeclName() << NumParams << ErrorKind;
12903   }
12904 
12905   // Overloaded operators other than operator() cannot be variadic.
12906   if (Op != OO_Call &&
12907       FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12908     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12909       << FnDecl->getDeclName();
12910   }
12911 
12912   // Some operators must be non-static member functions.
12913   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12914     return Diag(FnDecl->getLocation(),
12915                 diag::err_operator_overload_must_be_member)
12916       << FnDecl->getDeclName();
12917   }
12918 
12919   // C++ [over.inc]p1:
12920   //   The user-defined function called operator++ implements the
12921   //   prefix and postfix ++ operator. If this function is a member
12922   //   function with no parameters, or a non-member function with one
12923   //   parameter of class or enumeration type, it defines the prefix
12924   //   increment operator ++ for objects of that type. If the function
12925   //   is a member function with one parameter (which shall be of type
12926   //   int) or a non-member function with two parameters (the second
12927   //   of which shall be of type int), it defines the postfix
12928   //   increment operator ++ for objects of that type.
12929   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12930     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12931     QualType ParamType = LastParam->getType();
12932 
12933     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12934         !ParamType->isDependentType())
12935       return Diag(LastParam->getLocation(),
12936                   diag::err_operator_overload_post_incdec_must_be_int)
12937         << LastParam->getType() << (Op == OO_MinusMinus);
12938   }
12939 
12940   return false;
12941 }
12942 
12943 static bool
12944 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12945                                           FunctionTemplateDecl *TpDecl) {
12946   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12947 
12948   // Must have one or two template parameters.
12949   if (TemplateParams->size() == 1) {
12950     NonTypeTemplateParmDecl *PmDecl =
12951         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12952 
12953     // The template parameter must be a char parameter pack.
12954     if (PmDecl && PmDecl->isTemplateParameterPack() &&
12955         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12956       return false;
12957 
12958   } else if (TemplateParams->size() == 2) {
12959     TemplateTypeParmDecl *PmType =
12960         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12961     NonTypeTemplateParmDecl *PmArgs =
12962         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12963 
12964     // The second template parameter must be a parameter pack with the
12965     // first template parameter as its type.
12966     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12967         PmArgs->isTemplateParameterPack()) {
12968       const TemplateTypeParmType *TArgs =
12969           PmArgs->getType()->getAs<TemplateTypeParmType>();
12970       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12971           TArgs->getIndex() == PmType->getIndex()) {
12972         if (SemaRef.ActiveTemplateInstantiations.empty())
12973           SemaRef.Diag(TpDecl->getLocation(),
12974                        diag::ext_string_literal_operator_template);
12975         return false;
12976       }
12977     }
12978   }
12979 
12980   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12981                diag::err_literal_operator_template)
12982       << TpDecl->getTemplateParameters()->getSourceRange();
12983   return true;
12984 }
12985 
12986 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12987 /// of this literal operator function is well-formed. If so, returns
12988 /// false; otherwise, emits appropriate diagnostics and returns true.
12989 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12990   if (isa<CXXMethodDecl>(FnDecl)) {
12991     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12992       << FnDecl->getDeclName();
12993     return true;
12994   }
12995 
12996   if (FnDecl->isExternC()) {
12997     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12998     if (const LinkageSpecDecl *LSD =
12999             FnDecl->getDeclContext()->getExternCContext())
13000       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13001     return true;
13002   }
13003 
13004   // This might be the definition of a literal operator template.
13005   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13006 
13007   // This might be a specialization of a literal operator template.
13008   if (!TpDecl)
13009     TpDecl = FnDecl->getPrimaryTemplate();
13010 
13011   // template <char...> type operator "" name() and
13012   // template <class T, T...> type operator "" name() are the only valid
13013   // template signatures, and the only valid signatures with no parameters.
13014   if (TpDecl) {
13015     if (FnDecl->param_size() != 0) {
13016       Diag(FnDecl->getLocation(),
13017            diag::err_literal_operator_template_with_params);
13018       return true;
13019     }
13020 
13021     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13022       return true;
13023 
13024   } else if (FnDecl->param_size() == 1) {
13025     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13026 
13027     QualType ParamType = Param->getType().getUnqualifiedType();
13028 
13029     // Only unsigned long long int, long double, any character type, and const
13030     // char * are allowed as the only parameters.
13031     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13032         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13033         Context.hasSameType(ParamType, Context.CharTy) ||
13034         Context.hasSameType(ParamType, Context.WideCharTy) ||
13035         Context.hasSameType(ParamType, Context.Char16Ty) ||
13036         Context.hasSameType(ParamType, Context.Char32Ty)) {
13037     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13038       QualType InnerType = Ptr->getPointeeType();
13039 
13040       // Pointer parameter must be a const char *.
13041       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13042                                 Context.CharTy) &&
13043             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13044         Diag(Param->getSourceRange().getBegin(),
13045              diag::err_literal_operator_param)
13046             << ParamType << "'const char *'" << Param->getSourceRange();
13047         return true;
13048       }
13049 
13050     } else if (ParamType->isRealFloatingType()) {
13051       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13052           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13053       return true;
13054 
13055     } else if (ParamType->isIntegerType()) {
13056       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13057           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13058       return true;
13059 
13060     } else {
13061       Diag(Param->getSourceRange().getBegin(),
13062            diag::err_literal_operator_invalid_param)
13063           << ParamType << Param->getSourceRange();
13064       return true;
13065     }
13066 
13067   } else if (FnDecl->param_size() == 2) {
13068     FunctionDecl::param_iterator Param = FnDecl->param_begin();
13069 
13070     // First, verify that the first parameter is correct.
13071 
13072     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13073 
13074     // Two parameter function must have a pointer to const as a
13075     // first parameter; let's strip those qualifiers.
13076     const PointerType *PT = FirstParamType->getAs<PointerType>();
13077 
13078     if (!PT) {
13079       Diag((*Param)->getSourceRange().getBegin(),
13080            diag::err_literal_operator_param)
13081           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13082       return true;
13083     }
13084 
13085     QualType PointeeType = PT->getPointeeType();
13086     // First parameter must be const
13087     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13088       Diag((*Param)->getSourceRange().getBegin(),
13089            diag::err_literal_operator_param)
13090           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13091       return true;
13092     }
13093 
13094     QualType InnerType = PointeeType.getUnqualifiedType();
13095     // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
13096     // are allowed as the first parameter to a two-parameter function
13097     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13098           Context.hasSameType(InnerType, Context.WideCharTy) ||
13099           Context.hasSameType(InnerType, Context.Char16Ty) ||
13100           Context.hasSameType(InnerType, Context.Char32Ty))) {
13101       Diag((*Param)->getSourceRange().getBegin(),
13102            diag::err_literal_operator_param)
13103           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13104       return true;
13105     }
13106 
13107     // Move on to the second and final parameter.
13108     ++Param;
13109 
13110     // The second parameter must be a std::size_t.
13111     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13112     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13113       Diag((*Param)->getSourceRange().getBegin(),
13114            diag::err_literal_operator_param)
13115           << SecondParamType << Context.getSizeType()
13116           << (*Param)->getSourceRange();
13117       return true;
13118     }
13119   } else {
13120     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13121     return true;
13122   }
13123 
13124   // Parameters are good.
13125 
13126   // A parameter-declaration-clause containing a default argument is not
13127   // equivalent to any of the permitted forms.
13128   for (auto Param : FnDecl->parameters()) {
13129     if (Param->hasDefaultArg()) {
13130       Diag(Param->getDefaultArgRange().getBegin(),
13131            diag::err_literal_operator_default_argument)
13132         << Param->getDefaultArgRange();
13133       break;
13134     }
13135   }
13136 
13137   StringRef LiteralName
13138     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13139   if (LiteralName[0] != '_') {
13140     // C++11 [usrlit.suffix]p1:
13141     //   Literal suffix identifiers that do not start with an underscore
13142     //   are reserved for future standardization.
13143     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13144       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13145   }
13146 
13147   return false;
13148 }
13149 
13150 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13151 /// linkage specification, including the language and (if present)
13152 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13153 /// language string literal. LBraceLoc, if valid, provides the location of
13154 /// the '{' brace. Otherwise, this linkage specification does not
13155 /// have any braces.
13156 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13157                                            Expr *LangStr,
13158                                            SourceLocation LBraceLoc) {
13159   StringLiteral *Lit = cast<StringLiteral>(LangStr);
13160   if (!Lit->isAscii()) {
13161     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13162       << LangStr->getSourceRange();
13163     return nullptr;
13164   }
13165 
13166   StringRef Lang = Lit->getString();
13167   LinkageSpecDecl::LanguageIDs Language;
13168   if (Lang == "C")
13169     Language = LinkageSpecDecl::lang_c;
13170   else if (Lang == "C++")
13171     Language = LinkageSpecDecl::lang_cxx;
13172   else {
13173     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13174       << LangStr->getSourceRange();
13175     return nullptr;
13176   }
13177 
13178   // FIXME: Add all the various semantics of linkage specifications
13179 
13180   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13181                                                LangStr->getExprLoc(), Language,
13182                                                LBraceLoc.isValid());
13183   CurContext->addDecl(D);
13184   PushDeclContext(S, D);
13185   return D;
13186 }
13187 
13188 /// ActOnFinishLinkageSpecification - Complete the definition of
13189 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13190 /// valid, it's the position of the closing '}' brace in a linkage
13191 /// specification that uses braces.
13192 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13193                                             Decl *LinkageSpec,
13194                                             SourceLocation RBraceLoc) {
13195   if (RBraceLoc.isValid()) {
13196     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13197     LSDecl->setRBraceLoc(RBraceLoc);
13198   }
13199   PopDeclContext();
13200   return LinkageSpec;
13201 }
13202 
13203 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13204                                   AttributeList *AttrList,
13205                                   SourceLocation SemiLoc) {
13206   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13207   // Attribute declarations appertain to empty declaration so we handle
13208   // them here.
13209   if (AttrList)
13210     ProcessDeclAttributeList(S, ED, AttrList);
13211 
13212   CurContext->addDecl(ED);
13213   return ED;
13214 }
13215 
13216 /// \brief Perform semantic analysis for the variable declaration that
13217 /// occurs within a C++ catch clause, returning the newly-created
13218 /// variable.
13219 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13220                                          TypeSourceInfo *TInfo,
13221                                          SourceLocation StartLoc,
13222                                          SourceLocation Loc,
13223                                          IdentifierInfo *Name) {
13224   bool Invalid = false;
13225   QualType ExDeclType = TInfo->getType();
13226 
13227   // Arrays and functions decay.
13228   if (ExDeclType->isArrayType())
13229     ExDeclType = Context.getArrayDecayedType(ExDeclType);
13230   else if (ExDeclType->isFunctionType())
13231     ExDeclType = Context.getPointerType(ExDeclType);
13232 
13233   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13234   // The exception-declaration shall not denote a pointer or reference to an
13235   // incomplete type, other than [cv] void*.
13236   // N2844 forbids rvalue references.
13237   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13238     Diag(Loc, diag::err_catch_rvalue_ref);
13239     Invalid = true;
13240   }
13241 
13242   if (ExDeclType->isVariablyModifiedType()) {
13243     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13244     Invalid = true;
13245   }
13246 
13247   QualType BaseType = ExDeclType;
13248   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13249   unsigned DK = diag::err_catch_incomplete;
13250   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13251     BaseType = Ptr->getPointeeType();
13252     Mode = 1;
13253     DK = diag::err_catch_incomplete_ptr;
13254   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13255     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13256     BaseType = Ref->getPointeeType();
13257     Mode = 2;
13258     DK = diag::err_catch_incomplete_ref;
13259   }
13260   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13261       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13262     Invalid = true;
13263 
13264   if (!Invalid && !ExDeclType->isDependentType() &&
13265       RequireNonAbstractType(Loc, ExDeclType,
13266                              diag::err_abstract_type_in_decl,
13267                              AbstractVariableType))
13268     Invalid = true;
13269 
13270   // Only the non-fragile NeXT runtime currently supports C++ catches
13271   // of ObjC types, and no runtime supports catching ObjC types by value.
13272   if (!Invalid && getLangOpts().ObjC1) {
13273     QualType T = ExDeclType;
13274     if (const ReferenceType *RT = T->getAs<ReferenceType>())
13275       T = RT->getPointeeType();
13276 
13277     if (T->isObjCObjectType()) {
13278       Diag(Loc, diag::err_objc_object_catch);
13279       Invalid = true;
13280     } else if (T->isObjCObjectPointerType()) {
13281       // FIXME: should this be a test for macosx-fragile specifically?
13282       if (getLangOpts().ObjCRuntime.isFragile())
13283         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13284     }
13285   }
13286 
13287   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13288                                     ExDeclType, TInfo, SC_None);
13289   ExDecl->setExceptionVariable(true);
13290 
13291   // In ARC, infer 'retaining' for variables of retainable type.
13292   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13293     Invalid = true;
13294 
13295   if (!Invalid && !ExDeclType->isDependentType()) {
13296     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13297       // Insulate this from anything else we might currently be parsing.
13298       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
13299 
13300       // C++ [except.handle]p16:
13301       //   The object declared in an exception-declaration or, if the
13302       //   exception-declaration does not specify a name, a temporary (12.2) is
13303       //   copy-initialized (8.5) from the exception object. [...]
13304       //   The object is destroyed when the handler exits, after the destruction
13305       //   of any automatic objects initialized within the handler.
13306       //
13307       // We just pretend to initialize the object with itself, then make sure
13308       // it can be destroyed later.
13309       QualType initType = Context.getExceptionObjectType(ExDeclType);
13310 
13311       InitializedEntity entity =
13312         InitializedEntity::InitializeVariable(ExDecl);
13313       InitializationKind initKind =
13314         InitializationKind::CreateCopy(Loc, SourceLocation());
13315 
13316       Expr *opaqueValue =
13317         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13318       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13319       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13320       if (result.isInvalid())
13321         Invalid = true;
13322       else {
13323         // If the constructor used was non-trivial, set this as the
13324         // "initializer".
13325         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13326         if (!construct->getConstructor()->isTrivial()) {
13327           Expr *init = MaybeCreateExprWithCleanups(construct);
13328           ExDecl->setInit(init);
13329         }
13330 
13331         // And make sure it's destructable.
13332         FinalizeVarWithDestructor(ExDecl, recordType);
13333       }
13334     }
13335   }
13336 
13337   if (Invalid)
13338     ExDecl->setInvalidDecl();
13339 
13340   return ExDecl;
13341 }
13342 
13343 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13344 /// handler.
13345 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13346   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13347   bool Invalid = D.isInvalidType();
13348 
13349   // Check for unexpanded parameter packs.
13350   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13351                                       UPPC_ExceptionType)) {
13352     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13353                                              D.getIdentifierLoc());
13354     Invalid = true;
13355   }
13356 
13357   IdentifierInfo *II = D.getIdentifier();
13358   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13359                                              LookupOrdinaryName,
13360                                              ForRedeclaration)) {
13361     // The scope should be freshly made just for us. There is just no way
13362     // it contains any previous declaration, except for function parameters in
13363     // a function-try-block's catch statement.
13364     assert(!S->isDeclScope(PrevDecl));
13365     if (isDeclInScope(PrevDecl, CurContext, S)) {
13366       Diag(D.getIdentifierLoc(), diag::err_redefinition)
13367         << D.getIdentifier();
13368       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13369       Invalid = true;
13370     } else if (PrevDecl->isTemplateParameter())
13371       // Maybe we will complain about the shadowed template parameter.
13372       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13373   }
13374 
13375   if (D.getCXXScopeSpec().isSet() && !Invalid) {
13376     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13377       << D.getCXXScopeSpec().getRange();
13378     Invalid = true;
13379   }
13380 
13381   VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13382                                               D.getLocStart(),
13383                                               D.getIdentifierLoc(),
13384                                               D.getIdentifier());
13385   if (Invalid)
13386     ExDecl->setInvalidDecl();
13387 
13388   // Add the exception declaration into this scope.
13389   if (II)
13390     PushOnScopeChains(ExDecl, S);
13391   else
13392     CurContext->addDecl(ExDecl);
13393 
13394   ProcessDeclAttributes(S, ExDecl, D);
13395   return ExDecl;
13396 }
13397 
13398 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13399                                          Expr *AssertExpr,
13400                                          Expr *AssertMessageExpr,
13401                                          SourceLocation RParenLoc) {
13402   StringLiteral *AssertMessage =
13403       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13404 
13405   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13406     return nullptr;
13407 
13408   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13409                                       AssertMessage, RParenLoc, false);
13410 }
13411 
13412 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13413                                          Expr *AssertExpr,
13414                                          StringLiteral *AssertMessage,
13415                                          SourceLocation RParenLoc,
13416                                          bool Failed) {
13417   assert(AssertExpr != nullptr && "Expected non-null condition");
13418   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13419       !Failed) {
13420     // In a static_assert-declaration, the constant-expression shall be a
13421     // constant expression that can be contextually converted to bool.
13422     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13423     if (Converted.isInvalid())
13424       Failed = true;
13425 
13426     llvm::APSInt Cond;
13427     if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13428           diag::err_static_assert_expression_is_not_constant,
13429           /*AllowFold=*/false).isInvalid())
13430       Failed = true;
13431 
13432     if (!Failed && !Cond) {
13433       SmallString<256> MsgBuffer;
13434       llvm::raw_svector_ostream Msg(MsgBuffer);
13435       if (AssertMessage)
13436         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13437       Diag(StaticAssertLoc, diag::err_static_assert_failed)
13438         << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13439       Failed = true;
13440     }
13441   }
13442 
13443   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13444                                         AssertExpr, AssertMessage, RParenLoc,
13445                                         Failed);
13446 
13447   CurContext->addDecl(Decl);
13448   return Decl;
13449 }
13450 
13451 /// \brief Perform semantic analysis of the given friend type declaration.
13452 ///
13453 /// \returns A friend declaration that.
13454 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13455                                       SourceLocation FriendLoc,
13456                                       TypeSourceInfo *TSInfo) {
13457   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13458 
13459   QualType T = TSInfo->getType();
13460   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13461 
13462   // C++03 [class.friend]p2:
13463   //   An elaborated-type-specifier shall be used in a friend declaration
13464   //   for a class.*
13465   //
13466   //   * The class-key of the elaborated-type-specifier is required.
13467   if (!ActiveTemplateInstantiations.empty()) {
13468     // Do not complain about the form of friend template types during
13469     // template instantiation; we will already have complained when the
13470     // template was declared.
13471   } else {
13472     if (!T->isElaboratedTypeSpecifier()) {
13473       // If we evaluated the type to a record type, suggest putting
13474       // a tag in front.
13475       if (const RecordType *RT = T->getAs<RecordType>()) {
13476         RecordDecl *RD = RT->getDecl();
13477 
13478         SmallString<16> InsertionText(" ");
13479         InsertionText += RD->getKindName();
13480 
13481         Diag(TypeRange.getBegin(),
13482              getLangOpts().CPlusPlus11 ?
13483                diag::warn_cxx98_compat_unelaborated_friend_type :
13484                diag::ext_unelaborated_friend_type)
13485           << (unsigned) RD->getTagKind()
13486           << T
13487           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13488                                         InsertionText);
13489       } else {
13490         Diag(FriendLoc,
13491              getLangOpts().CPlusPlus11 ?
13492                diag::warn_cxx98_compat_nonclass_type_friend :
13493                diag::ext_nonclass_type_friend)
13494           << T
13495           << TypeRange;
13496       }
13497     } else if (T->getAs<EnumType>()) {
13498       Diag(FriendLoc,
13499            getLangOpts().CPlusPlus11 ?
13500              diag::warn_cxx98_compat_enum_friend :
13501              diag::ext_enum_friend)
13502         << T
13503         << TypeRange;
13504     }
13505 
13506     // C++11 [class.friend]p3:
13507     //   A friend declaration that does not declare a function shall have one
13508     //   of the following forms:
13509     //     friend elaborated-type-specifier ;
13510     //     friend simple-type-specifier ;
13511     //     friend typename-specifier ;
13512     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13513       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13514   }
13515 
13516   //   If the type specifier in a friend declaration designates a (possibly
13517   //   cv-qualified) class type, that class is declared as a friend; otherwise,
13518   //   the friend declaration is ignored.
13519   return FriendDecl::Create(Context, CurContext,
13520                             TSInfo->getTypeLoc().getLocStart(), TSInfo,
13521                             FriendLoc);
13522 }
13523 
13524 /// Handle a friend tag declaration where the scope specifier was
13525 /// templated.
13526 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13527                                     unsigned TagSpec, SourceLocation TagLoc,
13528                                     CXXScopeSpec &SS,
13529                                     IdentifierInfo *Name,
13530                                     SourceLocation NameLoc,
13531                                     AttributeList *Attr,
13532                                     MultiTemplateParamsArg TempParamLists) {
13533   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13534 
13535   bool IsMemberSpecialization = false;
13536   bool Invalid = false;
13537 
13538   if (TemplateParameterList *TemplateParams =
13539           MatchTemplateParametersToScopeSpecifier(
13540               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13541               IsMemberSpecialization, Invalid)) {
13542     if (TemplateParams->size() > 0) {
13543       // This is a declaration of a class template.
13544       if (Invalid)
13545         return nullptr;
13546 
13547       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13548                                 NameLoc, Attr, TemplateParams, AS_public,
13549                                 /*ModulePrivateLoc=*/SourceLocation(),
13550                                 FriendLoc, TempParamLists.size() - 1,
13551                                 TempParamLists.data()).get();
13552     } else {
13553       // The "template<>" header is extraneous.
13554       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13555         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13556       IsMemberSpecialization = true;
13557     }
13558   }
13559 
13560   if (Invalid) return nullptr;
13561 
13562   bool isAllExplicitSpecializations = true;
13563   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13564     if (TempParamLists[I]->size()) {
13565       isAllExplicitSpecializations = false;
13566       break;
13567     }
13568   }
13569 
13570   // FIXME: don't ignore attributes.
13571 
13572   // If it's explicit specializations all the way down, just forget
13573   // about the template header and build an appropriate non-templated
13574   // friend.  TODO: for source fidelity, remember the headers.
13575   if (isAllExplicitSpecializations) {
13576     if (SS.isEmpty()) {
13577       bool Owned = false;
13578       bool IsDependent = false;
13579       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13580                       Attr, AS_public,
13581                       /*ModulePrivateLoc=*/SourceLocation(),
13582                       MultiTemplateParamsArg(), Owned, IsDependent,
13583                       /*ScopedEnumKWLoc=*/SourceLocation(),
13584                       /*ScopedEnumUsesClassTag=*/false,
13585                       /*UnderlyingType=*/TypeResult(),
13586                       /*IsTypeSpecifier=*/false);
13587     }
13588 
13589     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13590     ElaboratedTypeKeyword Keyword
13591       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13592     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13593                                    *Name, NameLoc);
13594     if (T.isNull())
13595       return nullptr;
13596 
13597     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13598     if (isa<DependentNameType>(T)) {
13599       DependentNameTypeLoc TL =
13600           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13601       TL.setElaboratedKeywordLoc(TagLoc);
13602       TL.setQualifierLoc(QualifierLoc);
13603       TL.setNameLoc(NameLoc);
13604     } else {
13605       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13606       TL.setElaboratedKeywordLoc(TagLoc);
13607       TL.setQualifierLoc(QualifierLoc);
13608       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13609     }
13610 
13611     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13612                                             TSI, FriendLoc, TempParamLists);
13613     Friend->setAccess(AS_public);
13614     CurContext->addDecl(Friend);
13615     return Friend;
13616   }
13617 
13618   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13619 
13620 
13621 
13622   // Handle the case of a templated-scope friend class.  e.g.
13623   //   template <class T> class A<T>::B;
13624   // FIXME: we don't support these right now.
13625   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13626     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13627   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13628   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13629   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13630   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13631   TL.setElaboratedKeywordLoc(TagLoc);
13632   TL.setQualifierLoc(SS.getWithLocInContext(Context));
13633   TL.setNameLoc(NameLoc);
13634 
13635   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13636                                           TSI, FriendLoc, TempParamLists);
13637   Friend->setAccess(AS_public);
13638   Friend->setUnsupportedFriend(true);
13639   CurContext->addDecl(Friend);
13640   return Friend;
13641 }
13642 
13643 
13644 /// Handle a friend type declaration.  This works in tandem with
13645 /// ActOnTag.
13646 ///
13647 /// Notes on friend class templates:
13648 ///
13649 /// We generally treat friend class declarations as if they were
13650 /// declaring a class.  So, for example, the elaborated type specifier
13651 /// in a friend declaration is required to obey the restrictions of a
13652 /// class-head (i.e. no typedefs in the scope chain), template
13653 /// parameters are required to match up with simple template-ids, &c.
13654 /// However, unlike when declaring a template specialization, it's
13655 /// okay to refer to a template specialization without an empty
13656 /// template parameter declaration, e.g.
13657 ///   friend class A<T>::B<unsigned>;
13658 /// We permit this as a special case; if there are any template
13659 /// parameters present at all, require proper matching, i.e.
13660 ///   template <> template \<class T> friend class A<int>::B;
13661 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13662                                 MultiTemplateParamsArg TempParams) {
13663   SourceLocation Loc = DS.getLocStart();
13664 
13665   assert(DS.isFriendSpecified());
13666   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13667 
13668   // Try to convert the decl specifier to a type.  This works for
13669   // friend templates because ActOnTag never produces a ClassTemplateDecl
13670   // for a TUK_Friend.
13671   Declarator TheDeclarator(DS, Declarator::MemberContext);
13672   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13673   QualType T = TSI->getType();
13674   if (TheDeclarator.isInvalidType())
13675     return nullptr;
13676 
13677   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13678     return nullptr;
13679 
13680   // This is definitely an error in C++98.  It's probably meant to
13681   // be forbidden in C++0x, too, but the specification is just
13682   // poorly written.
13683   //
13684   // The problem is with declarations like the following:
13685   //   template <T> friend A<T>::foo;
13686   // where deciding whether a class C is a friend or not now hinges
13687   // on whether there exists an instantiation of A that causes
13688   // 'foo' to equal C.  There are restrictions on class-heads
13689   // (which we declare (by fiat) elaborated friend declarations to
13690   // be) that makes this tractable.
13691   //
13692   // FIXME: handle "template <> friend class A<T>;", which
13693   // is possibly well-formed?  Who even knows?
13694   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13695     Diag(Loc, diag::err_tagless_friend_type_template)
13696       << DS.getSourceRange();
13697     return nullptr;
13698   }
13699 
13700   // C++98 [class.friend]p1: A friend of a class is a function
13701   //   or class that is not a member of the class . . .
13702   // This is fixed in DR77, which just barely didn't make the C++03
13703   // deadline.  It's also a very silly restriction that seriously
13704   // affects inner classes and which nobody else seems to implement;
13705   // thus we never diagnose it, not even in -pedantic.
13706   //
13707   // But note that we could warn about it: it's always useless to
13708   // friend one of your own members (it's not, however, worthless to
13709   // friend a member of an arbitrary specialization of your template).
13710 
13711   Decl *D;
13712   if (!TempParams.empty())
13713     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13714                                    TempParams,
13715                                    TSI,
13716                                    DS.getFriendSpecLoc());
13717   else
13718     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13719 
13720   if (!D)
13721     return nullptr;
13722 
13723   D->setAccess(AS_public);
13724   CurContext->addDecl(D);
13725 
13726   return D;
13727 }
13728 
13729 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13730                                         MultiTemplateParamsArg TemplateParams) {
13731   const DeclSpec &DS = D.getDeclSpec();
13732 
13733   assert(DS.isFriendSpecified());
13734   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13735 
13736   SourceLocation Loc = D.getIdentifierLoc();
13737   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13738 
13739   // C++ [class.friend]p1
13740   //   A friend of a class is a function or class....
13741   // Note that this sees through typedefs, which is intended.
13742   // It *doesn't* see through dependent types, which is correct
13743   // according to [temp.arg.type]p3:
13744   //   If a declaration acquires a function type through a
13745   //   type dependent on a template-parameter and this causes
13746   //   a declaration that does not use the syntactic form of a
13747   //   function declarator to have a function type, the program
13748   //   is ill-formed.
13749   if (!TInfo->getType()->isFunctionType()) {
13750     Diag(Loc, diag::err_unexpected_friend);
13751 
13752     // It might be worthwhile to try to recover by creating an
13753     // appropriate declaration.
13754     return nullptr;
13755   }
13756 
13757   // C++ [namespace.memdef]p3
13758   //  - If a friend declaration in a non-local class first declares a
13759   //    class or function, the friend class or function is a member
13760   //    of the innermost enclosing namespace.
13761   //  - The name of the friend is not found by simple name lookup
13762   //    until a matching declaration is provided in that namespace
13763   //    scope (either before or after the class declaration granting
13764   //    friendship).
13765   //  - If a friend function is called, its name may be found by the
13766   //    name lookup that considers functions from namespaces and
13767   //    classes associated with the types of the function arguments.
13768   //  - When looking for a prior declaration of a class or a function
13769   //    declared as a friend, scopes outside the innermost enclosing
13770   //    namespace scope are not considered.
13771 
13772   CXXScopeSpec &SS = D.getCXXScopeSpec();
13773   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13774   DeclarationName Name = NameInfo.getName();
13775   assert(Name);
13776 
13777   // Check for unexpanded parameter packs.
13778   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13779       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13780       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13781     return nullptr;
13782 
13783   // The context we found the declaration in, or in which we should
13784   // create the declaration.
13785   DeclContext *DC;
13786   Scope *DCScope = S;
13787   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13788                         ForRedeclaration);
13789 
13790   // There are five cases here.
13791   //   - There's no scope specifier and we're in a local class. Only look
13792   //     for functions declared in the immediately-enclosing block scope.
13793   // We recover from invalid scope qualifiers as if they just weren't there.
13794   FunctionDecl *FunctionContainingLocalClass = nullptr;
13795   if ((SS.isInvalid() || !SS.isSet()) &&
13796       (FunctionContainingLocalClass =
13797            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13798     // C++11 [class.friend]p11:
13799     //   If a friend declaration appears in a local class and the name
13800     //   specified is an unqualified name, a prior declaration is
13801     //   looked up without considering scopes that are outside the
13802     //   innermost enclosing non-class scope. For a friend function
13803     //   declaration, if there is no prior declaration, the program is
13804     //   ill-formed.
13805 
13806     // Find the innermost enclosing non-class scope. This is the block
13807     // scope containing the local class definition (or for a nested class,
13808     // the outer local class).
13809     DCScope = S->getFnParent();
13810 
13811     // Look up the function name in the scope.
13812     Previous.clear(LookupLocalFriendName);
13813     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13814 
13815     if (!Previous.empty()) {
13816       // All possible previous declarations must have the same context:
13817       // either they were declared at block scope or they are members of
13818       // one of the enclosing local classes.
13819       DC = Previous.getRepresentativeDecl()->getDeclContext();
13820     } else {
13821       // This is ill-formed, but provide the context that we would have
13822       // declared the function in, if we were permitted to, for error recovery.
13823       DC = FunctionContainingLocalClass;
13824     }
13825     adjustContextForLocalExternDecl(DC);
13826 
13827     // C++ [class.friend]p6:
13828     //   A function can be defined in a friend declaration of a class if and
13829     //   only if the class is a non-local class (9.8), the function name is
13830     //   unqualified, and the function has namespace scope.
13831     if (D.isFunctionDefinition()) {
13832       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13833     }
13834 
13835   //   - There's no scope specifier, in which case we just go to the
13836   //     appropriate scope and look for a function or function template
13837   //     there as appropriate.
13838   } else if (SS.isInvalid() || !SS.isSet()) {
13839     // C++11 [namespace.memdef]p3:
13840     //   If the name in a friend declaration is neither qualified nor
13841     //   a template-id and the declaration is a function or an
13842     //   elaborated-type-specifier, the lookup to determine whether
13843     //   the entity has been previously declared shall not consider
13844     //   any scopes outside the innermost enclosing namespace.
13845     bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13846 
13847     // Find the appropriate context according to the above.
13848     DC = CurContext;
13849 
13850     // Skip class contexts.  If someone can cite chapter and verse
13851     // for this behavior, that would be nice --- it's what GCC and
13852     // EDG do, and it seems like a reasonable intent, but the spec
13853     // really only says that checks for unqualified existing
13854     // declarations should stop at the nearest enclosing namespace,
13855     // not that they should only consider the nearest enclosing
13856     // namespace.
13857     while (DC->isRecord())
13858       DC = DC->getParent();
13859 
13860     DeclContext *LookupDC = DC;
13861     while (LookupDC->isTransparentContext())
13862       LookupDC = LookupDC->getParent();
13863 
13864     while (true) {
13865       LookupQualifiedName(Previous, LookupDC);
13866 
13867       if (!Previous.empty()) {
13868         DC = LookupDC;
13869         break;
13870       }
13871 
13872       if (isTemplateId) {
13873         if (isa<TranslationUnitDecl>(LookupDC)) break;
13874       } else {
13875         if (LookupDC->isFileContext()) break;
13876       }
13877       LookupDC = LookupDC->getParent();
13878     }
13879 
13880     DCScope = getScopeForDeclContext(S, DC);
13881 
13882   //   - There's a non-dependent scope specifier, in which case we
13883   //     compute it and do a previous lookup there for a function
13884   //     or function template.
13885   } else if (!SS.getScopeRep()->isDependent()) {
13886     DC = computeDeclContext(SS);
13887     if (!DC) return nullptr;
13888 
13889     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13890 
13891     LookupQualifiedName(Previous, DC);
13892 
13893     // Ignore things found implicitly in the wrong scope.
13894     // TODO: better diagnostics for this case.  Suggesting the right
13895     // qualified scope would be nice...
13896     LookupResult::Filter F = Previous.makeFilter();
13897     while (F.hasNext()) {
13898       NamedDecl *D = F.next();
13899       if (!DC->InEnclosingNamespaceSetOf(
13900               D->getDeclContext()->getRedeclContext()))
13901         F.erase();
13902     }
13903     F.done();
13904 
13905     if (Previous.empty()) {
13906       D.setInvalidType();
13907       Diag(Loc, diag::err_qualified_friend_not_found)
13908           << Name << TInfo->getType();
13909       return nullptr;
13910     }
13911 
13912     // C++ [class.friend]p1: A friend of a class is a function or
13913     //   class that is not a member of the class . . .
13914     if (DC->Equals(CurContext))
13915       Diag(DS.getFriendSpecLoc(),
13916            getLangOpts().CPlusPlus11 ?
13917              diag::warn_cxx98_compat_friend_is_member :
13918              diag::err_friend_is_member);
13919 
13920     if (D.isFunctionDefinition()) {
13921       // C++ [class.friend]p6:
13922       //   A function can be defined in a friend declaration of a class if and
13923       //   only if the class is a non-local class (9.8), the function name is
13924       //   unqualified, and the function has namespace scope.
13925       SemaDiagnosticBuilder DB
13926         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13927 
13928       DB << SS.getScopeRep();
13929       if (DC->isFileContext())
13930         DB << FixItHint::CreateRemoval(SS.getRange());
13931       SS.clear();
13932     }
13933 
13934   //   - There's a scope specifier that does not match any template
13935   //     parameter lists, in which case we use some arbitrary context,
13936   //     create a method or method template, and wait for instantiation.
13937   //   - There's a scope specifier that does match some template
13938   //     parameter lists, which we don't handle right now.
13939   } else {
13940     if (D.isFunctionDefinition()) {
13941       // C++ [class.friend]p6:
13942       //   A function can be defined in a friend declaration of a class if and
13943       //   only if the class is a non-local class (9.8), the function name is
13944       //   unqualified, and the function has namespace scope.
13945       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13946         << SS.getScopeRep();
13947     }
13948 
13949     DC = CurContext;
13950     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13951   }
13952 
13953   if (!DC->isRecord()) {
13954     int DiagArg = -1;
13955     switch (D.getName().getKind()) {
13956     case UnqualifiedId::IK_ConstructorTemplateId:
13957     case UnqualifiedId::IK_ConstructorName:
13958       DiagArg = 0;
13959       break;
13960     case UnqualifiedId::IK_DestructorName:
13961       DiagArg = 1;
13962       break;
13963     case UnqualifiedId::IK_ConversionFunctionId:
13964       DiagArg = 2;
13965       break;
13966     case UnqualifiedId::IK_DeductionGuideName:
13967       DiagArg = 3;
13968       break;
13969     case UnqualifiedId::IK_Identifier:
13970     case UnqualifiedId::IK_ImplicitSelfParam:
13971     case UnqualifiedId::IK_LiteralOperatorId:
13972     case UnqualifiedId::IK_OperatorFunctionId:
13973     case UnqualifiedId::IK_TemplateId:
13974       break;
13975     }
13976     // This implies that it has to be an operator or function.
13977     if (DiagArg >= 0) {
13978       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13979       return nullptr;
13980     }
13981   }
13982 
13983   // FIXME: This is an egregious hack to cope with cases where the scope stack
13984   // does not contain the declaration context, i.e., in an out-of-line
13985   // definition of a class.
13986   Scope FakeDCScope(S, Scope::DeclScope, Diags);
13987   if (!DCScope) {
13988     FakeDCScope.setEntity(DC);
13989     DCScope = &FakeDCScope;
13990   }
13991 
13992   bool AddToScope = true;
13993   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13994                                           TemplateParams, AddToScope);
13995   if (!ND) return nullptr;
13996 
13997   assert(ND->getLexicalDeclContext() == CurContext);
13998 
13999   // If we performed typo correction, we might have added a scope specifier
14000   // and changed the decl context.
14001   DC = ND->getDeclContext();
14002 
14003   // Add the function declaration to the appropriate lookup tables,
14004   // adjusting the redeclarations list as necessary.  We don't
14005   // want to do this yet if the friending class is dependent.
14006   //
14007   // Also update the scope-based lookup if the target context's
14008   // lookup context is in lexical scope.
14009   if (!CurContext->isDependentContext()) {
14010     DC = DC->getRedeclContext();
14011     DC->makeDeclVisibleInContext(ND);
14012     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14013       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14014   }
14015 
14016   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14017                                        D.getIdentifierLoc(), ND,
14018                                        DS.getFriendSpecLoc());
14019   FrD->setAccess(AS_public);
14020   CurContext->addDecl(FrD);
14021 
14022   if (ND->isInvalidDecl()) {
14023     FrD->setInvalidDecl();
14024   } else {
14025     if (DC->isRecord()) CheckFriendAccess(ND);
14026 
14027     FunctionDecl *FD;
14028     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14029       FD = FTD->getTemplatedDecl();
14030     else
14031       FD = cast<FunctionDecl>(ND);
14032 
14033     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14034     // default argument expression, that declaration shall be a definition
14035     // and shall be the only declaration of the function or function
14036     // template in the translation unit.
14037     if (functionDeclHasDefaultArgument(FD)) {
14038       // We can't look at FD->getPreviousDecl() because it may not have been set
14039       // if we're in a dependent context. If the function is known to be a
14040       // redeclaration, we will have narrowed Previous down to the right decl.
14041       if (D.isRedeclaration()) {
14042         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14043         Diag(Previous.getRepresentativeDecl()->getLocation(),
14044              diag::note_previous_declaration);
14045       } else if (!D.isFunctionDefinition())
14046         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14047     }
14048 
14049     // Mark templated-scope function declarations as unsupported.
14050     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14051       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14052         << SS.getScopeRep() << SS.getRange()
14053         << cast<CXXRecordDecl>(CurContext);
14054       FrD->setUnsupportedFriend(true);
14055     }
14056   }
14057 
14058   return ND;
14059 }
14060 
14061 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14062   AdjustDeclIfTemplate(Dcl);
14063 
14064   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14065   if (!Fn) {
14066     Diag(DelLoc, diag::err_deleted_non_function);
14067     return;
14068   }
14069 
14070   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14071     // Don't consider the implicit declaration we generate for explicit
14072     // specializations. FIXME: Do not generate these implicit declarations.
14073     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14074          Prev->getPreviousDecl()) &&
14075         !Prev->isDefined()) {
14076       Diag(DelLoc, diag::err_deleted_decl_not_first);
14077       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14078            Prev->isImplicit() ? diag::note_previous_implicit_declaration
14079                               : diag::note_previous_declaration);
14080     }
14081     // If the declaration wasn't the first, we delete the function anyway for
14082     // recovery.
14083     Fn = Fn->getCanonicalDecl();
14084   }
14085 
14086   // dllimport/dllexport cannot be deleted.
14087   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14088     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14089     Fn->setInvalidDecl();
14090   }
14091 
14092   if (Fn->isDeleted())
14093     return;
14094 
14095   // See if we're deleting a function which is already known to override a
14096   // non-deleted virtual function.
14097   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14098     bool IssuedDiagnostic = false;
14099     for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
14100                                         E = MD->end_overridden_methods();
14101          I != E; ++I) {
14102       if (!(*MD->begin_overridden_methods())->isDeleted()) {
14103         if (!IssuedDiagnostic) {
14104           Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14105           IssuedDiagnostic = true;
14106         }
14107         Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
14108       }
14109     }
14110     // If this function was implicitly deleted because it was defaulted,
14111     // explain why it was deleted.
14112     if (IssuedDiagnostic && MD->isDefaulted())
14113       ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14114                                 /*Diagnose*/true);
14115   }
14116 
14117   // C++11 [basic.start.main]p3:
14118   //   A program that defines main as deleted [...] is ill-formed.
14119   if (Fn->isMain())
14120     Diag(DelLoc, diag::err_deleted_main);
14121 
14122   // C++11 [dcl.fct.def.delete]p4:
14123   //  A deleted function is implicitly inline.
14124   Fn->setImplicitlyInline();
14125   Fn->setDeletedAsWritten();
14126 }
14127 
14128 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14129   CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14130 
14131   if (MD) {
14132     if (MD->getParent()->isDependentType()) {
14133       MD->setDefaulted();
14134       MD->setExplicitlyDefaulted();
14135       return;
14136     }
14137 
14138     CXXSpecialMember Member = getSpecialMember(MD);
14139     if (Member == CXXInvalid) {
14140       if (!MD->isInvalidDecl())
14141         Diag(DefaultLoc, diag::err_default_special_members);
14142       return;
14143     }
14144 
14145     MD->setDefaulted();
14146     MD->setExplicitlyDefaulted();
14147 
14148     // If this definition appears within the record, do the checking when
14149     // the record is complete.
14150     const FunctionDecl *Primary = MD;
14151     if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14152       // Ask the template instantiation pattern that actually had the
14153       // '= default' on it.
14154       Primary = Pattern;
14155 
14156     // If the method was defaulted on its first declaration, we will have
14157     // already performed the checking in CheckCompletedCXXClass. Such a
14158     // declaration doesn't trigger an implicit definition.
14159     if (Primary->getCanonicalDecl()->isDefaulted())
14160       return;
14161 
14162     CheckExplicitlyDefaultedSpecialMember(MD);
14163 
14164     if (!MD->isInvalidDecl())
14165       DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14166   } else {
14167     Diag(DefaultLoc, diag::err_default_special_members);
14168   }
14169 }
14170 
14171 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14172   for (Stmt *SubStmt : S->children()) {
14173     if (!SubStmt)
14174       continue;
14175     if (isa<ReturnStmt>(SubStmt))
14176       Self.Diag(SubStmt->getLocStart(),
14177            diag::err_return_in_constructor_handler);
14178     if (!isa<Expr>(SubStmt))
14179       SearchForReturnInStmt(Self, SubStmt);
14180   }
14181 }
14182 
14183 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14184   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14185     CXXCatchStmt *Handler = TryBlock->getHandler(I);
14186     SearchForReturnInStmt(*this, Handler);
14187   }
14188 }
14189 
14190 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14191                                              const CXXMethodDecl *Old) {
14192   const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
14193   const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
14194 
14195   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14196 
14197   // If the calling conventions match, everything is fine
14198   if (NewCC == OldCC)
14199     return false;
14200 
14201   // If the calling conventions mismatch because the new function is static,
14202   // suppress the calling convention mismatch error; the error about static
14203   // function override (err_static_overrides_virtual from
14204   // Sema::CheckFunctionDeclaration) is more clear.
14205   if (New->getStorageClass() == SC_Static)
14206     return false;
14207 
14208   Diag(New->getLocation(),
14209        diag::err_conflicting_overriding_cc_attributes)
14210     << New->getDeclName() << New->getType() << Old->getType();
14211   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14212   return true;
14213 }
14214 
14215 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14216                                              const CXXMethodDecl *Old) {
14217   QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14218   QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14219 
14220   if (Context.hasSameType(NewTy, OldTy) ||
14221       NewTy->isDependentType() || OldTy->isDependentType())
14222     return false;
14223 
14224   // Check if the return types are covariant
14225   QualType NewClassTy, OldClassTy;
14226 
14227   /// Both types must be pointers or references to classes.
14228   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14229     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14230       NewClassTy = NewPT->getPointeeType();
14231       OldClassTy = OldPT->getPointeeType();
14232     }
14233   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14234     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14235       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14236         NewClassTy = NewRT->getPointeeType();
14237         OldClassTy = OldRT->getPointeeType();
14238       }
14239     }
14240   }
14241 
14242   // The return types aren't either both pointers or references to a class type.
14243   if (NewClassTy.isNull()) {
14244     Diag(New->getLocation(),
14245          diag::err_different_return_type_for_overriding_virtual_function)
14246         << New->getDeclName() << NewTy << OldTy
14247         << New->getReturnTypeSourceRange();
14248     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14249         << Old->getReturnTypeSourceRange();
14250 
14251     return true;
14252   }
14253 
14254   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14255     // C++14 [class.virtual]p8:
14256     //   If the class type in the covariant return type of D::f differs from
14257     //   that of B::f, the class type in the return type of D::f shall be
14258     //   complete at the point of declaration of D::f or shall be the class
14259     //   type D.
14260     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14261       if (!RT->isBeingDefined() &&
14262           RequireCompleteType(New->getLocation(), NewClassTy,
14263                               diag::err_covariant_return_incomplete,
14264                               New->getDeclName()))
14265         return true;
14266     }
14267 
14268     // Check if the new class derives from the old class.
14269     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14270       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14271           << New->getDeclName() << NewTy << OldTy
14272           << New->getReturnTypeSourceRange();
14273       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14274           << Old->getReturnTypeSourceRange();
14275       return true;
14276     }
14277 
14278     // Check if we the conversion from derived to base is valid.
14279     if (CheckDerivedToBaseConversion(
14280             NewClassTy, OldClassTy,
14281             diag::err_covariant_return_inaccessible_base,
14282             diag::err_covariant_return_ambiguous_derived_to_base_conv,
14283             New->getLocation(), New->getReturnTypeSourceRange(),
14284             New->getDeclName(), nullptr)) {
14285       // FIXME: this note won't trigger for delayed access control
14286       // diagnostics, and it's impossible to get an undelayed error
14287       // here from access control during the original parse because
14288       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14289       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14290           << Old->getReturnTypeSourceRange();
14291       return true;
14292     }
14293   }
14294 
14295   // The qualifiers of the return types must be the same.
14296   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14297     Diag(New->getLocation(),
14298          diag::err_covariant_return_type_different_qualifications)
14299         << New->getDeclName() << NewTy << OldTy
14300         << New->getReturnTypeSourceRange();
14301     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14302         << Old->getReturnTypeSourceRange();
14303     return true;
14304   }
14305 
14306 
14307   // The new class type must have the same or less qualifiers as the old type.
14308   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14309     Diag(New->getLocation(),
14310          diag::err_covariant_return_type_class_type_more_qualified)
14311         << New->getDeclName() << NewTy << OldTy
14312         << New->getReturnTypeSourceRange();
14313     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14314         << Old->getReturnTypeSourceRange();
14315     return true;
14316   }
14317 
14318   return false;
14319 }
14320 
14321 /// \brief Mark the given method pure.
14322 ///
14323 /// \param Method the method to be marked pure.
14324 ///
14325 /// \param InitRange the source range that covers the "0" initializer.
14326 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14327   SourceLocation EndLoc = InitRange.getEnd();
14328   if (EndLoc.isValid())
14329     Method->setRangeEnd(EndLoc);
14330 
14331   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14332     Method->setPure();
14333     return false;
14334   }
14335 
14336   if (!Method->isInvalidDecl())
14337     Diag(Method->getLocation(), diag::err_non_virtual_pure)
14338       << Method->getDeclName() << InitRange;
14339   return true;
14340 }
14341 
14342 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14343   if (D->getFriendObjectKind())
14344     Diag(D->getLocation(), diag::err_pure_friend);
14345   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14346     CheckPureMethod(M, ZeroLoc);
14347   else
14348     Diag(D->getLocation(), diag::err_illegal_initializer);
14349 }
14350 
14351 /// \brief Determine whether the given declaration is a static data member.
14352 static bool isStaticDataMember(const Decl *D) {
14353   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14354     return Var->isStaticDataMember();
14355 
14356   return false;
14357 }
14358 
14359 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14360 /// an initializer for the out-of-line declaration 'Dcl'.  The scope
14361 /// is a fresh scope pushed for just this purpose.
14362 ///
14363 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14364 /// static data member of class X, names should be looked up in the scope of
14365 /// class X.
14366 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14367   // If there is no declaration, there was an error parsing it.
14368   if (!D || D->isInvalidDecl())
14369     return;
14370 
14371   // We will always have a nested name specifier here, but this declaration
14372   // might not be out of line if the specifier names the current namespace:
14373   //   extern int n;
14374   //   int ::n = 0;
14375   if (D->isOutOfLine())
14376     EnterDeclaratorContext(S, D->getDeclContext());
14377 
14378   // If we are parsing the initializer for a static data member, push a
14379   // new expression evaluation context that is associated with this static
14380   // data member.
14381   if (isStaticDataMember(D))
14382     PushExpressionEvaluationContext(PotentiallyEvaluated, D);
14383 }
14384 
14385 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14386 /// initializer for the out-of-line declaration 'D'.
14387 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14388   // If there is no declaration, there was an error parsing it.
14389   if (!D || D->isInvalidDecl())
14390     return;
14391 
14392   if (isStaticDataMember(D))
14393     PopExpressionEvaluationContext();
14394 
14395   if (D->isOutOfLine())
14396     ExitDeclaratorContext(S);
14397 }
14398 
14399 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14400 /// C++ if/switch/while/for statement.
14401 /// e.g: "if (int x = f()) {...}"
14402 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14403   // C++ 6.4p2:
14404   // The declarator shall not specify a function or an array.
14405   // The type-specifier-seq shall not contain typedef and shall not declare a
14406   // new class or enumeration.
14407   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14408          "Parser allowed 'typedef' as storage class of condition decl.");
14409 
14410   Decl *Dcl = ActOnDeclarator(S, D);
14411   if (!Dcl)
14412     return true;
14413 
14414   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14415     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14416       << D.getSourceRange();
14417     return true;
14418   }
14419 
14420   return Dcl;
14421 }
14422 
14423 void Sema::LoadExternalVTableUses() {
14424   if (!ExternalSource)
14425     return;
14426 
14427   SmallVector<ExternalVTableUse, 4> VTables;
14428   ExternalSource->ReadUsedVTables(VTables);
14429   SmallVector<VTableUse, 4> NewUses;
14430   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14431     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14432       = VTablesUsed.find(VTables[I].Record);
14433     // Even if a definition wasn't required before, it may be required now.
14434     if (Pos != VTablesUsed.end()) {
14435       if (!Pos->second && VTables[I].DefinitionRequired)
14436         Pos->second = true;
14437       continue;
14438     }
14439 
14440     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14441     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14442   }
14443 
14444   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14445 }
14446 
14447 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14448                           bool DefinitionRequired) {
14449   // Ignore any vtable uses in unevaluated operands or for classes that do
14450   // not have a vtable.
14451   if (!Class->isDynamicClass() || Class->isDependentContext() ||
14452       CurContext->isDependentContext() || isUnevaluatedContext())
14453     return;
14454 
14455   // Try to insert this class into the map.
14456   LoadExternalVTableUses();
14457   Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14458   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14459     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14460   if (!Pos.second) {
14461     // If we already had an entry, check to see if we are promoting this vtable
14462     // to require a definition. If so, we need to reappend to the VTableUses
14463     // list, since we may have already processed the first entry.
14464     if (DefinitionRequired && !Pos.first->second) {
14465       Pos.first->second = true;
14466     } else {
14467       // Otherwise, we can early exit.
14468       return;
14469     }
14470   } else {
14471     // The Microsoft ABI requires that we perform the destructor body
14472     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14473     // the deleting destructor is emitted with the vtable, not with the
14474     // destructor definition as in the Itanium ABI.
14475     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14476       CXXDestructorDecl *DD = Class->getDestructor();
14477       if (DD && DD->isVirtual() && !DD->isDeleted()) {
14478         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14479           // If this is an out-of-line declaration, marking it referenced will
14480           // not do anything. Manually call CheckDestructor to look up operator
14481           // delete().
14482           ContextRAII SavedContext(*this, DD);
14483           CheckDestructor(DD);
14484         } else {
14485           MarkFunctionReferenced(Loc, Class->getDestructor());
14486         }
14487       }
14488     }
14489   }
14490 
14491   // Local classes need to have their virtual members marked
14492   // immediately. For all other classes, we mark their virtual members
14493   // at the end of the translation unit.
14494   if (Class->isLocalClass())
14495     MarkVirtualMembersReferenced(Loc, Class);
14496   else
14497     VTableUses.push_back(std::make_pair(Class, Loc));
14498 }
14499 
14500 bool Sema::DefineUsedVTables() {
14501   LoadExternalVTableUses();
14502   if (VTableUses.empty())
14503     return false;
14504 
14505   // Note: The VTableUses vector could grow as a result of marking
14506   // the members of a class as "used", so we check the size each
14507   // time through the loop and prefer indices (which are stable) to
14508   // iterators (which are not).
14509   bool DefinedAnything = false;
14510   for (unsigned I = 0; I != VTableUses.size(); ++I) {
14511     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14512     if (!Class)
14513       continue;
14514     TemplateSpecializationKind ClassTSK =
14515         Class->getTemplateSpecializationKind();
14516 
14517     SourceLocation Loc = VTableUses[I].second;
14518 
14519     bool DefineVTable = true;
14520 
14521     // If this class has a key function, but that key function is
14522     // defined in another translation unit, we don't need to emit the
14523     // vtable even though we're using it.
14524     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14525     if (KeyFunction && !KeyFunction->hasBody()) {
14526       // The key function is in another translation unit.
14527       DefineVTable = false;
14528       TemplateSpecializationKind TSK =
14529           KeyFunction->getTemplateSpecializationKind();
14530       assert(TSK != TSK_ExplicitInstantiationDefinition &&
14531              TSK != TSK_ImplicitInstantiation &&
14532              "Instantiations don't have key functions");
14533       (void)TSK;
14534     } else if (!KeyFunction) {
14535       // If we have a class with no key function that is the subject
14536       // of an explicit instantiation declaration, suppress the
14537       // vtable; it will live with the explicit instantiation
14538       // definition.
14539       bool IsExplicitInstantiationDeclaration =
14540           ClassTSK == TSK_ExplicitInstantiationDeclaration;
14541       for (auto R : Class->redecls()) {
14542         TemplateSpecializationKind TSK
14543           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14544         if (TSK == TSK_ExplicitInstantiationDeclaration)
14545           IsExplicitInstantiationDeclaration = true;
14546         else if (TSK == TSK_ExplicitInstantiationDefinition) {
14547           IsExplicitInstantiationDeclaration = false;
14548           break;
14549         }
14550       }
14551 
14552       if (IsExplicitInstantiationDeclaration)
14553         DefineVTable = false;
14554     }
14555 
14556     // The exception specifications for all virtual members may be needed even
14557     // if we are not providing an authoritative form of the vtable in this TU.
14558     // We may choose to emit it available_externally anyway.
14559     if (!DefineVTable) {
14560       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14561       continue;
14562     }
14563 
14564     // Mark all of the virtual members of this class as referenced, so
14565     // that we can build a vtable. Then, tell the AST consumer that a
14566     // vtable for this class is required.
14567     DefinedAnything = true;
14568     MarkVirtualMembersReferenced(Loc, Class);
14569     CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14570     if (VTablesUsed[Canonical])
14571       Consumer.HandleVTable(Class);
14572 
14573     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14574     // no key function or the key function is inlined. Don't warn in C++ ABIs
14575     // that lack key functions, since the user won't be able to make one.
14576     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14577         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14578       const FunctionDecl *KeyFunctionDef = nullptr;
14579       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14580                            KeyFunctionDef->isInlined())) {
14581         Diag(Class->getLocation(),
14582              ClassTSK == TSK_ExplicitInstantiationDefinition
14583                  ? diag::warn_weak_template_vtable
14584                  : diag::warn_weak_vtable)
14585             << Class;
14586       }
14587     }
14588   }
14589   VTableUses.clear();
14590 
14591   return DefinedAnything;
14592 }
14593 
14594 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14595                                                  const CXXRecordDecl *RD) {
14596   for (const auto *I : RD->methods())
14597     if (I->isVirtual() && !I->isPure())
14598       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14599 }
14600 
14601 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14602                                         const CXXRecordDecl *RD) {
14603   // Mark all functions which will appear in RD's vtable as used.
14604   CXXFinalOverriderMap FinalOverriders;
14605   RD->getFinalOverriders(FinalOverriders);
14606   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14607                                             E = FinalOverriders.end();
14608        I != E; ++I) {
14609     for (OverridingMethods::const_iterator OI = I->second.begin(),
14610                                            OE = I->second.end();
14611          OI != OE; ++OI) {
14612       assert(OI->second.size() > 0 && "no final overrider");
14613       CXXMethodDecl *Overrider = OI->second.front().Method;
14614 
14615       // C++ [basic.def.odr]p2:
14616       //   [...] A virtual member function is used if it is not pure. [...]
14617       if (!Overrider->isPure())
14618         MarkFunctionReferenced(Loc, Overrider);
14619     }
14620   }
14621 
14622   // Only classes that have virtual bases need a VTT.
14623   if (RD->getNumVBases() == 0)
14624     return;
14625 
14626   for (const auto &I : RD->bases()) {
14627     const CXXRecordDecl *Base =
14628         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14629     if (Base->getNumVBases() == 0)
14630       continue;
14631     MarkVirtualMembersReferenced(Loc, Base);
14632   }
14633 }
14634 
14635 /// SetIvarInitializers - This routine builds initialization ASTs for the
14636 /// Objective-C implementation whose ivars need be initialized.
14637 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14638   if (!getLangOpts().CPlusPlus)
14639     return;
14640   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14641     SmallVector<ObjCIvarDecl*, 8> ivars;
14642     CollectIvarsToConstructOrDestruct(OID, ivars);
14643     if (ivars.empty())
14644       return;
14645     SmallVector<CXXCtorInitializer*, 32> AllToInit;
14646     for (unsigned i = 0; i < ivars.size(); i++) {
14647       FieldDecl *Field = ivars[i];
14648       if (Field->isInvalidDecl())
14649         continue;
14650 
14651       CXXCtorInitializer *Member;
14652       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14653       InitializationKind InitKind =
14654         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14655 
14656       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14657       ExprResult MemberInit =
14658         InitSeq.Perform(*this, InitEntity, InitKind, None);
14659       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14660       // Note, MemberInit could actually come back empty if no initialization
14661       // is required (e.g., because it would call a trivial default constructor)
14662       if (!MemberInit.get() || MemberInit.isInvalid())
14663         continue;
14664 
14665       Member =
14666         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14667                                          SourceLocation(),
14668                                          MemberInit.getAs<Expr>(),
14669                                          SourceLocation());
14670       AllToInit.push_back(Member);
14671 
14672       // Be sure that the destructor is accessible and is marked as referenced.
14673       if (const RecordType *RecordTy =
14674               Context.getBaseElementType(Field->getType())
14675                   ->getAs<RecordType>()) {
14676         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14677         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14678           MarkFunctionReferenced(Field->getLocation(), Destructor);
14679           CheckDestructorAccess(Field->getLocation(), Destructor,
14680                             PDiag(diag::err_access_dtor_ivar)
14681                               << Context.getBaseElementType(Field->getType()));
14682         }
14683       }
14684     }
14685     ObjCImplementation->setIvarInitializers(Context,
14686                                             AllToInit.data(), AllToInit.size());
14687   }
14688 }
14689 
14690 static
14691 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14692                            llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14693                            llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14694                            llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14695                            Sema &S) {
14696   if (Ctor->isInvalidDecl())
14697     return;
14698 
14699   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14700 
14701   // Target may not be determinable yet, for instance if this is a dependent
14702   // call in an uninstantiated template.
14703   if (Target) {
14704     const FunctionDecl *FNTarget = nullptr;
14705     (void)Target->hasBody(FNTarget);
14706     Target = const_cast<CXXConstructorDecl*>(
14707       cast_or_null<CXXConstructorDecl>(FNTarget));
14708   }
14709 
14710   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14711                      // Avoid dereferencing a null pointer here.
14712                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14713 
14714   if (!Current.insert(Canonical).second)
14715     return;
14716 
14717   // We know that beyond here, we aren't chaining into a cycle.
14718   if (!Target || !Target->isDelegatingConstructor() ||
14719       Target->isInvalidDecl() || Valid.count(TCanonical)) {
14720     Valid.insert(Current.begin(), Current.end());
14721     Current.clear();
14722   // We've hit a cycle.
14723   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14724              Current.count(TCanonical)) {
14725     // If we haven't diagnosed this cycle yet, do so now.
14726     if (!Invalid.count(TCanonical)) {
14727       S.Diag((*Ctor->init_begin())->getSourceLocation(),
14728              diag::warn_delegating_ctor_cycle)
14729         << Ctor;
14730 
14731       // Don't add a note for a function delegating directly to itself.
14732       if (TCanonical != Canonical)
14733         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14734 
14735       CXXConstructorDecl *C = Target;
14736       while (C->getCanonicalDecl() != Canonical) {
14737         const FunctionDecl *FNTarget = nullptr;
14738         (void)C->getTargetConstructor()->hasBody(FNTarget);
14739         assert(FNTarget && "Ctor cycle through bodiless function");
14740 
14741         C = const_cast<CXXConstructorDecl*>(
14742           cast<CXXConstructorDecl>(FNTarget));
14743         S.Diag(C->getLocation(), diag::note_which_delegates_to);
14744       }
14745     }
14746 
14747     Invalid.insert(Current.begin(), Current.end());
14748     Current.clear();
14749   } else {
14750     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14751   }
14752 }
14753 
14754 
14755 void Sema::CheckDelegatingCtorCycles() {
14756   llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14757 
14758   for (DelegatingCtorDeclsType::iterator
14759          I = DelegatingCtorDecls.begin(ExternalSource),
14760          E = DelegatingCtorDecls.end();
14761        I != E; ++I)
14762     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14763 
14764   for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14765                                                          CE = Invalid.end();
14766        CI != CE; ++CI)
14767     (*CI)->setInvalidDecl();
14768 }
14769 
14770 namespace {
14771   /// \brief AST visitor that finds references to the 'this' expression.
14772   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14773     Sema &S;
14774 
14775   public:
14776     explicit FindCXXThisExpr(Sema &S) : S(S) { }
14777 
14778     bool VisitCXXThisExpr(CXXThisExpr *E) {
14779       S.Diag(E->getLocation(), diag::err_this_static_member_func)
14780         << E->isImplicit();
14781       return false;
14782     }
14783   };
14784 }
14785 
14786 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14787   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14788   if (!TSInfo)
14789     return false;
14790 
14791   TypeLoc TL = TSInfo->getTypeLoc();
14792   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14793   if (!ProtoTL)
14794     return false;
14795 
14796   // C++11 [expr.prim.general]p3:
14797   //   [The expression this] shall not appear before the optional
14798   //   cv-qualifier-seq and it shall not appear within the declaration of a
14799   //   static member function (although its type and value category are defined
14800   //   within a static member function as they are within a non-static member
14801   //   function). [ Note: this is because declaration matching does not occur
14802   //  until the complete declarator is known. - end note ]
14803   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14804   FindCXXThisExpr Finder(*this);
14805 
14806   // If the return type came after the cv-qualifier-seq, check it now.
14807   if (Proto->hasTrailingReturn() &&
14808       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14809     return true;
14810 
14811   // Check the exception specification.
14812   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14813     return true;
14814 
14815   return checkThisInStaticMemberFunctionAttributes(Method);
14816 }
14817 
14818 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14819   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14820   if (!TSInfo)
14821     return false;
14822 
14823   TypeLoc TL = TSInfo->getTypeLoc();
14824   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14825   if (!ProtoTL)
14826     return false;
14827 
14828   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14829   FindCXXThisExpr Finder(*this);
14830 
14831   switch (Proto->getExceptionSpecType()) {
14832   case EST_Unparsed:
14833   case EST_Uninstantiated:
14834   case EST_Unevaluated:
14835   case EST_BasicNoexcept:
14836   case EST_DynamicNone:
14837   case EST_MSAny:
14838   case EST_None:
14839     break;
14840 
14841   case EST_ComputedNoexcept:
14842     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14843       return true;
14844 
14845   case EST_Dynamic:
14846     for (const auto &E : Proto->exceptions()) {
14847       if (!Finder.TraverseType(E))
14848         return true;
14849     }
14850     break;
14851   }
14852 
14853   return false;
14854 }
14855 
14856 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14857   FindCXXThisExpr Finder(*this);
14858 
14859   // Check attributes.
14860   for (const auto *A : Method->attrs()) {
14861     // FIXME: This should be emitted by tblgen.
14862     Expr *Arg = nullptr;
14863     ArrayRef<Expr *> Args;
14864     if (const auto *G = dyn_cast<GuardedByAttr>(A))
14865       Arg = G->getArg();
14866     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14867       Arg = G->getArg();
14868     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14869       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14870     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14871       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14872     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14873       Arg = ETLF->getSuccessValue();
14874       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14875     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14876       Arg = STLF->getSuccessValue();
14877       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14878     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14879       Arg = LR->getArg();
14880     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14881       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14882     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14883       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14884     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14885       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14886     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14887       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14888     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14889       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14890 
14891     if (Arg && !Finder.TraverseStmt(Arg))
14892       return true;
14893 
14894     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14895       if (!Finder.TraverseStmt(Args[I]))
14896         return true;
14897     }
14898   }
14899 
14900   return false;
14901 }
14902 
14903 void Sema::checkExceptionSpecification(
14904     bool IsTopLevel, ExceptionSpecificationType EST,
14905     ArrayRef<ParsedType> DynamicExceptions,
14906     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14907     SmallVectorImpl<QualType> &Exceptions,
14908     FunctionProtoType::ExceptionSpecInfo &ESI) {
14909   Exceptions.clear();
14910   ESI.Type = EST;
14911   if (EST == EST_Dynamic) {
14912     Exceptions.reserve(DynamicExceptions.size());
14913     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14914       // FIXME: Preserve type source info.
14915       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14916 
14917       if (IsTopLevel) {
14918         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14919         collectUnexpandedParameterPacks(ET, Unexpanded);
14920         if (!Unexpanded.empty()) {
14921           DiagnoseUnexpandedParameterPacks(
14922               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14923               Unexpanded);
14924           continue;
14925         }
14926       }
14927 
14928       // Check that the type is valid for an exception spec, and
14929       // drop it if not.
14930       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14931         Exceptions.push_back(ET);
14932     }
14933     ESI.Exceptions = Exceptions;
14934     return;
14935   }
14936 
14937   if (EST == EST_ComputedNoexcept) {
14938     // If an error occurred, there's no expression here.
14939     if (NoexceptExpr) {
14940       assert((NoexceptExpr->isTypeDependent() ||
14941               NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14942               Context.BoolTy) &&
14943              "Parser should have made sure that the expression is boolean");
14944       if (IsTopLevel && NoexceptExpr &&
14945           DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14946         ESI.Type = EST_BasicNoexcept;
14947         return;
14948       }
14949 
14950       if (!NoexceptExpr->isValueDependent())
14951         NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14952                          diag::err_noexcept_needs_constant_expression,
14953                          /*AllowFold*/ false).get();
14954       ESI.NoexceptExpr = NoexceptExpr;
14955     }
14956     return;
14957   }
14958 }
14959 
14960 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14961              ExceptionSpecificationType EST,
14962              SourceRange SpecificationRange,
14963              ArrayRef<ParsedType> DynamicExceptions,
14964              ArrayRef<SourceRange> DynamicExceptionRanges,
14965              Expr *NoexceptExpr) {
14966   if (!MethodD)
14967     return;
14968 
14969   // Dig out the method we're referring to.
14970   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14971     MethodD = FunTmpl->getTemplatedDecl();
14972 
14973   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14974   if (!Method)
14975     return;
14976 
14977   // Check the exception specification.
14978   llvm::SmallVector<QualType, 4> Exceptions;
14979   FunctionProtoType::ExceptionSpecInfo ESI;
14980   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14981                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
14982                               ESI);
14983 
14984   // Update the exception specification on the function type.
14985   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14986 
14987   if (Method->isStatic())
14988     checkThisInStaticMemberFunctionExceptionSpec(Method);
14989 
14990   if (Method->isVirtual()) {
14991     // Check overrides, which we previously had to delay.
14992     for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14993                                      OEnd = Method->end_overridden_methods();
14994          O != OEnd; ++O)
14995       CheckOverridingFunctionExceptionSpec(Method, *O);
14996   }
14997 }
14998 
14999 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15000 ///
15001 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15002                                        SourceLocation DeclStart,
15003                                        Declarator &D, Expr *BitWidth,
15004                                        InClassInitStyle InitStyle,
15005                                        AccessSpecifier AS,
15006                                        AttributeList *MSPropertyAttr) {
15007   IdentifierInfo *II = D.getIdentifier();
15008   if (!II) {
15009     Diag(DeclStart, diag::err_anonymous_property);
15010     return nullptr;
15011   }
15012   SourceLocation Loc = D.getIdentifierLoc();
15013 
15014   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15015   QualType T = TInfo->getType();
15016   if (getLangOpts().CPlusPlus) {
15017     CheckExtraCXXDefaultArguments(D);
15018 
15019     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15020                                         UPPC_DataMemberType)) {
15021       D.setInvalidType();
15022       T = Context.IntTy;
15023       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15024     }
15025   }
15026 
15027   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15028 
15029   if (D.getDeclSpec().isInlineSpecified())
15030     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15031         << getLangOpts().CPlusPlus1z;
15032   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15033     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15034          diag::err_invalid_thread)
15035       << DeclSpec::getSpecifierName(TSCS);
15036 
15037   // Check to see if this name was declared as a member previously
15038   NamedDecl *PrevDecl = nullptr;
15039   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
15040   LookupName(Previous, S);
15041   switch (Previous.getResultKind()) {
15042   case LookupResult::Found:
15043   case LookupResult::FoundUnresolvedValue:
15044     PrevDecl = Previous.getAsSingle<NamedDecl>();
15045     break;
15046 
15047   case LookupResult::FoundOverloaded:
15048     PrevDecl = Previous.getRepresentativeDecl();
15049     break;
15050 
15051   case LookupResult::NotFound:
15052   case LookupResult::NotFoundInCurrentInstantiation:
15053   case LookupResult::Ambiguous:
15054     break;
15055   }
15056 
15057   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15058     // Maybe we will complain about the shadowed template parameter.
15059     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15060     // Just pretend that we didn't see the previous declaration.
15061     PrevDecl = nullptr;
15062   }
15063 
15064   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15065     PrevDecl = nullptr;
15066 
15067   SourceLocation TSSL = D.getLocStart();
15068   const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
15069   MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15070       Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15071   ProcessDeclAttributes(TUScope, NewPD, D);
15072   NewPD->setAccess(AS);
15073 
15074   if (NewPD->isInvalidDecl())
15075     Record->setInvalidDecl();
15076 
15077   if (D.getDeclSpec().isModulePrivateSpecified())
15078     NewPD->setModulePrivate();
15079 
15080   if (NewPD->isInvalidDecl() && PrevDecl) {
15081     // Don't introduce NewFD into scope; there's already something
15082     // with the same name in the same scope.
15083   } else if (II) {
15084     PushOnScopeChains(NewPD, S);
15085   } else
15086     Record->addDecl(NewPD);
15087 
15088   return NewPD;
15089 }
15090